PackageManagerService.java revision 53d52c8fbf814154aaa0d4209efefd4f6cb2f465
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.getDefaultCompilerFilter;
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
540    public static final int REASON_LAST = REASON_AB_OTA;
541
542    /** All dangerous permission names in the same order as the events in MetricsEvent */
543    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
544            Manifest.permission.READ_CALENDAR,
545            Manifest.permission.WRITE_CALENDAR,
546            Manifest.permission.CAMERA,
547            Manifest.permission.READ_CONTACTS,
548            Manifest.permission.WRITE_CONTACTS,
549            Manifest.permission.GET_ACCOUNTS,
550            Manifest.permission.ACCESS_FINE_LOCATION,
551            Manifest.permission.ACCESS_COARSE_LOCATION,
552            Manifest.permission.RECORD_AUDIO,
553            Manifest.permission.READ_PHONE_STATE,
554            Manifest.permission.CALL_PHONE,
555            Manifest.permission.READ_CALL_LOG,
556            Manifest.permission.WRITE_CALL_LOG,
557            Manifest.permission.ADD_VOICEMAIL,
558            Manifest.permission.USE_SIP,
559            Manifest.permission.PROCESS_OUTGOING_CALLS,
560            Manifest.permission.READ_CELL_BROADCASTS,
561            Manifest.permission.BODY_SENSORS,
562            Manifest.permission.SEND_SMS,
563            Manifest.permission.RECEIVE_SMS,
564            Manifest.permission.READ_SMS,
565            Manifest.permission.RECEIVE_WAP_PUSH,
566            Manifest.permission.RECEIVE_MMS,
567            Manifest.permission.READ_EXTERNAL_STORAGE,
568            Manifest.permission.WRITE_EXTERNAL_STORAGE,
569            Manifest.permission.READ_PHONE_NUMBERS,
570            Manifest.permission.ANSWER_PHONE_CALLS);
571
572
573    /**
574     * Version number for the package parser cache. Increment this whenever the format or
575     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
576     */
577    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
578
579    /**
580     * Whether the package parser cache is enabled.
581     */
582    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
583
584    final ServiceThread mHandlerThread;
585
586    final PackageHandler mHandler;
587
588    private final ProcessLoggingHandler mProcessLoggingHandler;
589
590    /**
591     * Messages for {@link #mHandler} that need to wait for system ready before
592     * being dispatched.
593     */
594    private ArrayList<Message> mPostSystemReadyMessages;
595
596    final int mSdkVersion = Build.VERSION.SDK_INT;
597
598    final Context mContext;
599    final boolean mFactoryTest;
600    final boolean mOnlyCore;
601    final DisplayMetrics mMetrics;
602    final int mDefParseFlags;
603    final String[] mSeparateProcesses;
604    final boolean mIsUpgrade;
605    final boolean mIsPreNUpgrade;
606    final boolean mIsPreNMR1Upgrade;
607
608    // Have we told the Activity Manager to whitelist the default container service by uid yet?
609    @GuardedBy("mPackages")
610    boolean mDefaultContainerWhitelisted = false;
611
612    @GuardedBy("mPackages")
613    private boolean mDexOptDialogShown;
614
615    /** The location for ASEC container files on internal storage. */
616    final String mAsecInternalPath;
617
618    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
619    // LOCK HELD.  Can be called with mInstallLock held.
620    @GuardedBy("mInstallLock")
621    final Installer mInstaller;
622
623    /** Directory where installed third-party apps stored */
624    final File mAppInstallDir;
625
626    /**
627     * Directory to which applications installed internally have their
628     * 32 bit native libraries copied.
629     */
630    private File mAppLib32InstallDir;
631
632    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
633    // apps.
634    final File mDrmAppPrivateInstallDir;
635
636    // ----------------------------------------------------------------
637
638    // Lock for state used when installing and doing other long running
639    // operations.  Methods that must be called with this lock held have
640    // the suffix "LI".
641    final Object mInstallLock = new Object();
642
643    // ----------------------------------------------------------------
644
645    // Keys are String (package name), values are Package.  This also serves
646    // as the lock for the global state.  Methods that must be called with
647    // this lock held have the prefix "LP".
648    @GuardedBy("mPackages")
649    final ArrayMap<String, PackageParser.Package> mPackages =
650            new ArrayMap<String, PackageParser.Package>();
651
652    final ArrayMap<String, Set<String>> mKnownCodebase =
653            new ArrayMap<String, Set<String>>();
654
655    // Keys are isolated uids and values are the uid of the application
656    // that created the isolated proccess.
657    @GuardedBy("mPackages")
658    final SparseIntArray mIsolatedOwners = new SparseIntArray();
659
660    // List of APK paths to load for each user and package. This data is never
661    // persisted by the package manager. Instead, the overlay manager will
662    // ensure the data is up-to-date in runtime.
663    @GuardedBy("mPackages")
664    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
665        new SparseArray<ArrayMap<String, ArrayList<String>>>();
666
667    /**
668     * Tracks new system packages [received in an OTA] that we expect to
669     * find updated user-installed versions. Keys are package name, values
670     * are package location.
671     */
672    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
673    /**
674     * Tracks high priority intent filters for protected actions. During boot, certain
675     * filter actions are protected and should never be allowed to have a high priority
676     * intent filter for them. However, there is one, and only one exception -- the
677     * setup wizard. It must be able to define a high priority intent filter for these
678     * actions to ensure there are no escapes from the wizard. We need to delay processing
679     * of these during boot as we need to look at all of the system packages in order
680     * to know which component is the setup wizard.
681     */
682    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
683    /**
684     * Whether or not processing protected filters should be deferred.
685     */
686    private boolean mDeferProtectedFilters = true;
687
688    /**
689     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
690     */
691    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
692    /**
693     * Whether or not system app permissions should be promoted from install to runtime.
694     */
695    boolean mPromoteSystemApps;
696
697    @GuardedBy("mPackages")
698    final Settings mSettings;
699
700    /**
701     * Set of package names that are currently "frozen", which means active
702     * surgery is being done on the code/data for that package. The platform
703     * will refuse to launch frozen packages to avoid race conditions.
704     *
705     * @see PackageFreezer
706     */
707    @GuardedBy("mPackages")
708    final ArraySet<String> mFrozenPackages = new ArraySet<>();
709
710    final ProtectedPackages mProtectedPackages;
711
712    boolean mFirstBoot;
713
714    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
715
716    // System configuration read by SystemConfig.
717    final int[] mGlobalGids;
718    final SparseArray<ArraySet<String>> mSystemPermissions;
719    @GuardedBy("mAvailableFeatures")
720    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
721
722    // If mac_permissions.xml was found for seinfo labeling.
723    boolean mFoundPolicyFile;
724
725    private final InstantAppRegistry mInstantAppRegistry;
726
727    @GuardedBy("mPackages")
728    int mChangedPackagesSequenceNumber;
729    /**
730     * List of changed [installed, removed or updated] packages.
731     * mapping from user id -> sequence number -> package name
732     */
733    @GuardedBy("mPackages")
734    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
735    /**
736     * The sequence number of the last change to a package.
737     * mapping from user id -> package name -> sequence number
738     */
739    @GuardedBy("mPackages")
740    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
741
742    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
743        @Override public boolean hasFeature(String feature) {
744            return PackageManagerService.this.hasSystemFeature(feature, 0);
745        }
746    };
747
748    public static final class SharedLibraryEntry {
749        public final String path;
750        public final String apk;
751        public final SharedLibraryInfo info;
752
753        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
754                String declaringPackageName, int declaringPackageVersionCode) {
755            path = _path;
756            apk = _apk;
757            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
758                    declaringPackageName, declaringPackageVersionCode), null);
759        }
760    }
761
762    // Currently known shared libraries.
763    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
764    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
765            new ArrayMap<>();
766
767    // All available activities, for your resolving pleasure.
768    final ActivityIntentResolver mActivities =
769            new ActivityIntentResolver();
770
771    // All available receivers, for your resolving pleasure.
772    final ActivityIntentResolver mReceivers =
773            new ActivityIntentResolver();
774
775    // All available services, for your resolving pleasure.
776    final ServiceIntentResolver mServices = new ServiceIntentResolver();
777
778    // All available providers, for your resolving pleasure.
779    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
780
781    // Mapping from provider base names (first directory in content URI codePath)
782    // to the provider information.
783    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
784            new ArrayMap<String, PackageParser.Provider>();
785
786    // Mapping from instrumentation class names to info about them.
787    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
788            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
789
790    // Mapping from permission names to info about them.
791    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
792            new ArrayMap<String, PackageParser.PermissionGroup>();
793
794    // Packages whose data we have transfered into another package, thus
795    // should no longer exist.
796    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
797
798    // Broadcast actions that are only available to the system.
799    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
800
801    /** List of packages waiting for verification. */
802    final SparseArray<PackageVerificationState> mPendingVerification
803            = new SparseArray<PackageVerificationState>();
804
805    /** Set of packages associated with each app op permission. */
806    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
807
808    final PackageInstallerService mInstallerService;
809
810    private final PackageDexOptimizer mPackageDexOptimizer;
811    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
812    // is used by other apps).
813    private final DexManager mDexManager;
814
815    private AtomicInteger mNextMoveId = new AtomicInteger();
816    private final MoveCallbacks mMoveCallbacks;
817
818    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
819
820    // Cache of users who need badging.
821    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
822
823    /** Token for keys in mPendingVerification. */
824    private int mPendingVerificationToken = 0;
825
826    volatile boolean mSystemReady;
827    volatile boolean mSafeMode;
828    volatile boolean mHasSystemUidErrors;
829    private volatile boolean mEphemeralAppsDisabled;
830
831    ApplicationInfo mAndroidApplication;
832    final ActivityInfo mResolveActivity = new ActivityInfo();
833    final ResolveInfo mResolveInfo = new ResolveInfo();
834    ComponentName mResolveComponentName;
835    PackageParser.Package mPlatformPackage;
836    ComponentName mCustomResolverComponentName;
837
838    boolean mResolverReplaced = false;
839
840    private final @Nullable ComponentName mIntentFilterVerifierComponent;
841    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
842
843    private int mIntentFilterVerificationToken = 0;
844
845    /** The service connection to the ephemeral resolver */
846    final EphemeralResolverConnection mInstantAppResolverConnection;
847    /** Component used to show resolver settings for Instant Apps */
848    final ComponentName mInstantAppResolverSettingsComponent;
849
850    /** Activity used to install instant applications */
851    ActivityInfo mInstantAppInstallerActivity;
852    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
853
854    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
855            = new SparseArray<IntentFilterVerificationState>();
856
857    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
858
859    // List of packages names to keep cached, even if they are uninstalled for all users
860    private List<String> mKeepUninstalledPackages;
861
862    private UserManagerInternal mUserManagerInternal;
863
864    private DeviceIdleController.LocalService mDeviceIdleController;
865
866    private File mCacheDir;
867
868    private ArraySet<String> mPrivappPermissionsViolations;
869
870    private Future<?> mPrepareAppDataFuture;
871
872    private static class IFVerificationParams {
873        PackageParser.Package pkg;
874        boolean replacing;
875        int userId;
876        int verifierUid;
877
878        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
879                int _userId, int _verifierUid) {
880            pkg = _pkg;
881            replacing = _replacing;
882            userId = _userId;
883            replacing = _replacing;
884            verifierUid = _verifierUid;
885        }
886    }
887
888    private interface IntentFilterVerifier<T extends IntentFilter> {
889        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
890                                               T filter, String packageName);
891        void startVerifications(int userId);
892        void receiveVerificationResponse(int verificationId);
893    }
894
895    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
896        private Context mContext;
897        private ComponentName mIntentFilterVerifierComponent;
898        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
899
900        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
901            mContext = context;
902            mIntentFilterVerifierComponent = verifierComponent;
903        }
904
905        private String getDefaultScheme() {
906            return IntentFilter.SCHEME_HTTPS;
907        }
908
909        @Override
910        public void startVerifications(int userId) {
911            // Launch verifications requests
912            int count = mCurrentIntentFilterVerifications.size();
913            for (int n=0; n<count; n++) {
914                int verificationId = mCurrentIntentFilterVerifications.get(n);
915                final IntentFilterVerificationState ivs =
916                        mIntentFilterVerificationStates.get(verificationId);
917
918                String packageName = ivs.getPackageName();
919
920                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
921                final int filterCount = filters.size();
922                ArraySet<String> domainsSet = new ArraySet<>();
923                for (int m=0; m<filterCount; m++) {
924                    PackageParser.ActivityIntentInfo filter = filters.get(m);
925                    domainsSet.addAll(filter.getHostsList());
926                }
927                synchronized (mPackages) {
928                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
929                            packageName, domainsSet) != null) {
930                        scheduleWriteSettingsLocked();
931                    }
932                }
933                sendVerificationRequest(userId, verificationId, ivs);
934            }
935            mCurrentIntentFilterVerifications.clear();
936        }
937
938        private void sendVerificationRequest(int userId, int verificationId,
939                IntentFilterVerificationState ivs) {
940
941            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
942            verificationIntent.putExtra(
943                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
944                    verificationId);
945            verificationIntent.putExtra(
946                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
947                    getDefaultScheme());
948            verificationIntent.putExtra(
949                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
950                    ivs.getHostsString());
951            verificationIntent.putExtra(
952                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
953                    ivs.getPackageName());
954            verificationIntent.setComponent(mIntentFilterVerifierComponent);
955            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
956
957            DeviceIdleController.LocalService idleController = getDeviceIdleController();
958            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
959                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
960                    userId, false, "intent filter verifier");
961
962            UserHandle user = new UserHandle(userId);
963            mContext.sendBroadcastAsUser(verificationIntent, user);
964            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
965                    "Sending IntentFilter verification broadcast");
966        }
967
968        public void receiveVerificationResponse(int verificationId) {
969            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
970
971            final boolean verified = ivs.isVerified();
972
973            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
974            final int count = filters.size();
975            if (DEBUG_DOMAIN_VERIFICATION) {
976                Slog.i(TAG, "Received verification response " + verificationId
977                        + " for " + count + " filters, verified=" + verified);
978            }
979            for (int n=0; n<count; n++) {
980                PackageParser.ActivityIntentInfo filter = filters.get(n);
981                filter.setVerified(verified);
982
983                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
984                        + " verified with result:" + verified + " and hosts:"
985                        + ivs.getHostsString());
986            }
987
988            mIntentFilterVerificationStates.remove(verificationId);
989
990            final String packageName = ivs.getPackageName();
991            IntentFilterVerificationInfo ivi = null;
992
993            synchronized (mPackages) {
994                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
995            }
996            if (ivi == null) {
997                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
998                        + verificationId + " packageName:" + packageName);
999                return;
1000            }
1001            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1002                    "Updating IntentFilterVerificationInfo for package " + packageName
1003                            +" verificationId:" + verificationId);
1004
1005            synchronized (mPackages) {
1006                if (verified) {
1007                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1008                } else {
1009                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1010                }
1011                scheduleWriteSettingsLocked();
1012
1013                final int userId = ivs.getUserId();
1014                if (userId != UserHandle.USER_ALL) {
1015                    final int userStatus =
1016                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1017
1018                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1019                    boolean needUpdate = false;
1020
1021                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1022                    // already been set by the User thru the Disambiguation dialog
1023                    switch (userStatus) {
1024                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1025                            if (verified) {
1026                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1027                            } else {
1028                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1029                            }
1030                            needUpdate = true;
1031                            break;
1032
1033                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1034                            if (verified) {
1035                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1036                                needUpdate = true;
1037                            }
1038                            break;
1039
1040                        default:
1041                            // Nothing to do
1042                    }
1043
1044                    if (needUpdate) {
1045                        mSettings.updateIntentFilterVerificationStatusLPw(
1046                                packageName, updatedStatus, userId);
1047                        scheduleWritePackageRestrictionsLocked(userId);
1048                    }
1049                }
1050            }
1051        }
1052
1053        @Override
1054        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1055                    ActivityIntentInfo filter, String packageName) {
1056            if (!hasValidDomains(filter)) {
1057                return false;
1058            }
1059            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1060            if (ivs == null) {
1061                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1062                        packageName);
1063            }
1064            if (DEBUG_DOMAIN_VERIFICATION) {
1065                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1066            }
1067            ivs.addFilter(filter);
1068            return true;
1069        }
1070
1071        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1072                int userId, int verificationId, String packageName) {
1073            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1074                    verifierUid, userId, packageName);
1075            ivs.setPendingState();
1076            synchronized (mPackages) {
1077                mIntentFilterVerificationStates.append(verificationId, ivs);
1078                mCurrentIntentFilterVerifications.add(verificationId);
1079            }
1080            return ivs;
1081        }
1082    }
1083
1084    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1085        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1086                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1087                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1088    }
1089
1090    // Set of pending broadcasts for aggregating enable/disable of components.
1091    static class PendingPackageBroadcasts {
1092        // for each user id, a map of <package name -> components within that package>
1093        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1094
1095        public PendingPackageBroadcasts() {
1096            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1097        }
1098
1099        public ArrayList<String> get(int userId, String packageName) {
1100            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1101            return packages.get(packageName);
1102        }
1103
1104        public void put(int userId, String packageName, ArrayList<String> components) {
1105            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1106            packages.put(packageName, components);
1107        }
1108
1109        public void remove(int userId, String packageName) {
1110            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1111            if (packages != null) {
1112                packages.remove(packageName);
1113            }
1114        }
1115
1116        public void remove(int userId) {
1117            mUidMap.remove(userId);
1118        }
1119
1120        public int userIdCount() {
1121            return mUidMap.size();
1122        }
1123
1124        public int userIdAt(int n) {
1125            return mUidMap.keyAt(n);
1126        }
1127
1128        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1129            return mUidMap.get(userId);
1130        }
1131
1132        public int size() {
1133            // total number of pending broadcast entries across all userIds
1134            int num = 0;
1135            for (int i = 0; i< mUidMap.size(); i++) {
1136                num += mUidMap.valueAt(i).size();
1137            }
1138            return num;
1139        }
1140
1141        public void clear() {
1142            mUidMap.clear();
1143        }
1144
1145        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1146            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1147            if (map == null) {
1148                map = new ArrayMap<String, ArrayList<String>>();
1149                mUidMap.put(userId, map);
1150            }
1151            return map;
1152        }
1153    }
1154    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1155
1156    // Service Connection to remote media container service to copy
1157    // package uri's from external media onto secure containers
1158    // or internal storage.
1159    private IMediaContainerService mContainerService = null;
1160
1161    static final int SEND_PENDING_BROADCAST = 1;
1162    static final int MCS_BOUND = 3;
1163    static final int END_COPY = 4;
1164    static final int INIT_COPY = 5;
1165    static final int MCS_UNBIND = 6;
1166    static final int START_CLEANING_PACKAGE = 7;
1167    static final int FIND_INSTALL_LOC = 8;
1168    static final int POST_INSTALL = 9;
1169    static final int MCS_RECONNECT = 10;
1170    static final int MCS_GIVE_UP = 11;
1171    static final int UPDATED_MEDIA_STATUS = 12;
1172    static final int WRITE_SETTINGS = 13;
1173    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1174    static final int PACKAGE_VERIFIED = 15;
1175    static final int CHECK_PENDING_VERIFICATION = 16;
1176    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1177    static final int INTENT_FILTER_VERIFIED = 18;
1178    static final int WRITE_PACKAGE_LIST = 19;
1179    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1180
1181    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1182
1183    // Delay time in millisecs
1184    static final int BROADCAST_DELAY = 10 * 1000;
1185
1186    static UserManagerService sUserManager;
1187
1188    // Stores a list of users whose package restrictions file needs to be updated
1189    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1190
1191    final private DefaultContainerConnection mDefContainerConn =
1192            new DefaultContainerConnection();
1193    class DefaultContainerConnection implements ServiceConnection {
1194        public void onServiceConnected(ComponentName name, IBinder service) {
1195            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1196            final IMediaContainerService imcs = IMediaContainerService.Stub
1197                    .asInterface(Binder.allowBlocking(service));
1198            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1199        }
1200
1201        public void onServiceDisconnected(ComponentName name) {
1202            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1203        }
1204    }
1205
1206    // Recordkeeping of restore-after-install operations that are currently in flight
1207    // between the Package Manager and the Backup Manager
1208    static class PostInstallData {
1209        public InstallArgs args;
1210        public PackageInstalledInfo res;
1211
1212        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1213            args = _a;
1214            res = _r;
1215        }
1216    }
1217
1218    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1219    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1220
1221    // XML tags for backup/restore of various bits of state
1222    private static final String TAG_PREFERRED_BACKUP = "pa";
1223    private static final String TAG_DEFAULT_APPS = "da";
1224    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1225
1226    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1227    private static final String TAG_ALL_GRANTS = "rt-grants";
1228    private static final String TAG_GRANT = "grant";
1229    private static final String ATTR_PACKAGE_NAME = "pkg";
1230
1231    private static final String TAG_PERMISSION = "perm";
1232    private static final String ATTR_PERMISSION_NAME = "name";
1233    private static final String ATTR_IS_GRANTED = "g";
1234    private static final String ATTR_USER_SET = "set";
1235    private static final String ATTR_USER_FIXED = "fixed";
1236    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1237
1238    // System/policy permission grants are not backed up
1239    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1240            FLAG_PERMISSION_POLICY_FIXED
1241            | FLAG_PERMISSION_SYSTEM_FIXED
1242            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1243
1244    // And we back up these user-adjusted states
1245    private static final int USER_RUNTIME_GRANT_MASK =
1246            FLAG_PERMISSION_USER_SET
1247            | FLAG_PERMISSION_USER_FIXED
1248            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1249
1250    final @Nullable String mRequiredVerifierPackage;
1251    final @NonNull String mRequiredInstallerPackage;
1252    final @NonNull String mRequiredUninstallerPackage;
1253    final @Nullable String mSetupWizardPackage;
1254    final @Nullable String mStorageManagerPackage;
1255    final @NonNull String mServicesSystemSharedLibraryPackageName;
1256    final @NonNull String mSharedSystemSharedLibraryPackageName;
1257
1258    final boolean mPermissionReviewRequired;
1259
1260    private final PackageUsage mPackageUsage = new PackageUsage();
1261    private final CompilerStats mCompilerStats = new CompilerStats();
1262
1263    class PackageHandler extends Handler {
1264        private boolean mBound = false;
1265        final ArrayList<HandlerParams> mPendingInstalls =
1266            new ArrayList<HandlerParams>();
1267
1268        private boolean connectToService() {
1269            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1270                    " DefaultContainerService");
1271            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1272            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1273            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1274                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1275                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1276                mBound = true;
1277                return true;
1278            }
1279            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1280            return false;
1281        }
1282
1283        private void disconnectService() {
1284            mContainerService = null;
1285            mBound = false;
1286            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1287            mContext.unbindService(mDefContainerConn);
1288            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1289        }
1290
1291        PackageHandler(Looper looper) {
1292            super(looper);
1293        }
1294
1295        public void handleMessage(Message msg) {
1296            try {
1297                doHandleMessage(msg);
1298            } finally {
1299                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1300            }
1301        }
1302
1303        void doHandleMessage(Message msg) {
1304            switch (msg.what) {
1305                case INIT_COPY: {
1306                    HandlerParams params = (HandlerParams) msg.obj;
1307                    int idx = mPendingInstalls.size();
1308                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1309                    // If a bind was already initiated we dont really
1310                    // need to do anything. The pending install
1311                    // will be processed later on.
1312                    if (!mBound) {
1313                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1314                                System.identityHashCode(mHandler));
1315                        // If this is the only one pending we might
1316                        // have to bind to the service again.
1317                        if (!connectToService()) {
1318                            Slog.e(TAG, "Failed to bind to media container service");
1319                            params.serviceError();
1320                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1321                                    System.identityHashCode(mHandler));
1322                            if (params.traceMethod != null) {
1323                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1324                                        params.traceCookie);
1325                            }
1326                            return;
1327                        } else {
1328                            // Once we bind to the service, the first
1329                            // pending request will be processed.
1330                            mPendingInstalls.add(idx, params);
1331                        }
1332                    } else {
1333                        mPendingInstalls.add(idx, params);
1334                        // Already bound to the service. Just make
1335                        // sure we trigger off processing the first request.
1336                        if (idx == 0) {
1337                            mHandler.sendEmptyMessage(MCS_BOUND);
1338                        }
1339                    }
1340                    break;
1341                }
1342                case MCS_BOUND: {
1343                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1344                    if (msg.obj != null) {
1345                        mContainerService = (IMediaContainerService) msg.obj;
1346                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1347                                System.identityHashCode(mHandler));
1348                    }
1349                    if (mContainerService == null) {
1350                        if (!mBound) {
1351                            // Something seriously wrong since we are not bound and we are not
1352                            // waiting for connection. Bail out.
1353                            Slog.e(TAG, "Cannot bind to media container service");
1354                            for (HandlerParams params : mPendingInstalls) {
1355                                // Indicate service bind error
1356                                params.serviceError();
1357                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1358                                        System.identityHashCode(params));
1359                                if (params.traceMethod != null) {
1360                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1361                                            params.traceMethod, params.traceCookie);
1362                                }
1363                                return;
1364                            }
1365                            mPendingInstalls.clear();
1366                        } else {
1367                            Slog.w(TAG, "Waiting to connect to media container service");
1368                        }
1369                    } else if (mPendingInstalls.size() > 0) {
1370                        HandlerParams params = mPendingInstalls.get(0);
1371                        if (params != null) {
1372                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1373                                    System.identityHashCode(params));
1374                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1375                            if (params.startCopy()) {
1376                                // We are done...  look for more work or to
1377                                // go idle.
1378                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1379                                        "Checking for more work or unbind...");
1380                                // Delete pending install
1381                                if (mPendingInstalls.size() > 0) {
1382                                    mPendingInstalls.remove(0);
1383                                }
1384                                if (mPendingInstalls.size() == 0) {
1385                                    if (mBound) {
1386                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1387                                                "Posting delayed MCS_UNBIND");
1388                                        removeMessages(MCS_UNBIND);
1389                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1390                                        // Unbind after a little delay, to avoid
1391                                        // continual thrashing.
1392                                        sendMessageDelayed(ubmsg, 10000);
1393                                    }
1394                                } else {
1395                                    // There are more pending requests in queue.
1396                                    // Just post MCS_BOUND message to trigger processing
1397                                    // of next pending install.
1398                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1399                                            "Posting MCS_BOUND for next work");
1400                                    mHandler.sendEmptyMessage(MCS_BOUND);
1401                                }
1402                            }
1403                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1404                        }
1405                    } else {
1406                        // Should never happen ideally.
1407                        Slog.w(TAG, "Empty queue");
1408                    }
1409                    break;
1410                }
1411                case MCS_RECONNECT: {
1412                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1413                    if (mPendingInstalls.size() > 0) {
1414                        if (mBound) {
1415                            disconnectService();
1416                        }
1417                        if (!connectToService()) {
1418                            Slog.e(TAG, "Failed to bind to media container service");
1419                            for (HandlerParams params : mPendingInstalls) {
1420                                // Indicate service bind error
1421                                params.serviceError();
1422                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1423                                        System.identityHashCode(params));
1424                            }
1425                            mPendingInstalls.clear();
1426                        }
1427                    }
1428                    break;
1429                }
1430                case MCS_UNBIND: {
1431                    // If there is no actual work left, then time to unbind.
1432                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1433
1434                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1435                        if (mBound) {
1436                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1437
1438                            disconnectService();
1439                        }
1440                    } else if (mPendingInstalls.size() > 0) {
1441                        // There are more pending requests in queue.
1442                        // Just post MCS_BOUND message to trigger processing
1443                        // of next pending install.
1444                        mHandler.sendEmptyMessage(MCS_BOUND);
1445                    }
1446
1447                    break;
1448                }
1449                case MCS_GIVE_UP: {
1450                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1451                    HandlerParams params = mPendingInstalls.remove(0);
1452                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1453                            System.identityHashCode(params));
1454                    break;
1455                }
1456                case SEND_PENDING_BROADCAST: {
1457                    String packages[];
1458                    ArrayList<String> components[];
1459                    int size = 0;
1460                    int uids[];
1461                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1462                    synchronized (mPackages) {
1463                        if (mPendingBroadcasts == null) {
1464                            return;
1465                        }
1466                        size = mPendingBroadcasts.size();
1467                        if (size <= 0) {
1468                            // Nothing to be done. Just return
1469                            return;
1470                        }
1471                        packages = new String[size];
1472                        components = new ArrayList[size];
1473                        uids = new int[size];
1474                        int i = 0;  // filling out the above arrays
1475
1476                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1477                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1478                            Iterator<Map.Entry<String, ArrayList<String>>> it
1479                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1480                                            .entrySet().iterator();
1481                            while (it.hasNext() && i < size) {
1482                                Map.Entry<String, ArrayList<String>> ent = it.next();
1483                                packages[i] = ent.getKey();
1484                                components[i] = ent.getValue();
1485                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1486                                uids[i] = (ps != null)
1487                                        ? UserHandle.getUid(packageUserId, ps.appId)
1488                                        : -1;
1489                                i++;
1490                            }
1491                        }
1492                        size = i;
1493                        mPendingBroadcasts.clear();
1494                    }
1495                    // Send broadcasts
1496                    for (int i = 0; i < size; i++) {
1497                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1498                    }
1499                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1500                    break;
1501                }
1502                case START_CLEANING_PACKAGE: {
1503                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1504                    final String packageName = (String)msg.obj;
1505                    final int userId = msg.arg1;
1506                    final boolean andCode = msg.arg2 != 0;
1507                    synchronized (mPackages) {
1508                        if (userId == UserHandle.USER_ALL) {
1509                            int[] users = sUserManager.getUserIds();
1510                            for (int user : users) {
1511                                mSettings.addPackageToCleanLPw(
1512                                        new PackageCleanItem(user, packageName, andCode));
1513                            }
1514                        } else {
1515                            mSettings.addPackageToCleanLPw(
1516                                    new PackageCleanItem(userId, packageName, andCode));
1517                        }
1518                    }
1519                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1520                    startCleaningPackages();
1521                } break;
1522                case POST_INSTALL: {
1523                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1524
1525                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1526                    final boolean didRestore = (msg.arg2 != 0);
1527                    mRunningInstalls.delete(msg.arg1);
1528
1529                    if (data != null) {
1530                        InstallArgs args = data.args;
1531                        PackageInstalledInfo parentRes = data.res;
1532
1533                        final boolean grantPermissions = (args.installFlags
1534                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1535                        final boolean killApp = (args.installFlags
1536                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1537                        final String[] grantedPermissions = args.installGrantPermissions;
1538
1539                        // Handle the parent package
1540                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1541                                grantedPermissions, didRestore, args.installerPackageName,
1542                                args.observer);
1543
1544                        // Handle the child packages
1545                        final int childCount = (parentRes.addedChildPackages != null)
1546                                ? parentRes.addedChildPackages.size() : 0;
1547                        for (int i = 0; i < childCount; i++) {
1548                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1549                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1550                                    grantedPermissions, false, args.installerPackageName,
1551                                    args.observer);
1552                        }
1553
1554                        // Log tracing if needed
1555                        if (args.traceMethod != null) {
1556                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1557                                    args.traceCookie);
1558                        }
1559                    } else {
1560                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1561                    }
1562
1563                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1564                } break;
1565                case UPDATED_MEDIA_STATUS: {
1566                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1567                    boolean reportStatus = msg.arg1 == 1;
1568                    boolean doGc = msg.arg2 == 1;
1569                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1570                    if (doGc) {
1571                        // Force a gc to clear up stale containers.
1572                        Runtime.getRuntime().gc();
1573                    }
1574                    if (msg.obj != null) {
1575                        @SuppressWarnings("unchecked")
1576                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1577                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1578                        // Unload containers
1579                        unloadAllContainers(args);
1580                    }
1581                    if (reportStatus) {
1582                        try {
1583                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1584                                    "Invoking StorageManagerService call back");
1585                            PackageHelper.getStorageManager().finishMediaUpdate();
1586                        } catch (RemoteException e) {
1587                            Log.e(TAG, "StorageManagerService not running?");
1588                        }
1589                    }
1590                } break;
1591                case WRITE_SETTINGS: {
1592                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1593                    synchronized (mPackages) {
1594                        removeMessages(WRITE_SETTINGS);
1595                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1596                        mSettings.writeLPr();
1597                        mDirtyUsers.clear();
1598                    }
1599                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1600                } break;
1601                case WRITE_PACKAGE_RESTRICTIONS: {
1602                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1603                    synchronized (mPackages) {
1604                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1605                        for (int userId : mDirtyUsers) {
1606                            mSettings.writePackageRestrictionsLPr(userId);
1607                        }
1608                        mDirtyUsers.clear();
1609                    }
1610                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1611                } break;
1612                case WRITE_PACKAGE_LIST: {
1613                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1614                    synchronized (mPackages) {
1615                        removeMessages(WRITE_PACKAGE_LIST);
1616                        mSettings.writePackageListLPr(msg.arg1);
1617                    }
1618                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1619                } break;
1620                case CHECK_PENDING_VERIFICATION: {
1621                    final int verificationId = msg.arg1;
1622                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1623
1624                    if ((state != null) && !state.timeoutExtended()) {
1625                        final InstallArgs args = state.getInstallArgs();
1626                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1627
1628                        Slog.i(TAG, "Verification timed out for " + originUri);
1629                        mPendingVerification.remove(verificationId);
1630
1631                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1632
1633                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1634                            Slog.i(TAG, "Continuing with installation of " + originUri);
1635                            state.setVerifierResponse(Binder.getCallingUid(),
1636                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1637                            broadcastPackageVerified(verificationId, originUri,
1638                                    PackageManager.VERIFICATION_ALLOW,
1639                                    state.getInstallArgs().getUser());
1640                            try {
1641                                ret = args.copyApk(mContainerService, true);
1642                            } catch (RemoteException e) {
1643                                Slog.e(TAG, "Could not contact the ContainerService");
1644                            }
1645                        } else {
1646                            broadcastPackageVerified(verificationId, originUri,
1647                                    PackageManager.VERIFICATION_REJECT,
1648                                    state.getInstallArgs().getUser());
1649                        }
1650
1651                        Trace.asyncTraceEnd(
1652                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1653
1654                        processPendingInstall(args, ret);
1655                        mHandler.sendEmptyMessage(MCS_UNBIND);
1656                    }
1657                    break;
1658                }
1659                case PACKAGE_VERIFIED: {
1660                    final int verificationId = msg.arg1;
1661
1662                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1663                    if (state == null) {
1664                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1665                        break;
1666                    }
1667
1668                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1669
1670                    state.setVerifierResponse(response.callerUid, response.code);
1671
1672                    if (state.isVerificationComplete()) {
1673                        mPendingVerification.remove(verificationId);
1674
1675                        final InstallArgs args = state.getInstallArgs();
1676                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1677
1678                        int ret;
1679                        if (state.isInstallAllowed()) {
1680                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1681                            broadcastPackageVerified(verificationId, originUri,
1682                                    response.code, state.getInstallArgs().getUser());
1683                            try {
1684                                ret = args.copyApk(mContainerService, true);
1685                            } catch (RemoteException e) {
1686                                Slog.e(TAG, "Could not contact the ContainerService");
1687                            }
1688                        } else {
1689                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1690                        }
1691
1692                        Trace.asyncTraceEnd(
1693                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1694
1695                        processPendingInstall(args, ret);
1696                        mHandler.sendEmptyMessage(MCS_UNBIND);
1697                    }
1698
1699                    break;
1700                }
1701                case START_INTENT_FILTER_VERIFICATIONS: {
1702                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1703                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1704                            params.replacing, params.pkg);
1705                    break;
1706                }
1707                case INTENT_FILTER_VERIFIED: {
1708                    final int verificationId = msg.arg1;
1709
1710                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1711                            verificationId);
1712                    if (state == null) {
1713                        Slog.w(TAG, "Invalid IntentFilter verification token "
1714                                + verificationId + " received");
1715                        break;
1716                    }
1717
1718                    final int userId = state.getUserId();
1719
1720                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1721                            "Processing IntentFilter verification with token:"
1722                            + verificationId + " and userId:" + userId);
1723
1724                    final IntentFilterVerificationResponse response =
1725                            (IntentFilterVerificationResponse) msg.obj;
1726
1727                    state.setVerifierResponse(response.callerUid, response.code);
1728
1729                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1730                            "IntentFilter verification with token:" + verificationId
1731                            + " and userId:" + userId
1732                            + " is settings verifier response with response code:"
1733                            + response.code);
1734
1735                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1736                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1737                                + response.getFailedDomainsString());
1738                    }
1739
1740                    if (state.isVerificationComplete()) {
1741                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1742                    } else {
1743                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1744                                "IntentFilter verification with token:" + verificationId
1745                                + " was not said to be complete");
1746                    }
1747
1748                    break;
1749                }
1750                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1751                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1752                            mInstantAppResolverConnection,
1753                            (InstantAppRequest) msg.obj,
1754                            mInstantAppInstallerActivity,
1755                            mHandler);
1756                }
1757            }
1758        }
1759    }
1760
1761    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1762            boolean killApp, String[] grantedPermissions,
1763            boolean launchedForRestore, String installerPackage,
1764            IPackageInstallObserver2 installObserver) {
1765        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1766            // Send the removed broadcasts
1767            if (res.removedInfo != null) {
1768                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1769            }
1770
1771            // Now that we successfully installed the package, grant runtime
1772            // permissions if requested before broadcasting the install. Also
1773            // for legacy apps in permission review mode we clear the permission
1774            // review flag which is used to emulate runtime permissions for
1775            // legacy apps.
1776            if (grantPermissions) {
1777                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1778            }
1779
1780            final boolean update = res.removedInfo != null
1781                    && res.removedInfo.removedPackage != null;
1782            final String origInstallerPackageName = res.removedInfo != null
1783                    ? res.removedInfo.installerPackageName : null;
1784
1785            // If this is the first time we have child packages for a disabled privileged
1786            // app that had no children, we grant requested runtime permissions to the new
1787            // children if the parent on the system image had them already granted.
1788            if (res.pkg.parentPackage != null) {
1789                synchronized (mPackages) {
1790                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1791                }
1792            }
1793
1794            synchronized (mPackages) {
1795                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1796            }
1797
1798            final String packageName = res.pkg.applicationInfo.packageName;
1799
1800            // Determine the set of users who are adding this package for
1801            // the first time vs. those who are seeing an update.
1802            int[] firstUsers = EMPTY_INT_ARRAY;
1803            int[] updateUsers = EMPTY_INT_ARRAY;
1804            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1805            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1806            for (int newUser : res.newUsers) {
1807                if (ps.getInstantApp(newUser)) {
1808                    continue;
1809                }
1810                if (allNewUsers) {
1811                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1812                    continue;
1813                }
1814                boolean isNew = true;
1815                for (int origUser : res.origUsers) {
1816                    if (origUser == newUser) {
1817                        isNew = false;
1818                        break;
1819                    }
1820                }
1821                if (isNew) {
1822                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1823                } else {
1824                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1825                }
1826            }
1827
1828            // Send installed broadcasts if the package is not a static shared lib.
1829            if (res.pkg.staticSharedLibName == null) {
1830                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1831
1832                // Send added for users that see the package for the first time
1833                // sendPackageAddedForNewUsers also deals with system apps
1834                int appId = UserHandle.getAppId(res.uid);
1835                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1836                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1837
1838                // Send added for users that don't see the package for the first time
1839                Bundle extras = new Bundle(1);
1840                extras.putInt(Intent.EXTRA_UID, res.uid);
1841                if (update) {
1842                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1843                }
1844                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1845                        extras, 0 /*flags*/,
1846                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1847                if (origInstallerPackageName != null) {
1848                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1849                            extras, 0 /*flags*/,
1850                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1851                }
1852
1853                // Send replaced for users that don't see the package for the first time
1854                if (update) {
1855                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1856                            packageName, extras, 0 /*flags*/,
1857                            null /*targetPackage*/, null /*finishedReceiver*/,
1858                            updateUsers);
1859                    if (origInstallerPackageName != null) {
1860                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1861                                extras, 0 /*flags*/,
1862                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1863                    }
1864                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1865                            null /*package*/, null /*extras*/, 0 /*flags*/,
1866                            packageName /*targetPackage*/,
1867                            null /*finishedReceiver*/, updateUsers);
1868                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1869                    // First-install and we did a restore, so we're responsible for the
1870                    // first-launch broadcast.
1871                    if (DEBUG_BACKUP) {
1872                        Slog.i(TAG, "Post-restore of " + packageName
1873                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1874                    }
1875                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1876                }
1877
1878                // Send broadcast package appeared if forward locked/external for all users
1879                // treat asec-hosted packages like removable media on upgrade
1880                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1881                    if (DEBUG_INSTALL) {
1882                        Slog.i(TAG, "upgrading pkg " + res.pkg
1883                                + " is ASEC-hosted -> AVAILABLE");
1884                    }
1885                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1886                    ArrayList<String> pkgList = new ArrayList<>(1);
1887                    pkgList.add(packageName);
1888                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1889                }
1890            }
1891
1892            // Work that needs to happen on first install within each user
1893            if (firstUsers != null && firstUsers.length > 0) {
1894                synchronized (mPackages) {
1895                    for (int userId : firstUsers) {
1896                        // If this app is a browser and it's newly-installed for some
1897                        // users, clear any default-browser state in those users. The
1898                        // app's nature doesn't depend on the user, so we can just check
1899                        // its browser nature in any user and generalize.
1900                        if (packageIsBrowser(packageName, userId)) {
1901                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1902                        }
1903
1904                        // We may also need to apply pending (restored) runtime
1905                        // permission grants within these users.
1906                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1907                    }
1908                }
1909            }
1910
1911            // Log current value of "unknown sources" setting
1912            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1913                    getUnknownSourcesSettings());
1914
1915            // Force a gc to clear up things
1916            Runtime.getRuntime().gc();
1917
1918            // Remove the replaced package's older resources safely now
1919            // We delete after a gc for applications  on sdcard.
1920            if (res.removedInfo != null && res.removedInfo.args != null) {
1921                synchronized (mInstallLock) {
1922                    res.removedInfo.args.doPostDeleteLI(true);
1923                }
1924            }
1925
1926            // Notify DexManager that the package was installed for new users.
1927            // The updated users should already be indexed and the package code paths
1928            // should not change.
1929            // Don't notify the manager for ephemeral apps as they are not expected to
1930            // survive long enough to benefit of background optimizations.
1931            for (int userId : firstUsers) {
1932                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1933                // There's a race currently where some install events may interleave with an uninstall.
1934                // This can lead to package info being null (b/36642664).
1935                if (info != null) {
1936                    mDexManager.notifyPackageInstalled(info, userId);
1937                }
1938            }
1939        }
1940
1941        // If someone is watching installs - notify them
1942        if (installObserver != null) {
1943            try {
1944                Bundle extras = extrasForInstallResult(res);
1945                installObserver.onPackageInstalled(res.name, res.returnCode,
1946                        res.returnMsg, extras);
1947            } catch (RemoteException e) {
1948                Slog.i(TAG, "Observer no longer exists.");
1949            }
1950        }
1951    }
1952
1953    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1954            PackageParser.Package pkg) {
1955        if (pkg.parentPackage == null) {
1956            return;
1957        }
1958        if (pkg.requestedPermissions == null) {
1959            return;
1960        }
1961        final PackageSetting disabledSysParentPs = mSettings
1962                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1963        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1964                || !disabledSysParentPs.isPrivileged()
1965                || (disabledSysParentPs.childPackageNames != null
1966                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1967            return;
1968        }
1969        final int[] allUserIds = sUserManager.getUserIds();
1970        final int permCount = pkg.requestedPermissions.size();
1971        for (int i = 0; i < permCount; i++) {
1972            String permission = pkg.requestedPermissions.get(i);
1973            BasePermission bp = mSettings.mPermissions.get(permission);
1974            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1975                continue;
1976            }
1977            for (int userId : allUserIds) {
1978                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1979                        permission, userId)) {
1980                    grantRuntimePermission(pkg.packageName, permission, userId);
1981                }
1982            }
1983        }
1984    }
1985
1986    private StorageEventListener mStorageListener = new StorageEventListener() {
1987        @Override
1988        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1989            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1990                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1991                    final String volumeUuid = vol.getFsUuid();
1992
1993                    // Clean up any users or apps that were removed or recreated
1994                    // while this volume was missing
1995                    sUserManager.reconcileUsers(volumeUuid);
1996                    reconcileApps(volumeUuid);
1997
1998                    // Clean up any install sessions that expired or were
1999                    // cancelled while this volume was missing
2000                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2001
2002                    loadPrivatePackages(vol);
2003
2004                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2005                    unloadPrivatePackages(vol);
2006                }
2007            }
2008
2009            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2010                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2011                    updateExternalMediaStatus(true, false);
2012                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2013                    updateExternalMediaStatus(false, false);
2014                }
2015            }
2016        }
2017
2018        @Override
2019        public void onVolumeForgotten(String fsUuid) {
2020            if (TextUtils.isEmpty(fsUuid)) {
2021                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2022                return;
2023            }
2024
2025            // Remove any apps installed on the forgotten volume
2026            synchronized (mPackages) {
2027                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2028                for (PackageSetting ps : packages) {
2029                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2030                    deletePackageVersioned(new VersionedPackage(ps.name,
2031                            PackageManager.VERSION_CODE_HIGHEST),
2032                            new LegacyPackageDeleteObserver(null).getBinder(),
2033                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2034                    // Try very hard to release any references to this package
2035                    // so we don't risk the system server being killed due to
2036                    // open FDs
2037                    AttributeCache.instance().removePackage(ps.name);
2038                }
2039
2040                mSettings.onVolumeForgotten(fsUuid);
2041                mSettings.writeLPr();
2042            }
2043        }
2044    };
2045
2046    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2047            String[] grantedPermissions) {
2048        for (int userId : userIds) {
2049            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2050        }
2051    }
2052
2053    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2054            String[] grantedPermissions) {
2055        SettingBase sb = (SettingBase) pkg.mExtras;
2056        if (sb == null) {
2057            return;
2058        }
2059
2060        PermissionsState permissionsState = sb.getPermissionsState();
2061
2062        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2063                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2064
2065        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2066                >= Build.VERSION_CODES.M;
2067
2068        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2069
2070        for (String permission : pkg.requestedPermissions) {
2071            final BasePermission bp;
2072            synchronized (mPackages) {
2073                bp = mSettings.mPermissions.get(permission);
2074            }
2075            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2076                    && (!instantApp || bp.isInstant())
2077                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2078                    && (grantedPermissions == null
2079                           || ArrayUtils.contains(grantedPermissions, permission))) {
2080                final int flags = permissionsState.getPermissionFlags(permission, userId);
2081                if (supportsRuntimePermissions) {
2082                    // Installer cannot change immutable permissions.
2083                    if ((flags & immutableFlags) == 0) {
2084                        grantRuntimePermission(pkg.packageName, permission, userId);
2085                    }
2086                } else if (mPermissionReviewRequired) {
2087                    // In permission review mode we clear the review flag when we
2088                    // are asked to install the app with all permissions granted.
2089                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2090                        updatePermissionFlags(permission, pkg.packageName,
2091                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2092                    }
2093                }
2094            }
2095        }
2096    }
2097
2098    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2099        Bundle extras = null;
2100        switch (res.returnCode) {
2101            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2102                extras = new Bundle();
2103                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2104                        res.origPermission);
2105                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2106                        res.origPackage);
2107                break;
2108            }
2109            case PackageManager.INSTALL_SUCCEEDED: {
2110                extras = new Bundle();
2111                extras.putBoolean(Intent.EXTRA_REPLACING,
2112                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2113                break;
2114            }
2115        }
2116        return extras;
2117    }
2118
2119    void scheduleWriteSettingsLocked() {
2120        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2121            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2122        }
2123    }
2124
2125    void scheduleWritePackageListLocked(int userId) {
2126        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2127            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2128            msg.arg1 = userId;
2129            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2130        }
2131    }
2132
2133    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2134        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2135        scheduleWritePackageRestrictionsLocked(userId);
2136    }
2137
2138    void scheduleWritePackageRestrictionsLocked(int userId) {
2139        final int[] userIds = (userId == UserHandle.USER_ALL)
2140                ? sUserManager.getUserIds() : new int[]{userId};
2141        for (int nextUserId : userIds) {
2142            if (!sUserManager.exists(nextUserId)) return;
2143            mDirtyUsers.add(nextUserId);
2144            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2145                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2146            }
2147        }
2148    }
2149
2150    public static PackageManagerService main(Context context, Installer installer,
2151            boolean factoryTest, boolean onlyCore) {
2152        // Self-check for initial settings.
2153        PackageManagerServiceCompilerMapping.checkProperties();
2154
2155        PackageManagerService m = new PackageManagerService(context, installer,
2156                factoryTest, onlyCore);
2157        m.enableSystemUserPackages();
2158        ServiceManager.addService("package", m);
2159        return m;
2160    }
2161
2162    private void enableSystemUserPackages() {
2163        if (!UserManager.isSplitSystemUser()) {
2164            return;
2165        }
2166        // For system user, enable apps based on the following conditions:
2167        // - app is whitelisted or belong to one of these groups:
2168        //   -- system app which has no launcher icons
2169        //   -- system app which has INTERACT_ACROSS_USERS permission
2170        //   -- system IME app
2171        // - app is not in the blacklist
2172        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2173        Set<String> enableApps = new ArraySet<>();
2174        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2175                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2176                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2177        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2178        enableApps.addAll(wlApps);
2179        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2180                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2181        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2182        enableApps.removeAll(blApps);
2183        Log.i(TAG, "Applications installed for system user: " + enableApps);
2184        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2185                UserHandle.SYSTEM);
2186        final int allAppsSize = allAps.size();
2187        synchronized (mPackages) {
2188            for (int i = 0; i < allAppsSize; i++) {
2189                String pName = allAps.get(i);
2190                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2191                // Should not happen, but we shouldn't be failing if it does
2192                if (pkgSetting == null) {
2193                    continue;
2194                }
2195                boolean install = enableApps.contains(pName);
2196                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2197                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2198                            + " for system user");
2199                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2200                }
2201            }
2202            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2203        }
2204    }
2205
2206    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2207        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2208                Context.DISPLAY_SERVICE);
2209        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2210    }
2211
2212    /**
2213     * Requests that files preopted on a secondary system partition be copied to the data partition
2214     * if possible.  Note that the actual copying of the files is accomplished by init for security
2215     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2216     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2217     */
2218    private static void requestCopyPreoptedFiles() {
2219        final int WAIT_TIME_MS = 100;
2220        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2221        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2222            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2223            // We will wait for up to 100 seconds.
2224            final long timeStart = SystemClock.uptimeMillis();
2225            final long timeEnd = timeStart + 100 * 1000;
2226            long timeNow = timeStart;
2227            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2228                try {
2229                    Thread.sleep(WAIT_TIME_MS);
2230                } catch (InterruptedException e) {
2231                    // Do nothing
2232                }
2233                timeNow = SystemClock.uptimeMillis();
2234                if (timeNow > timeEnd) {
2235                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2236                    Slog.wtf(TAG, "cppreopt did not finish!");
2237                    break;
2238                }
2239            }
2240
2241            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2242        }
2243    }
2244
2245    public PackageManagerService(Context context, Installer installer,
2246            boolean factoryTest, boolean onlyCore) {
2247        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2248        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2249        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2250                SystemClock.uptimeMillis());
2251
2252        if (mSdkVersion <= 0) {
2253            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2254        }
2255
2256        mContext = context;
2257
2258        mPermissionReviewRequired = context.getResources().getBoolean(
2259                R.bool.config_permissionReviewRequired);
2260
2261        mFactoryTest = factoryTest;
2262        mOnlyCore = onlyCore;
2263        mMetrics = new DisplayMetrics();
2264        mSettings = new Settings(mPackages);
2265        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2266                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2267        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2268                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2269        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2270                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2271        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2272                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2273        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2274                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2275        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2276                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2277
2278        String separateProcesses = SystemProperties.get("debug.separate_processes");
2279        if (separateProcesses != null && separateProcesses.length() > 0) {
2280            if ("*".equals(separateProcesses)) {
2281                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2282                mSeparateProcesses = null;
2283                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2284            } else {
2285                mDefParseFlags = 0;
2286                mSeparateProcesses = separateProcesses.split(",");
2287                Slog.w(TAG, "Running with debug.separate_processes: "
2288                        + separateProcesses);
2289            }
2290        } else {
2291            mDefParseFlags = 0;
2292            mSeparateProcesses = null;
2293        }
2294
2295        mInstaller = installer;
2296        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2297                "*dexopt*");
2298        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2299        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2300
2301        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2302                FgThread.get().getLooper());
2303
2304        getDefaultDisplayMetrics(context, mMetrics);
2305
2306        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2307        SystemConfig systemConfig = SystemConfig.getInstance();
2308        mGlobalGids = systemConfig.getGlobalGids();
2309        mSystemPermissions = systemConfig.getSystemPermissions();
2310        mAvailableFeatures = systemConfig.getAvailableFeatures();
2311        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2312
2313        mProtectedPackages = new ProtectedPackages(mContext);
2314
2315        synchronized (mInstallLock) {
2316        // writer
2317        synchronized (mPackages) {
2318            mHandlerThread = new ServiceThread(TAG,
2319                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2320            mHandlerThread.start();
2321            mHandler = new PackageHandler(mHandlerThread.getLooper());
2322            mProcessLoggingHandler = new ProcessLoggingHandler();
2323            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2324
2325            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2326            mInstantAppRegistry = new InstantAppRegistry(this);
2327
2328            File dataDir = Environment.getDataDirectory();
2329            mAppInstallDir = new File(dataDir, "app");
2330            mAppLib32InstallDir = new File(dataDir, "app-lib");
2331            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2332            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2333            sUserManager = new UserManagerService(context, this,
2334                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2335
2336            // Propagate permission configuration in to package manager.
2337            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2338                    = systemConfig.getPermissions();
2339            for (int i=0; i<permConfig.size(); i++) {
2340                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2341                BasePermission bp = mSettings.mPermissions.get(perm.name);
2342                if (bp == null) {
2343                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2344                    mSettings.mPermissions.put(perm.name, bp);
2345                }
2346                if (perm.gids != null) {
2347                    bp.setGids(perm.gids, perm.perUser);
2348                }
2349            }
2350
2351            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2352            final int builtInLibCount = libConfig.size();
2353            for (int i = 0; i < builtInLibCount; i++) {
2354                String name = libConfig.keyAt(i);
2355                String path = libConfig.valueAt(i);
2356                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2357                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2358            }
2359
2360            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2361
2362            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2363            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2364            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2365
2366            // Clean up orphaned packages for which the code path doesn't exist
2367            // and they are an update to a system app - caused by bug/32321269
2368            final int packageSettingCount = mSettings.mPackages.size();
2369            for (int i = packageSettingCount - 1; i >= 0; i--) {
2370                PackageSetting ps = mSettings.mPackages.valueAt(i);
2371                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2372                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2373                    mSettings.mPackages.removeAt(i);
2374                    mSettings.enableSystemPackageLPw(ps.name);
2375                }
2376            }
2377
2378            if (mFirstBoot) {
2379                requestCopyPreoptedFiles();
2380            }
2381
2382            String customResolverActivity = Resources.getSystem().getString(
2383                    R.string.config_customResolverActivity);
2384            if (TextUtils.isEmpty(customResolverActivity)) {
2385                customResolverActivity = null;
2386            } else {
2387                mCustomResolverComponentName = ComponentName.unflattenFromString(
2388                        customResolverActivity);
2389            }
2390
2391            long startTime = SystemClock.uptimeMillis();
2392
2393            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2394                    startTime);
2395
2396            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2397            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2398
2399            if (bootClassPath == null) {
2400                Slog.w(TAG, "No BOOTCLASSPATH found!");
2401            }
2402
2403            if (systemServerClassPath == null) {
2404                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2405            }
2406
2407            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2408
2409            final VersionInfo ver = mSettings.getInternalVersion();
2410            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2411            if (mIsUpgrade) {
2412                logCriticalInfo(Log.INFO,
2413                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2414            }
2415
2416            // when upgrading from pre-M, promote system app permissions from install to runtime
2417            mPromoteSystemApps =
2418                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2419
2420            // When upgrading from pre-N, we need to handle package extraction like first boot,
2421            // as there is no profiling data available.
2422            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2423
2424            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2425
2426            // save off the names of pre-existing system packages prior to scanning; we don't
2427            // want to automatically grant runtime permissions for new system apps
2428            if (mPromoteSystemApps) {
2429                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2430                while (pkgSettingIter.hasNext()) {
2431                    PackageSetting ps = pkgSettingIter.next();
2432                    if (isSystemApp(ps)) {
2433                        mExistingSystemPackages.add(ps.name);
2434                    }
2435                }
2436            }
2437
2438            mCacheDir = preparePackageParserCache(mIsUpgrade);
2439
2440            // Set flag to monitor and not change apk file paths when
2441            // scanning install directories.
2442            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2443
2444            if (mIsUpgrade || mFirstBoot) {
2445                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2446            }
2447
2448            // Collect vendor overlay packages. (Do this before scanning any apps.)
2449            // For security and version matching reason, only consider
2450            // overlay packages if they reside in the right directory.
2451            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2452                    | PackageParser.PARSE_IS_SYSTEM
2453                    | PackageParser.PARSE_IS_SYSTEM_DIR
2454                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2455
2456            // Find base frameworks (resource packages without code).
2457            scanDirTracedLI(frameworkDir, mDefParseFlags
2458                    | PackageParser.PARSE_IS_SYSTEM
2459                    | PackageParser.PARSE_IS_SYSTEM_DIR
2460                    | PackageParser.PARSE_IS_PRIVILEGED,
2461                    scanFlags | SCAN_NO_DEX, 0);
2462
2463            // Collected privileged system packages.
2464            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2465            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2466                    | PackageParser.PARSE_IS_SYSTEM
2467                    | PackageParser.PARSE_IS_SYSTEM_DIR
2468                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2469
2470            // Collect ordinary system packages.
2471            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2472            scanDirTracedLI(systemAppDir, mDefParseFlags
2473                    | PackageParser.PARSE_IS_SYSTEM
2474                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2475
2476            // Collect all vendor packages.
2477            File vendorAppDir = new File("/vendor/app");
2478            try {
2479                vendorAppDir = vendorAppDir.getCanonicalFile();
2480            } catch (IOException e) {
2481                // failed to look up canonical path, continue with original one
2482            }
2483            scanDirTracedLI(vendorAppDir, mDefParseFlags
2484                    | PackageParser.PARSE_IS_SYSTEM
2485                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2486
2487            // Collect all OEM packages.
2488            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2489            scanDirTracedLI(oemAppDir, mDefParseFlags
2490                    | PackageParser.PARSE_IS_SYSTEM
2491                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2492
2493            // Prune any system packages that no longer exist.
2494            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2495            if (!mOnlyCore) {
2496                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2497                while (psit.hasNext()) {
2498                    PackageSetting ps = psit.next();
2499
2500                    /*
2501                     * If this is not a system app, it can't be a
2502                     * disable system app.
2503                     */
2504                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2505                        continue;
2506                    }
2507
2508                    /*
2509                     * If the package is scanned, it's not erased.
2510                     */
2511                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2512                    if (scannedPkg != null) {
2513                        /*
2514                         * If the system app is both scanned and in the
2515                         * disabled packages list, then it must have been
2516                         * added via OTA. Remove it from the currently
2517                         * scanned package so the previously user-installed
2518                         * application can be scanned.
2519                         */
2520                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2521                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2522                                    + ps.name + "; removing system app.  Last known codePath="
2523                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2524                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2525                                    + scannedPkg.mVersionCode);
2526                            removePackageLI(scannedPkg, true);
2527                            mExpectingBetter.put(ps.name, ps.codePath);
2528                        }
2529
2530                        continue;
2531                    }
2532
2533                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2534                        psit.remove();
2535                        logCriticalInfo(Log.WARN, "System package " + ps.name
2536                                + " no longer exists; it's data will be wiped");
2537                        // Actual deletion of code and data will be handled by later
2538                        // reconciliation step
2539                    } else {
2540                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2541                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2542                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2543                        }
2544                    }
2545                }
2546            }
2547
2548            //look for any incomplete package installations
2549            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2550            for (int i = 0; i < deletePkgsList.size(); i++) {
2551                // Actual deletion of code and data will be handled by later
2552                // reconciliation step
2553                final String packageName = deletePkgsList.get(i).name;
2554                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2555                synchronized (mPackages) {
2556                    mSettings.removePackageLPw(packageName);
2557                }
2558            }
2559
2560            //delete tmp files
2561            deleteTempPackageFiles();
2562
2563            // Remove any shared userIDs that have no associated packages
2564            mSettings.pruneSharedUsersLPw();
2565
2566            if (!mOnlyCore) {
2567                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2568                        SystemClock.uptimeMillis());
2569                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2570
2571                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2572                        | PackageParser.PARSE_FORWARD_LOCK,
2573                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2574
2575                /**
2576                 * Remove disable package settings for any updated system
2577                 * apps that were removed via an OTA. If they're not a
2578                 * previously-updated app, remove them completely.
2579                 * Otherwise, just revoke their system-level permissions.
2580                 */
2581                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2582                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2583                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2584
2585                    String msg;
2586                    if (deletedPkg == null) {
2587                        msg = "Updated system package " + deletedAppName
2588                                + " no longer exists; it's data will be wiped";
2589                        // Actual deletion of code and data will be handled by later
2590                        // reconciliation step
2591                    } else {
2592                        msg = "Updated system app + " + deletedAppName
2593                                + " no longer present; removing system privileges for "
2594                                + deletedAppName;
2595
2596                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2597
2598                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2599                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2600                    }
2601                    logCriticalInfo(Log.WARN, msg);
2602                }
2603
2604                /**
2605                 * Make sure all system apps that we expected to appear on
2606                 * the userdata partition actually showed up. If they never
2607                 * appeared, crawl back and revive the system version.
2608                 */
2609                for (int i = 0; i < mExpectingBetter.size(); i++) {
2610                    final String packageName = mExpectingBetter.keyAt(i);
2611                    if (!mPackages.containsKey(packageName)) {
2612                        final File scanFile = mExpectingBetter.valueAt(i);
2613
2614                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2615                                + " but never showed up; reverting to system");
2616
2617                        int reparseFlags = mDefParseFlags;
2618                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2619                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2620                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2621                                    | PackageParser.PARSE_IS_PRIVILEGED;
2622                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2623                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2624                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2625                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2626                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2627                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2628                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2629                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2630                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2631                        } else {
2632                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2633                            continue;
2634                        }
2635
2636                        mSettings.enableSystemPackageLPw(packageName);
2637
2638                        try {
2639                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2640                        } catch (PackageManagerException e) {
2641                            Slog.e(TAG, "Failed to parse original system package: "
2642                                    + e.getMessage());
2643                        }
2644                    }
2645                }
2646            }
2647            mExpectingBetter.clear();
2648
2649            // Resolve the storage manager.
2650            mStorageManagerPackage = getStorageManagerPackageName();
2651
2652            // Resolve protected action filters. Only the setup wizard is allowed to
2653            // have a high priority filter for these actions.
2654            mSetupWizardPackage = getSetupWizardPackageName();
2655            if (mProtectedFilters.size() > 0) {
2656                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2657                    Slog.i(TAG, "No setup wizard;"
2658                        + " All protected intents capped to priority 0");
2659                }
2660                for (ActivityIntentInfo filter : mProtectedFilters) {
2661                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2662                        if (DEBUG_FILTERS) {
2663                            Slog.i(TAG, "Found setup wizard;"
2664                                + " allow priority " + filter.getPriority() + ";"
2665                                + " package: " + filter.activity.info.packageName
2666                                + " activity: " + filter.activity.className
2667                                + " priority: " + filter.getPriority());
2668                        }
2669                        // skip setup wizard; allow it to keep the high priority filter
2670                        continue;
2671                    }
2672                    Slog.w(TAG, "Protected action; cap priority to 0;"
2673                            + " package: " + filter.activity.info.packageName
2674                            + " activity: " + filter.activity.className
2675                            + " origPrio: " + filter.getPriority());
2676                    filter.setPriority(0);
2677                }
2678            }
2679            mDeferProtectedFilters = false;
2680            mProtectedFilters.clear();
2681
2682            // Now that we know all of the shared libraries, update all clients to have
2683            // the correct library paths.
2684            updateAllSharedLibrariesLPw(null);
2685
2686            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2687                // NOTE: We ignore potential failures here during a system scan (like
2688                // the rest of the commands above) because there's precious little we
2689                // can do about it. A settings error is reported, though.
2690                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2691            }
2692
2693            // Now that we know all the packages we are keeping,
2694            // read and update their last usage times.
2695            mPackageUsage.read(mPackages);
2696            mCompilerStats.read();
2697
2698            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2699                    SystemClock.uptimeMillis());
2700            Slog.i(TAG, "Time to scan packages: "
2701                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2702                    + " seconds");
2703
2704            // If the platform SDK has changed since the last time we booted,
2705            // we need to re-grant app permission to catch any new ones that
2706            // appear.  This is really a hack, and means that apps can in some
2707            // cases get permissions that the user didn't initially explicitly
2708            // allow...  it would be nice to have some better way to handle
2709            // this situation.
2710            int updateFlags = UPDATE_PERMISSIONS_ALL;
2711            if (ver.sdkVersion != mSdkVersion) {
2712                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2713                        + mSdkVersion + "; regranting permissions for internal storage");
2714                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2715            }
2716            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2717            ver.sdkVersion = mSdkVersion;
2718
2719            // If this is the first boot or an update from pre-M, and it is a normal
2720            // boot, then we need to initialize the default preferred apps across
2721            // all defined users.
2722            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2723                for (UserInfo user : sUserManager.getUsers(true)) {
2724                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2725                    applyFactoryDefaultBrowserLPw(user.id);
2726                    primeDomainVerificationsLPw(user.id);
2727                }
2728            }
2729
2730            // Prepare storage for system user really early during boot,
2731            // since core system apps like SettingsProvider and SystemUI
2732            // can't wait for user to start
2733            final int storageFlags;
2734            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2735                storageFlags = StorageManager.FLAG_STORAGE_DE;
2736            } else {
2737                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2738            }
2739            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2740                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2741                    true /* onlyCoreApps */);
2742            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2743                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2744                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2745                traceLog.traceBegin("AppDataFixup");
2746                try {
2747                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2748                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2749                } catch (InstallerException e) {
2750                    Slog.w(TAG, "Trouble fixing GIDs", e);
2751                }
2752                traceLog.traceEnd();
2753
2754                traceLog.traceBegin("AppDataPrepare");
2755                if (deferPackages == null || deferPackages.isEmpty()) {
2756                    return;
2757                }
2758                int count = 0;
2759                for (String pkgName : deferPackages) {
2760                    PackageParser.Package pkg = null;
2761                    synchronized (mPackages) {
2762                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2763                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2764                            pkg = ps.pkg;
2765                        }
2766                    }
2767                    if (pkg != null) {
2768                        synchronized (mInstallLock) {
2769                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2770                                    true /* maybeMigrateAppData */);
2771                        }
2772                        count++;
2773                    }
2774                }
2775                traceLog.traceEnd();
2776                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2777            }, "prepareAppData");
2778
2779            // If this is first boot after an OTA, and a normal boot, then
2780            // we need to clear code cache directories.
2781            // Note that we do *not* clear the application profiles. These remain valid
2782            // across OTAs and are used to drive profile verification (post OTA) and
2783            // profile compilation (without waiting to collect a fresh set of profiles).
2784            if (mIsUpgrade && !onlyCore) {
2785                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2786                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2787                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2788                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2789                        // No apps are running this early, so no need to freeze
2790                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2791                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2792                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2793                    }
2794                }
2795                ver.fingerprint = Build.FINGERPRINT;
2796            }
2797
2798            checkDefaultBrowser();
2799
2800            // clear only after permissions and other defaults have been updated
2801            mExistingSystemPackages.clear();
2802            mPromoteSystemApps = false;
2803
2804            // All the changes are done during package scanning.
2805            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2806
2807            // can downgrade to reader
2808            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2809            mSettings.writeLPr();
2810            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2811
2812            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2813                    SystemClock.uptimeMillis());
2814
2815            if (!mOnlyCore) {
2816                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2817                mRequiredInstallerPackage = getRequiredInstallerLPr();
2818                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2819                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2820                if (mIntentFilterVerifierComponent != null) {
2821                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2822                            mIntentFilterVerifierComponent);
2823                } else {
2824                    mIntentFilterVerifier = null;
2825                }
2826                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2827                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2828                        SharedLibraryInfo.VERSION_UNDEFINED);
2829                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2830                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2831                        SharedLibraryInfo.VERSION_UNDEFINED);
2832            } else {
2833                mRequiredVerifierPackage = null;
2834                mRequiredInstallerPackage = null;
2835                mRequiredUninstallerPackage = null;
2836                mIntentFilterVerifierComponent = null;
2837                mIntentFilterVerifier = null;
2838                mServicesSystemSharedLibraryPackageName = null;
2839                mSharedSystemSharedLibraryPackageName = null;
2840            }
2841
2842            mInstallerService = new PackageInstallerService(context, this);
2843            final Pair<ComponentName, String> instantAppResolverComponent =
2844                    getInstantAppResolverLPr();
2845            if (instantAppResolverComponent != null) {
2846                if (DEBUG_EPHEMERAL) {
2847                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2848                }
2849                mInstantAppResolverConnection = new EphemeralResolverConnection(
2850                        mContext, instantAppResolverComponent.first,
2851                        instantAppResolverComponent.second);
2852                mInstantAppResolverSettingsComponent =
2853                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2854            } else {
2855                mInstantAppResolverConnection = null;
2856                mInstantAppResolverSettingsComponent = null;
2857            }
2858            updateInstantAppInstallerLocked(null);
2859
2860            // Read and update the usage of dex files.
2861            // Do this at the end of PM init so that all the packages have their
2862            // data directory reconciled.
2863            // At this point we know the code paths of the packages, so we can validate
2864            // the disk file and build the internal cache.
2865            // The usage file is expected to be small so loading and verifying it
2866            // should take a fairly small time compare to the other activities (e.g. package
2867            // scanning).
2868            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2869            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2870            for (int userId : currentUserIds) {
2871                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2872            }
2873            mDexManager.load(userPackages);
2874        } // synchronized (mPackages)
2875        } // synchronized (mInstallLock)
2876
2877        // Now after opening every single application zip, make sure they
2878        // are all flushed.  Not really needed, but keeps things nice and
2879        // tidy.
2880        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2881        Runtime.getRuntime().gc();
2882        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2883
2884        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2885        FallbackCategoryProvider.loadFallbacks();
2886        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2887
2888        // The initial scanning above does many calls into installd while
2889        // holding the mPackages lock, but we're mostly interested in yelling
2890        // once we have a booted system.
2891        mInstaller.setWarnIfHeld(mPackages);
2892
2893        // Expose private service for system components to use.
2894        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2895        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2896    }
2897
2898    private void updateInstantAppInstallerLocked(String modifiedPackage) {
2899        // we're only interested in updating the installer appliction when 1) it's not
2900        // already set or 2) the modified package is the installer
2901        if (mInstantAppInstallerActivity != null
2902                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
2903                        .equals(modifiedPackage)) {
2904            return;
2905        }
2906        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
2907    }
2908
2909    private static File preparePackageParserCache(boolean isUpgrade) {
2910        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2911            return null;
2912        }
2913
2914        // Disable package parsing on eng builds to allow for faster incremental development.
2915        if ("eng".equals(Build.TYPE)) {
2916            return null;
2917        }
2918
2919        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2920            Slog.i(TAG, "Disabling package parser cache due to system property.");
2921            return null;
2922        }
2923
2924        // The base directory for the package parser cache lives under /data/system/.
2925        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2926                "package_cache");
2927        if (cacheBaseDir == null) {
2928            return null;
2929        }
2930
2931        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2932        // This also serves to "GC" unused entries when the package cache version changes (which
2933        // can only happen during upgrades).
2934        if (isUpgrade) {
2935            FileUtils.deleteContents(cacheBaseDir);
2936        }
2937
2938
2939        // Return the versioned package cache directory. This is something like
2940        // "/data/system/package_cache/1"
2941        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2942
2943        // The following is a workaround to aid development on non-numbered userdebug
2944        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2945        // the system partition is newer.
2946        //
2947        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2948        // that starts with "eng." to signify that this is an engineering build and not
2949        // destined for release.
2950        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2951            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2952
2953            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2954            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2955            // in general and should not be used for production changes. In this specific case,
2956            // we know that they will work.
2957            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2958            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2959                FileUtils.deleteContents(cacheBaseDir);
2960                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2961            }
2962        }
2963
2964        return cacheDir;
2965    }
2966
2967    @Override
2968    public boolean isFirstBoot() {
2969        return mFirstBoot;
2970    }
2971
2972    @Override
2973    public boolean isOnlyCoreApps() {
2974        return mOnlyCore;
2975    }
2976
2977    @Override
2978    public boolean isUpgrade() {
2979        return mIsUpgrade;
2980    }
2981
2982    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2983        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2984
2985        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2986                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2987                UserHandle.USER_SYSTEM);
2988        if (matches.size() == 1) {
2989            return matches.get(0).getComponentInfo().packageName;
2990        } else if (matches.size() == 0) {
2991            Log.e(TAG, "There should probably be a verifier, but, none were found");
2992            return null;
2993        }
2994        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2995    }
2996
2997    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2998        synchronized (mPackages) {
2999            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3000            if (libraryEntry == null) {
3001                throw new IllegalStateException("Missing required shared library:" + name);
3002            }
3003            return libraryEntry.apk;
3004        }
3005    }
3006
3007    private @NonNull String getRequiredInstallerLPr() {
3008        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3009        intent.addCategory(Intent.CATEGORY_DEFAULT);
3010        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3011
3012        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3013                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3014                UserHandle.USER_SYSTEM);
3015        if (matches.size() == 1) {
3016            ResolveInfo resolveInfo = matches.get(0);
3017            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3018                throw new RuntimeException("The installer must be a privileged app");
3019            }
3020            return matches.get(0).getComponentInfo().packageName;
3021        } else {
3022            throw new RuntimeException("There must be exactly one installer; found " + matches);
3023        }
3024    }
3025
3026    private @NonNull String getRequiredUninstallerLPr() {
3027        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3028        intent.addCategory(Intent.CATEGORY_DEFAULT);
3029        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3030
3031        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3032                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3033                UserHandle.USER_SYSTEM);
3034        if (resolveInfo == null ||
3035                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3036            throw new RuntimeException("There must be exactly one uninstaller; found "
3037                    + resolveInfo);
3038        }
3039        return resolveInfo.getComponentInfo().packageName;
3040    }
3041
3042    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3043        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3044
3045        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3046                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3047                UserHandle.USER_SYSTEM);
3048        ResolveInfo best = null;
3049        final int N = matches.size();
3050        for (int i = 0; i < N; i++) {
3051            final ResolveInfo cur = matches.get(i);
3052            final String packageName = cur.getComponentInfo().packageName;
3053            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3054                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3055                continue;
3056            }
3057
3058            if (best == null || cur.priority > best.priority) {
3059                best = cur;
3060            }
3061        }
3062
3063        if (best != null) {
3064            return best.getComponentInfo().getComponentName();
3065        }
3066        Slog.w(TAG, "Intent filter verifier not found");
3067        return null;
3068    }
3069
3070    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3071        final String[] packageArray =
3072                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3073        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3074            if (DEBUG_EPHEMERAL) {
3075                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3076            }
3077            return null;
3078        }
3079
3080        final int callingUid = Binder.getCallingUid();
3081        final int resolveFlags =
3082                MATCH_DIRECT_BOOT_AWARE
3083                | MATCH_DIRECT_BOOT_UNAWARE
3084                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3085        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3086        final Intent resolverIntent = new Intent(actionName);
3087        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3088                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3089        // temporarily look for the old action
3090        if (resolvers.size() == 0) {
3091            if (DEBUG_EPHEMERAL) {
3092                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3093            }
3094            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3095            resolverIntent.setAction(actionName);
3096            resolvers = queryIntentServicesInternal(resolverIntent, null,
3097                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3098        }
3099        final int N = resolvers.size();
3100        if (N == 0) {
3101            if (DEBUG_EPHEMERAL) {
3102                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3103            }
3104            return null;
3105        }
3106
3107        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3108        for (int i = 0; i < N; i++) {
3109            final ResolveInfo info = resolvers.get(i);
3110
3111            if (info.serviceInfo == null) {
3112                continue;
3113            }
3114
3115            final String packageName = info.serviceInfo.packageName;
3116            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3117                if (DEBUG_EPHEMERAL) {
3118                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3119                            + " pkg: " + packageName + ", info:" + info);
3120                }
3121                continue;
3122            }
3123
3124            if (DEBUG_EPHEMERAL) {
3125                Slog.v(TAG, "Ephemeral resolver found;"
3126                        + " pkg: " + packageName + ", info:" + info);
3127            }
3128            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3129        }
3130        if (DEBUG_EPHEMERAL) {
3131            Slog.v(TAG, "Ephemeral resolver NOT found");
3132        }
3133        return null;
3134    }
3135
3136    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3137        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3138        intent.addCategory(Intent.CATEGORY_DEFAULT);
3139        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3140
3141        final int resolveFlags =
3142                MATCH_DIRECT_BOOT_AWARE
3143                | MATCH_DIRECT_BOOT_UNAWARE
3144                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3145        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3146                resolveFlags, UserHandle.USER_SYSTEM);
3147        // temporarily look for the old action
3148        if (matches.isEmpty()) {
3149            if (DEBUG_EPHEMERAL) {
3150                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3151            }
3152            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3153            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3154                    resolveFlags, UserHandle.USER_SYSTEM);
3155        }
3156        Iterator<ResolveInfo> iter = matches.iterator();
3157        while (iter.hasNext()) {
3158            final ResolveInfo rInfo = iter.next();
3159            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3160            if (ps != null) {
3161                final PermissionsState permissionsState = ps.getPermissionsState();
3162                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3163                    continue;
3164                }
3165            }
3166            iter.remove();
3167        }
3168        if (matches.size() == 0) {
3169            return null;
3170        } else if (matches.size() == 1) {
3171            return (ActivityInfo) matches.get(0).getComponentInfo();
3172        } else {
3173            throw new RuntimeException(
3174                    "There must be at most one ephemeral installer; found " + matches);
3175        }
3176    }
3177
3178    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3179            @NonNull ComponentName resolver) {
3180        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3181                .addCategory(Intent.CATEGORY_DEFAULT)
3182                .setPackage(resolver.getPackageName());
3183        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3184        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3185                UserHandle.USER_SYSTEM);
3186        // temporarily look for the old action
3187        if (matches.isEmpty()) {
3188            if (DEBUG_EPHEMERAL) {
3189                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3190            }
3191            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3192            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3193                    UserHandle.USER_SYSTEM);
3194        }
3195        if (matches.isEmpty()) {
3196            return null;
3197        }
3198        return matches.get(0).getComponentInfo().getComponentName();
3199    }
3200
3201    private void primeDomainVerificationsLPw(int userId) {
3202        if (DEBUG_DOMAIN_VERIFICATION) {
3203            Slog.d(TAG, "Priming domain verifications in user " + userId);
3204        }
3205
3206        SystemConfig systemConfig = SystemConfig.getInstance();
3207        ArraySet<String> packages = systemConfig.getLinkedApps();
3208
3209        for (String packageName : packages) {
3210            PackageParser.Package pkg = mPackages.get(packageName);
3211            if (pkg != null) {
3212                if (!pkg.isSystemApp()) {
3213                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3214                    continue;
3215                }
3216
3217                ArraySet<String> domains = null;
3218                for (PackageParser.Activity a : pkg.activities) {
3219                    for (ActivityIntentInfo filter : a.intents) {
3220                        if (hasValidDomains(filter)) {
3221                            if (domains == null) {
3222                                domains = new ArraySet<String>();
3223                            }
3224                            domains.addAll(filter.getHostsList());
3225                        }
3226                    }
3227                }
3228
3229                if (domains != null && domains.size() > 0) {
3230                    if (DEBUG_DOMAIN_VERIFICATION) {
3231                        Slog.v(TAG, "      + " + packageName);
3232                    }
3233                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3234                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3235                    // and then 'always' in the per-user state actually used for intent resolution.
3236                    final IntentFilterVerificationInfo ivi;
3237                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3238                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3239                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3240                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3241                } else {
3242                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3243                            + "' does not handle web links");
3244                }
3245            } else {
3246                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3247            }
3248        }
3249
3250        scheduleWritePackageRestrictionsLocked(userId);
3251        scheduleWriteSettingsLocked();
3252    }
3253
3254    private void applyFactoryDefaultBrowserLPw(int userId) {
3255        // The default browser app's package name is stored in a string resource,
3256        // with a product-specific overlay used for vendor customization.
3257        String browserPkg = mContext.getResources().getString(
3258                com.android.internal.R.string.default_browser);
3259        if (!TextUtils.isEmpty(browserPkg)) {
3260            // non-empty string => required to be a known package
3261            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3262            if (ps == null) {
3263                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3264                browserPkg = null;
3265            } else {
3266                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3267            }
3268        }
3269
3270        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3271        // default.  If there's more than one, just leave everything alone.
3272        if (browserPkg == null) {
3273            calculateDefaultBrowserLPw(userId);
3274        }
3275    }
3276
3277    private void calculateDefaultBrowserLPw(int userId) {
3278        List<String> allBrowsers = resolveAllBrowserApps(userId);
3279        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3280        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3281    }
3282
3283    private List<String> resolveAllBrowserApps(int userId) {
3284        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3285        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3286                PackageManager.MATCH_ALL, userId);
3287
3288        final int count = list.size();
3289        List<String> result = new ArrayList<String>(count);
3290        for (int i=0; i<count; i++) {
3291            ResolveInfo info = list.get(i);
3292            if (info.activityInfo == null
3293                    || !info.handleAllWebDataURI
3294                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3295                    || result.contains(info.activityInfo.packageName)) {
3296                continue;
3297            }
3298            result.add(info.activityInfo.packageName);
3299        }
3300
3301        return result;
3302    }
3303
3304    private boolean packageIsBrowser(String packageName, int userId) {
3305        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3306                PackageManager.MATCH_ALL, userId);
3307        final int N = list.size();
3308        for (int i = 0; i < N; i++) {
3309            ResolveInfo info = list.get(i);
3310            if (packageName.equals(info.activityInfo.packageName)) {
3311                return true;
3312            }
3313        }
3314        return false;
3315    }
3316
3317    private void checkDefaultBrowser() {
3318        final int myUserId = UserHandle.myUserId();
3319        final String packageName = getDefaultBrowserPackageName(myUserId);
3320        if (packageName != null) {
3321            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3322            if (info == null) {
3323                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3324                synchronized (mPackages) {
3325                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3326                }
3327            }
3328        }
3329    }
3330
3331    @Override
3332    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3333            throws RemoteException {
3334        try {
3335            return super.onTransact(code, data, reply, flags);
3336        } catch (RuntimeException e) {
3337            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3338                Slog.wtf(TAG, "Package Manager Crash", e);
3339            }
3340            throw e;
3341        }
3342    }
3343
3344    static int[] appendInts(int[] cur, int[] add) {
3345        if (add == null) return cur;
3346        if (cur == null) return add;
3347        final int N = add.length;
3348        for (int i=0; i<N; i++) {
3349            cur = appendInt(cur, add[i]);
3350        }
3351        return cur;
3352    }
3353
3354    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3355        if (!sUserManager.exists(userId)) return null;
3356        if (ps == null) {
3357            return null;
3358        }
3359        final PackageParser.Package p = ps.pkg;
3360        if (p == null) {
3361            return null;
3362        }
3363        // Filter out ephemeral app metadata:
3364        //   * The system/shell/root can see metadata for any app
3365        //   * An installed app can see metadata for 1) other installed apps
3366        //     and 2) ephemeral apps that have explicitly interacted with it
3367        //   * Ephemeral apps can only see their own data and exposed installed apps
3368        //   * Holding a signature permission allows seeing instant apps
3369        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3370        if (callingAppId != Process.SYSTEM_UID
3371                && callingAppId != Process.SHELL_UID
3372                && callingAppId != Process.ROOT_UID
3373                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3374                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3375            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3376            if (instantAppPackageName != null) {
3377                // ephemeral apps can only get information on themselves or
3378                // installed apps that are exposed.
3379                if (!instantAppPackageName.equals(p.packageName)
3380                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3381                    return null;
3382                }
3383            } else {
3384                if (ps.getInstantApp(userId)) {
3385                    // only get access to the ephemeral app if we've been granted access
3386                    if (!mInstantAppRegistry.isInstantAccessGranted(
3387                            userId, callingAppId, ps.appId)) {
3388                        return null;
3389                    }
3390                }
3391            }
3392        }
3393
3394        final PermissionsState permissionsState = ps.getPermissionsState();
3395
3396        // Compute GIDs only if requested
3397        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3398                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3399        // Compute granted permissions only if package has requested permissions
3400        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3401                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3402        final PackageUserState state = ps.readUserState(userId);
3403
3404        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3405                && ps.isSystem()) {
3406            flags |= MATCH_ANY_USER;
3407        }
3408
3409        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3410                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3411
3412        if (packageInfo == null) {
3413            return null;
3414        }
3415
3416        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3417
3418        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3419                resolveExternalPackageNameLPr(p);
3420
3421        return packageInfo;
3422    }
3423
3424    @Override
3425    public void checkPackageStartable(String packageName, int userId) {
3426        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3427
3428        synchronized (mPackages) {
3429            final PackageSetting ps = mSettings.mPackages.get(packageName);
3430            if (ps == null) {
3431                throw new SecurityException("Package " + packageName + " was not found!");
3432            }
3433
3434            if (!ps.getInstalled(userId)) {
3435                throw new SecurityException(
3436                        "Package " + packageName + " was not installed for user " + userId + "!");
3437            }
3438
3439            if (mSafeMode && !ps.isSystem()) {
3440                throw new SecurityException("Package " + packageName + " not a system app!");
3441            }
3442
3443            if (mFrozenPackages.contains(packageName)) {
3444                throw new SecurityException("Package " + packageName + " is currently frozen!");
3445            }
3446
3447            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3448                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3449                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3450            }
3451        }
3452    }
3453
3454    @Override
3455    public boolean isPackageAvailable(String packageName, int userId) {
3456        if (!sUserManager.exists(userId)) return false;
3457        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3458                false /* requireFullPermission */, false /* checkShell */, "is package available");
3459        synchronized (mPackages) {
3460            PackageParser.Package p = mPackages.get(packageName);
3461            if (p != null) {
3462                final PackageSetting ps = (PackageSetting) p.mExtras;
3463                if (ps != null) {
3464                    final PackageUserState state = ps.readUserState(userId);
3465                    if (state != null) {
3466                        return PackageParser.isAvailable(state);
3467                    }
3468                }
3469            }
3470        }
3471        return false;
3472    }
3473
3474    @Override
3475    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3476        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3477                flags, userId);
3478    }
3479
3480    @Override
3481    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3482            int flags, int userId) {
3483        return getPackageInfoInternal(versionedPackage.getPackageName(),
3484                // TODO: We will change version code to long, so in the new API it is long
3485                (int) versionedPackage.getVersionCode(), flags, userId);
3486    }
3487
3488    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3489            int flags, int userId) {
3490        if (!sUserManager.exists(userId)) return null;
3491        flags = updateFlagsForPackage(flags, userId, packageName);
3492        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3493                false /* requireFullPermission */, false /* checkShell */, "get package info");
3494
3495        // reader
3496        synchronized (mPackages) {
3497            // Normalize package name to handle renamed packages and static libs
3498            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3499
3500            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3501            if (matchFactoryOnly) {
3502                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3503                if (ps != null) {
3504                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3505                        return null;
3506                    }
3507                    return generatePackageInfo(ps, flags, userId);
3508                }
3509            }
3510
3511            PackageParser.Package p = mPackages.get(packageName);
3512            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3513                return null;
3514            }
3515            if (DEBUG_PACKAGE_INFO)
3516                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3517            if (p != null) {
3518                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3519                        Binder.getCallingUid(), userId)) {
3520                    return null;
3521                }
3522                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3523            }
3524            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3525                final PackageSetting ps = mSettings.mPackages.get(packageName);
3526                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3527                    return null;
3528                }
3529                return generatePackageInfo(ps, flags, userId);
3530            }
3531        }
3532        return null;
3533    }
3534
3535
3536    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3537        // System/shell/root get to see all static libs
3538        final int appId = UserHandle.getAppId(uid);
3539        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3540                || appId == Process.ROOT_UID) {
3541            return false;
3542        }
3543
3544        // No package means no static lib as it is always on internal storage
3545        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3546            return false;
3547        }
3548
3549        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3550                ps.pkg.staticSharedLibVersion);
3551        if (libEntry == null) {
3552            return false;
3553        }
3554
3555        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3556        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3557        if (uidPackageNames == null) {
3558            return true;
3559        }
3560
3561        for (String uidPackageName : uidPackageNames) {
3562            if (ps.name.equals(uidPackageName)) {
3563                return false;
3564            }
3565            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3566            if (uidPs != null) {
3567                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3568                        libEntry.info.getName());
3569                if (index < 0) {
3570                    continue;
3571                }
3572                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3573                    return false;
3574                }
3575            }
3576        }
3577        return true;
3578    }
3579
3580    @Override
3581    public String[] currentToCanonicalPackageNames(String[] names) {
3582        String[] out = new String[names.length];
3583        // reader
3584        synchronized (mPackages) {
3585            for (int i=names.length-1; i>=0; i--) {
3586                PackageSetting ps = mSettings.mPackages.get(names[i]);
3587                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3588            }
3589        }
3590        return out;
3591    }
3592
3593    @Override
3594    public String[] canonicalToCurrentPackageNames(String[] names) {
3595        String[] out = new String[names.length];
3596        // reader
3597        synchronized (mPackages) {
3598            for (int i=names.length-1; i>=0; i--) {
3599                String cur = mSettings.getRenamedPackageLPr(names[i]);
3600                out[i] = cur != null ? cur : names[i];
3601            }
3602        }
3603        return out;
3604    }
3605
3606    @Override
3607    public int getPackageUid(String packageName, int flags, int userId) {
3608        if (!sUserManager.exists(userId)) return -1;
3609        flags = updateFlagsForPackage(flags, userId, packageName);
3610        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3611                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3612
3613        // reader
3614        synchronized (mPackages) {
3615            final PackageParser.Package p = mPackages.get(packageName);
3616            if (p != null && p.isMatch(flags)) {
3617                return UserHandle.getUid(userId, p.applicationInfo.uid);
3618            }
3619            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3620                final PackageSetting ps = mSettings.mPackages.get(packageName);
3621                if (ps != null && ps.isMatch(flags)) {
3622                    return UserHandle.getUid(userId, ps.appId);
3623                }
3624            }
3625        }
3626
3627        return -1;
3628    }
3629
3630    @Override
3631    public int[] getPackageGids(String packageName, int flags, int userId) {
3632        if (!sUserManager.exists(userId)) return null;
3633        flags = updateFlagsForPackage(flags, userId, packageName);
3634        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3635                false /* requireFullPermission */, false /* checkShell */,
3636                "getPackageGids");
3637
3638        // reader
3639        synchronized (mPackages) {
3640            final PackageParser.Package p = mPackages.get(packageName);
3641            if (p != null && p.isMatch(flags)) {
3642                PackageSetting ps = (PackageSetting) p.mExtras;
3643                // TODO: Shouldn't this be checking for package installed state for userId and
3644                // return null?
3645                return ps.getPermissionsState().computeGids(userId);
3646            }
3647            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3648                final PackageSetting ps = mSettings.mPackages.get(packageName);
3649                if (ps != null && ps.isMatch(flags)) {
3650                    return ps.getPermissionsState().computeGids(userId);
3651                }
3652            }
3653        }
3654
3655        return null;
3656    }
3657
3658    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3659        if (bp.perm != null) {
3660            return PackageParser.generatePermissionInfo(bp.perm, flags);
3661        }
3662        PermissionInfo pi = new PermissionInfo();
3663        pi.name = bp.name;
3664        pi.packageName = bp.sourcePackage;
3665        pi.nonLocalizedLabel = bp.name;
3666        pi.protectionLevel = bp.protectionLevel;
3667        return pi;
3668    }
3669
3670    @Override
3671    public PermissionInfo getPermissionInfo(String name, int flags) {
3672        // reader
3673        synchronized (mPackages) {
3674            final BasePermission p = mSettings.mPermissions.get(name);
3675            if (p != null) {
3676                return generatePermissionInfo(p, flags);
3677            }
3678            return null;
3679        }
3680    }
3681
3682    @Override
3683    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3684            int flags) {
3685        // reader
3686        synchronized (mPackages) {
3687            if (group != null && !mPermissionGroups.containsKey(group)) {
3688                // This is thrown as NameNotFoundException
3689                return null;
3690            }
3691
3692            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3693            for (BasePermission p : mSettings.mPermissions.values()) {
3694                if (group == null) {
3695                    if (p.perm == null || p.perm.info.group == null) {
3696                        out.add(generatePermissionInfo(p, flags));
3697                    }
3698                } else {
3699                    if (p.perm != null && group.equals(p.perm.info.group)) {
3700                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3701                    }
3702                }
3703            }
3704            return new ParceledListSlice<>(out);
3705        }
3706    }
3707
3708    @Override
3709    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3710        // reader
3711        synchronized (mPackages) {
3712            return PackageParser.generatePermissionGroupInfo(
3713                    mPermissionGroups.get(name), flags);
3714        }
3715    }
3716
3717    @Override
3718    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3719        // reader
3720        synchronized (mPackages) {
3721            final int N = mPermissionGroups.size();
3722            ArrayList<PermissionGroupInfo> out
3723                    = new ArrayList<PermissionGroupInfo>(N);
3724            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3725                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3726            }
3727            return new ParceledListSlice<>(out);
3728        }
3729    }
3730
3731    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3732            int uid, int userId) {
3733        if (!sUserManager.exists(userId)) return null;
3734        PackageSetting ps = mSettings.mPackages.get(packageName);
3735        if (ps != null) {
3736            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3737                return null;
3738            }
3739            if (ps.pkg == null) {
3740                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3741                if (pInfo != null) {
3742                    return pInfo.applicationInfo;
3743                }
3744                return null;
3745            }
3746            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3747                    ps.readUserState(userId), userId);
3748            if (ai != null) {
3749                rebaseEnabledOverlays(ai, userId);
3750                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3751            }
3752            return ai;
3753        }
3754        return null;
3755    }
3756
3757    @Override
3758    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3759        if (!sUserManager.exists(userId)) return null;
3760        flags = updateFlagsForApplication(flags, userId, packageName);
3761        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3762                false /* requireFullPermission */, false /* checkShell */, "get application info");
3763
3764        // writer
3765        synchronized (mPackages) {
3766            // Normalize package name to handle renamed packages and static libs
3767            packageName = resolveInternalPackageNameLPr(packageName,
3768                    PackageManager.VERSION_CODE_HIGHEST);
3769
3770            PackageParser.Package p = mPackages.get(packageName);
3771            if (DEBUG_PACKAGE_INFO) Log.v(
3772                    TAG, "getApplicationInfo " + packageName
3773                    + ": " + p);
3774            if (p != null) {
3775                PackageSetting ps = mSettings.mPackages.get(packageName);
3776                if (ps == null) return null;
3777                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3778                    return null;
3779                }
3780                // Note: isEnabledLP() does not apply here - always return info
3781                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3782                        p, flags, ps.readUserState(userId), userId);
3783                if (ai != null) {
3784                    rebaseEnabledOverlays(ai, userId);
3785                    ai.packageName = resolveExternalPackageNameLPr(p);
3786                }
3787                return ai;
3788            }
3789            if ("android".equals(packageName)||"system".equals(packageName)) {
3790                return mAndroidApplication;
3791            }
3792            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3793                // Already generates the external package name
3794                return generateApplicationInfoFromSettingsLPw(packageName,
3795                        Binder.getCallingUid(), flags, userId);
3796            }
3797        }
3798        return null;
3799    }
3800
3801    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3802        List<String> paths = new ArrayList<>();
3803        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3804            mEnabledOverlayPaths.get(userId);
3805        if (userSpecificOverlays != null) {
3806            if (!"android".equals(ai.packageName)) {
3807                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3808                if (frameworkOverlays != null) {
3809                    paths.addAll(frameworkOverlays);
3810                }
3811            }
3812
3813            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3814            if (appOverlays != null) {
3815                paths.addAll(appOverlays);
3816            }
3817        }
3818        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3819    }
3820
3821    private String normalizePackageNameLPr(String packageName) {
3822        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3823        return normalizedPackageName != null ? normalizedPackageName : packageName;
3824    }
3825
3826    @Override
3827    public void deletePreloadsFileCache() {
3828        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3829            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3830        }
3831        File dir = Environment.getDataPreloadsFileCacheDirectory();
3832        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3833        FileUtils.deleteContents(dir);
3834    }
3835
3836    @Override
3837    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3838            final IPackageDataObserver observer) {
3839        mContext.enforceCallingOrSelfPermission(
3840                android.Manifest.permission.CLEAR_APP_CACHE, null);
3841        mHandler.post(() -> {
3842            boolean success = false;
3843            try {
3844                freeStorage(volumeUuid, freeStorageSize, 0);
3845                success = true;
3846            } catch (IOException e) {
3847                Slog.w(TAG, e);
3848            }
3849            if (observer != null) {
3850                try {
3851                    observer.onRemoveCompleted(null, success);
3852                } catch (RemoteException e) {
3853                    Slog.w(TAG, e);
3854                }
3855            }
3856        });
3857    }
3858
3859    @Override
3860    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3861            final IntentSender pi) {
3862        mContext.enforceCallingOrSelfPermission(
3863                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3864        mHandler.post(() -> {
3865            boolean success = false;
3866            try {
3867                freeStorage(volumeUuid, freeStorageSize, 0);
3868                success = true;
3869            } catch (IOException e) {
3870                Slog.w(TAG, e);
3871            }
3872            if (pi != null) {
3873                try {
3874                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3875                } catch (SendIntentException e) {
3876                    Slog.w(TAG, e);
3877                }
3878            }
3879        });
3880    }
3881
3882    /**
3883     * Blocking call to clear various types of cached data across the system
3884     * until the requested bytes are available.
3885     */
3886    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3887        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3888        final File file = storage.findPathForUuid(volumeUuid);
3889        if (file.getUsableSpace() >= bytes) return;
3890
3891        if (ENABLE_FREE_CACHE_V2) {
3892            final boolean aggressive = (storageFlags
3893                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3894            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
3895                    volumeUuid);
3896
3897            // 1. Pre-flight to determine if we have any chance to succeed
3898            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3899            if (internalVolume && (aggressive || SystemProperties
3900                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
3901                deletePreloadsFileCache();
3902                if (file.getUsableSpace() >= bytes) return;
3903            }
3904
3905            // 3. Consider parsed APK data (aggressive only)
3906            if (internalVolume && aggressive) {
3907                FileUtils.deleteContents(mCacheDir);
3908                if (file.getUsableSpace() >= bytes) return;
3909            }
3910
3911            // 4. Consider cached app data (above quotas)
3912            try {
3913                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3914            } catch (InstallerException ignored) {
3915            }
3916            if (file.getUsableSpace() >= bytes) return;
3917
3918            // 5. Consider shared libraries with refcount=0 and age>2h
3919            // 6. Consider dexopt output (aggressive only)
3920            // 7. Consider ephemeral apps not used in last week
3921
3922            // 8. Consider cached app data (below quotas)
3923            try {
3924                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3925                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3926            } catch (InstallerException ignored) {
3927            }
3928            if (file.getUsableSpace() >= bytes) return;
3929
3930            // 9. Consider DropBox entries
3931            // 10. Consider ephemeral cookies
3932
3933        } else {
3934            try {
3935                mInstaller.freeCache(volumeUuid, bytes, 0);
3936            } catch (InstallerException ignored) {
3937            }
3938            if (file.getUsableSpace() >= bytes) return;
3939        }
3940
3941        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3942    }
3943
3944    /**
3945     * Update given flags based on encryption status of current user.
3946     */
3947    private int updateFlags(int flags, int userId) {
3948        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3949                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3950            // Caller expressed an explicit opinion about what encryption
3951            // aware/unaware components they want to see, so fall through and
3952            // give them what they want
3953        } else {
3954            // Caller expressed no opinion, so match based on user state
3955            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3956                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3957            } else {
3958                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3959            }
3960        }
3961        return flags;
3962    }
3963
3964    private UserManagerInternal getUserManagerInternal() {
3965        if (mUserManagerInternal == null) {
3966            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3967        }
3968        return mUserManagerInternal;
3969    }
3970
3971    private DeviceIdleController.LocalService getDeviceIdleController() {
3972        if (mDeviceIdleController == null) {
3973            mDeviceIdleController =
3974                    LocalServices.getService(DeviceIdleController.LocalService.class);
3975        }
3976        return mDeviceIdleController;
3977    }
3978
3979    /**
3980     * Update given flags when being used to request {@link PackageInfo}.
3981     */
3982    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3983        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3984        boolean triaged = true;
3985        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3986                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3987            // Caller is asking for component details, so they'd better be
3988            // asking for specific encryption matching behavior, or be triaged
3989            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3990                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3991                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3992                triaged = false;
3993            }
3994        }
3995        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3996                | PackageManager.MATCH_SYSTEM_ONLY
3997                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3998            triaged = false;
3999        }
4000        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4001            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4002                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4003                    + Debug.getCallers(5));
4004        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4005                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4006            // If the caller wants all packages and has a restricted profile associated with it,
4007            // then match all users. This is to make sure that launchers that need to access work
4008            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4009            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4010            flags |= PackageManager.MATCH_ANY_USER;
4011        }
4012        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4013            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4014                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4015        }
4016        return updateFlags(flags, userId);
4017    }
4018
4019    /**
4020     * Update given flags when being used to request {@link ApplicationInfo}.
4021     */
4022    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4023        return updateFlagsForPackage(flags, userId, cookie);
4024    }
4025
4026    /**
4027     * Update given flags when being used to request {@link ComponentInfo}.
4028     */
4029    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4030        if (cookie instanceof Intent) {
4031            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4032                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4033            }
4034        }
4035
4036        boolean triaged = true;
4037        // Caller is asking for component details, so they'd better be
4038        // asking for specific encryption matching behavior, or be triaged
4039        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4040                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4041                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4042            triaged = false;
4043        }
4044        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4045            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4046                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4047        }
4048
4049        return updateFlags(flags, userId);
4050    }
4051
4052    /**
4053     * Update given intent when being used to request {@link ResolveInfo}.
4054     */
4055    private Intent updateIntentForResolve(Intent intent) {
4056        if (intent.getSelector() != null) {
4057            intent = intent.getSelector();
4058        }
4059        if (DEBUG_PREFERRED) {
4060            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4061        }
4062        return intent;
4063    }
4064
4065    /**
4066     * Update given flags when being used to request {@link ResolveInfo}.
4067     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4068     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4069     * flag set. However, this flag is only honoured in three circumstances:
4070     * <ul>
4071     * <li>when called from a system process</li>
4072     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4073     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4074     * action and a {@code android.intent.category.BROWSABLE} category</li>
4075     * </ul>
4076     */
4077    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4078            boolean includeInstantApps) {
4079        // Safe mode means we shouldn't match any third-party components
4080        if (mSafeMode) {
4081            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4082        }
4083        if (getInstantAppPackageName(callingUid) != null) {
4084            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4085            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4086            flags |= PackageManager.MATCH_INSTANT;
4087        } else {
4088            // Otherwise, prevent leaking ephemeral components
4089            final boolean isSpecialProcess =
4090                    callingUid == Process.SYSTEM_UID
4091                    || callingUid == Process.SHELL_UID
4092                    || callingUid == 0;
4093            final boolean allowMatchInstant =
4094                    (includeInstantApps
4095                            && Intent.ACTION_VIEW.equals(intent.getAction())
4096                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4097                            && hasWebURI(intent))
4098                    || isSpecialProcess
4099                    || mContext.checkCallingOrSelfPermission(
4100                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4101            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4102            if (!allowMatchInstant) {
4103                flags &= ~PackageManager.MATCH_INSTANT;
4104            }
4105        }
4106        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4107    }
4108
4109    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4110            int userId) {
4111        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4112        if (ret != null) {
4113            rebaseEnabledOverlays(ret.applicationInfo, userId);
4114        }
4115        return ret;
4116    }
4117
4118    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4119            PackageUserState state, int userId) {
4120        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4121        if (ai != null) {
4122            rebaseEnabledOverlays(ai.applicationInfo, userId);
4123        }
4124        return ai;
4125    }
4126
4127    @Override
4128    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4129        if (!sUserManager.exists(userId)) return null;
4130        flags = updateFlagsForComponent(flags, userId, component);
4131        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4132                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4133        synchronized (mPackages) {
4134            PackageParser.Activity a = mActivities.mActivities.get(component);
4135
4136            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4137            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4138                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4139                if (ps == null) return null;
4140                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4141            }
4142            if (mResolveComponentName.equals(component)) {
4143                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4144                        userId);
4145            }
4146        }
4147        return null;
4148    }
4149
4150    @Override
4151    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4152            String resolvedType) {
4153        synchronized (mPackages) {
4154            if (component.equals(mResolveComponentName)) {
4155                // The resolver supports EVERYTHING!
4156                return true;
4157            }
4158            PackageParser.Activity a = mActivities.mActivities.get(component);
4159            if (a == null) {
4160                return false;
4161            }
4162            for (int i=0; i<a.intents.size(); i++) {
4163                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4164                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4165                    return true;
4166                }
4167            }
4168            return false;
4169        }
4170    }
4171
4172    @Override
4173    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4174        if (!sUserManager.exists(userId)) return null;
4175        flags = updateFlagsForComponent(flags, userId, component);
4176        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4177                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4178        synchronized (mPackages) {
4179            PackageParser.Activity a = mReceivers.mActivities.get(component);
4180            if (DEBUG_PACKAGE_INFO) Log.v(
4181                TAG, "getReceiverInfo " + component + ": " + a);
4182            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4183                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4184                if (ps == null) return null;
4185                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4186            }
4187        }
4188        return null;
4189    }
4190
4191    @Override
4192    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4193        if (!sUserManager.exists(userId)) return null;
4194        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4195
4196        flags = updateFlagsForPackage(flags, userId, null);
4197
4198        final boolean canSeeStaticLibraries =
4199                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4200                        == PERMISSION_GRANTED
4201                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4202                        == PERMISSION_GRANTED
4203                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4204                        == PERMISSION_GRANTED
4205                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4206                        == PERMISSION_GRANTED;
4207
4208        synchronized (mPackages) {
4209            List<SharedLibraryInfo> result = null;
4210
4211            final int libCount = mSharedLibraries.size();
4212            for (int i = 0; i < libCount; i++) {
4213                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4214                if (versionedLib == null) {
4215                    continue;
4216                }
4217
4218                final int versionCount = versionedLib.size();
4219                for (int j = 0; j < versionCount; j++) {
4220                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4221                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4222                        break;
4223                    }
4224                    final long identity = Binder.clearCallingIdentity();
4225                    try {
4226                        // TODO: We will change version code to long, so in the new API it is long
4227                        PackageInfo packageInfo = getPackageInfoVersioned(
4228                                libInfo.getDeclaringPackage(), flags, userId);
4229                        if (packageInfo == null) {
4230                            continue;
4231                        }
4232                    } finally {
4233                        Binder.restoreCallingIdentity(identity);
4234                    }
4235
4236                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4237                            // TODO: Remove cast for lib version once internally we support longs.
4238                            (int) libInfo.getVersion(), libInfo.getType(),
4239                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4240                            flags, userId));
4241
4242                    if (result == null) {
4243                        result = new ArrayList<>();
4244                    }
4245                    result.add(resLibInfo);
4246                }
4247            }
4248
4249            return result != null ? new ParceledListSlice<>(result) : null;
4250        }
4251    }
4252
4253    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4254            SharedLibraryInfo libInfo, int flags, int userId) {
4255        List<VersionedPackage> versionedPackages = null;
4256        final int packageCount = mSettings.mPackages.size();
4257        for (int i = 0; i < packageCount; i++) {
4258            PackageSetting ps = mSettings.mPackages.valueAt(i);
4259
4260            if (ps == null) {
4261                continue;
4262            }
4263
4264            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4265                continue;
4266            }
4267
4268            final String libName = libInfo.getName();
4269            if (libInfo.isStatic()) {
4270                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4271                if (libIdx < 0) {
4272                    continue;
4273                }
4274                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4275                    continue;
4276                }
4277                if (versionedPackages == null) {
4278                    versionedPackages = new ArrayList<>();
4279                }
4280                // If the dependent is a static shared lib, use the public package name
4281                String dependentPackageName = ps.name;
4282                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4283                    dependentPackageName = ps.pkg.manifestPackageName;
4284                }
4285                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4286            } else if (ps.pkg != null) {
4287                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4288                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4289                    if (versionedPackages == null) {
4290                        versionedPackages = new ArrayList<>();
4291                    }
4292                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4293                }
4294            }
4295        }
4296
4297        return versionedPackages;
4298    }
4299
4300    @Override
4301    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4302        if (!sUserManager.exists(userId)) return null;
4303        flags = updateFlagsForComponent(flags, userId, component);
4304        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4305                false /* requireFullPermission */, false /* checkShell */, "get service info");
4306        synchronized (mPackages) {
4307            PackageParser.Service s = mServices.mServices.get(component);
4308            if (DEBUG_PACKAGE_INFO) Log.v(
4309                TAG, "getServiceInfo " + component + ": " + s);
4310            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4311                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4312                if (ps == null) return null;
4313                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4314                        ps.readUserState(userId), userId);
4315                if (si != null) {
4316                    rebaseEnabledOverlays(si.applicationInfo, userId);
4317                }
4318                return si;
4319            }
4320        }
4321        return null;
4322    }
4323
4324    @Override
4325    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4326        if (!sUserManager.exists(userId)) return null;
4327        flags = updateFlagsForComponent(flags, userId, component);
4328        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4329                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4330        synchronized (mPackages) {
4331            PackageParser.Provider p = mProviders.mProviders.get(component);
4332            if (DEBUG_PACKAGE_INFO) Log.v(
4333                TAG, "getProviderInfo " + component + ": " + p);
4334            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4335                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4336                if (ps == null) return null;
4337                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4338                        ps.readUserState(userId), userId);
4339                if (pi != null) {
4340                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4341                }
4342                return pi;
4343            }
4344        }
4345        return null;
4346    }
4347
4348    @Override
4349    public String[] getSystemSharedLibraryNames() {
4350        synchronized (mPackages) {
4351            Set<String> libs = null;
4352            final int libCount = mSharedLibraries.size();
4353            for (int i = 0; i < libCount; i++) {
4354                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4355                if (versionedLib == null) {
4356                    continue;
4357                }
4358                final int versionCount = versionedLib.size();
4359                for (int j = 0; j < versionCount; j++) {
4360                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4361                    if (!libEntry.info.isStatic()) {
4362                        if (libs == null) {
4363                            libs = new ArraySet<>();
4364                        }
4365                        libs.add(libEntry.info.getName());
4366                        break;
4367                    }
4368                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4369                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4370                            UserHandle.getUserId(Binder.getCallingUid()))) {
4371                        if (libs == null) {
4372                            libs = new ArraySet<>();
4373                        }
4374                        libs.add(libEntry.info.getName());
4375                        break;
4376                    }
4377                }
4378            }
4379
4380            if (libs != null) {
4381                String[] libsArray = new String[libs.size()];
4382                libs.toArray(libsArray);
4383                return libsArray;
4384            }
4385
4386            return null;
4387        }
4388    }
4389
4390    @Override
4391    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4392        synchronized (mPackages) {
4393            return mServicesSystemSharedLibraryPackageName;
4394        }
4395    }
4396
4397    @Override
4398    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4399        synchronized (mPackages) {
4400            return mSharedSystemSharedLibraryPackageName;
4401        }
4402    }
4403
4404    private void updateSequenceNumberLP(String packageName, int[] userList) {
4405        for (int i = userList.length - 1; i >= 0; --i) {
4406            final int userId = userList[i];
4407            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4408            if (changedPackages == null) {
4409                changedPackages = new SparseArray<>();
4410                mChangedPackages.put(userId, changedPackages);
4411            }
4412            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4413            if (sequenceNumbers == null) {
4414                sequenceNumbers = new HashMap<>();
4415                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4416            }
4417            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4418            if (sequenceNumber != null) {
4419                changedPackages.remove(sequenceNumber);
4420            }
4421            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4422            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4423        }
4424        mChangedPackagesSequenceNumber++;
4425    }
4426
4427    @Override
4428    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4429        synchronized (mPackages) {
4430            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4431                return null;
4432            }
4433            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4434            if (changedPackages == null) {
4435                return null;
4436            }
4437            final List<String> packageNames =
4438                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4439            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4440                final String packageName = changedPackages.get(i);
4441                if (packageName != null) {
4442                    packageNames.add(packageName);
4443                }
4444            }
4445            return packageNames.isEmpty()
4446                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4447        }
4448    }
4449
4450    @Override
4451    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4452        ArrayList<FeatureInfo> res;
4453        synchronized (mAvailableFeatures) {
4454            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4455            res.addAll(mAvailableFeatures.values());
4456        }
4457        final FeatureInfo fi = new FeatureInfo();
4458        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4459                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4460        res.add(fi);
4461
4462        return new ParceledListSlice<>(res);
4463    }
4464
4465    @Override
4466    public boolean hasSystemFeature(String name, int version) {
4467        synchronized (mAvailableFeatures) {
4468            final FeatureInfo feat = mAvailableFeatures.get(name);
4469            if (feat == null) {
4470                return false;
4471            } else {
4472                return feat.version >= version;
4473            }
4474        }
4475    }
4476
4477    @Override
4478    public int checkPermission(String permName, String pkgName, int userId) {
4479        if (!sUserManager.exists(userId)) {
4480            return PackageManager.PERMISSION_DENIED;
4481        }
4482
4483        synchronized (mPackages) {
4484            final PackageParser.Package p = mPackages.get(pkgName);
4485            if (p != null && p.mExtras != null) {
4486                final PackageSetting ps = (PackageSetting) p.mExtras;
4487                final PermissionsState permissionsState = ps.getPermissionsState();
4488                if (permissionsState.hasPermission(permName, userId)) {
4489                    return PackageManager.PERMISSION_GRANTED;
4490                }
4491                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4492                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4493                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4494                    return PackageManager.PERMISSION_GRANTED;
4495                }
4496            }
4497        }
4498
4499        return PackageManager.PERMISSION_DENIED;
4500    }
4501
4502    @Override
4503    public int checkUidPermission(String permName, int uid) {
4504        final int userId = UserHandle.getUserId(uid);
4505
4506        if (!sUserManager.exists(userId)) {
4507            return PackageManager.PERMISSION_DENIED;
4508        }
4509
4510        synchronized (mPackages) {
4511            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4512            if (obj != null) {
4513                final SettingBase ps = (SettingBase) obj;
4514                final PermissionsState permissionsState = ps.getPermissionsState();
4515                if (permissionsState.hasPermission(permName, userId)) {
4516                    return PackageManager.PERMISSION_GRANTED;
4517                }
4518                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4519                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4520                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4521                    return PackageManager.PERMISSION_GRANTED;
4522                }
4523            } else {
4524                ArraySet<String> perms = mSystemPermissions.get(uid);
4525                if (perms != null) {
4526                    if (perms.contains(permName)) {
4527                        return PackageManager.PERMISSION_GRANTED;
4528                    }
4529                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4530                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4531                        return PackageManager.PERMISSION_GRANTED;
4532                    }
4533                }
4534            }
4535        }
4536
4537        return PackageManager.PERMISSION_DENIED;
4538    }
4539
4540    @Override
4541    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4542        if (UserHandle.getCallingUserId() != userId) {
4543            mContext.enforceCallingPermission(
4544                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4545                    "isPermissionRevokedByPolicy for user " + userId);
4546        }
4547
4548        if (checkPermission(permission, packageName, userId)
4549                == PackageManager.PERMISSION_GRANTED) {
4550            return false;
4551        }
4552
4553        final long identity = Binder.clearCallingIdentity();
4554        try {
4555            final int flags = getPermissionFlags(permission, packageName, userId);
4556            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4557        } finally {
4558            Binder.restoreCallingIdentity(identity);
4559        }
4560    }
4561
4562    @Override
4563    public String getPermissionControllerPackageName() {
4564        synchronized (mPackages) {
4565            return mRequiredInstallerPackage;
4566        }
4567    }
4568
4569    /**
4570     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4571     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4572     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4573     * @param message the message to log on security exception
4574     */
4575    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4576            boolean checkShell, String message) {
4577        if (userId < 0) {
4578            throw new IllegalArgumentException("Invalid userId " + userId);
4579        }
4580        if (checkShell) {
4581            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4582        }
4583        if (userId == UserHandle.getUserId(callingUid)) return;
4584        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4585            if (requireFullPermission) {
4586                mContext.enforceCallingOrSelfPermission(
4587                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4588            } else {
4589                try {
4590                    mContext.enforceCallingOrSelfPermission(
4591                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4592                } catch (SecurityException se) {
4593                    mContext.enforceCallingOrSelfPermission(
4594                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4595                }
4596            }
4597        }
4598    }
4599
4600    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4601        if (callingUid == Process.SHELL_UID) {
4602            if (userHandle >= 0
4603                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4604                throw new SecurityException("Shell does not have permission to access user "
4605                        + userHandle);
4606            } else if (userHandle < 0) {
4607                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4608                        + Debug.getCallers(3));
4609            }
4610        }
4611    }
4612
4613    private BasePermission findPermissionTreeLP(String permName) {
4614        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4615            if (permName.startsWith(bp.name) &&
4616                    permName.length() > bp.name.length() &&
4617                    permName.charAt(bp.name.length()) == '.') {
4618                return bp;
4619            }
4620        }
4621        return null;
4622    }
4623
4624    private BasePermission checkPermissionTreeLP(String permName) {
4625        if (permName != null) {
4626            BasePermission bp = findPermissionTreeLP(permName);
4627            if (bp != null) {
4628                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4629                    return bp;
4630                }
4631                throw new SecurityException("Calling uid "
4632                        + Binder.getCallingUid()
4633                        + " is not allowed to add to permission tree "
4634                        + bp.name + " owned by uid " + bp.uid);
4635            }
4636        }
4637        throw new SecurityException("No permission tree found for " + permName);
4638    }
4639
4640    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4641        if (s1 == null) {
4642            return s2 == null;
4643        }
4644        if (s2 == null) {
4645            return false;
4646        }
4647        if (s1.getClass() != s2.getClass()) {
4648            return false;
4649        }
4650        return s1.equals(s2);
4651    }
4652
4653    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4654        if (pi1.icon != pi2.icon) return false;
4655        if (pi1.logo != pi2.logo) return false;
4656        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4657        if (!compareStrings(pi1.name, pi2.name)) return false;
4658        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4659        // We'll take care of setting this one.
4660        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4661        // These are not currently stored in settings.
4662        //if (!compareStrings(pi1.group, pi2.group)) return false;
4663        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4664        //if (pi1.labelRes != pi2.labelRes) return false;
4665        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4666        return true;
4667    }
4668
4669    int permissionInfoFootprint(PermissionInfo info) {
4670        int size = info.name.length();
4671        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4672        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4673        return size;
4674    }
4675
4676    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4677        int size = 0;
4678        for (BasePermission perm : mSettings.mPermissions.values()) {
4679            if (perm.uid == tree.uid) {
4680                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4681            }
4682        }
4683        return size;
4684    }
4685
4686    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4687        // We calculate the max size of permissions defined by this uid and throw
4688        // if that plus the size of 'info' would exceed our stated maximum.
4689        if (tree.uid != Process.SYSTEM_UID) {
4690            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4691            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4692                throw new SecurityException("Permission tree size cap exceeded");
4693            }
4694        }
4695    }
4696
4697    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4698        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4699            throw new SecurityException("Label must be specified in permission");
4700        }
4701        BasePermission tree = checkPermissionTreeLP(info.name);
4702        BasePermission bp = mSettings.mPermissions.get(info.name);
4703        boolean added = bp == null;
4704        boolean changed = true;
4705        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4706        if (added) {
4707            enforcePermissionCapLocked(info, tree);
4708            bp = new BasePermission(info.name, tree.sourcePackage,
4709                    BasePermission.TYPE_DYNAMIC);
4710        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4711            throw new SecurityException(
4712                    "Not allowed to modify non-dynamic permission "
4713                    + info.name);
4714        } else {
4715            if (bp.protectionLevel == fixedLevel
4716                    && bp.perm.owner.equals(tree.perm.owner)
4717                    && bp.uid == tree.uid
4718                    && comparePermissionInfos(bp.perm.info, info)) {
4719                changed = false;
4720            }
4721        }
4722        bp.protectionLevel = fixedLevel;
4723        info = new PermissionInfo(info);
4724        info.protectionLevel = fixedLevel;
4725        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4726        bp.perm.info.packageName = tree.perm.info.packageName;
4727        bp.uid = tree.uid;
4728        if (added) {
4729            mSettings.mPermissions.put(info.name, bp);
4730        }
4731        if (changed) {
4732            if (!async) {
4733                mSettings.writeLPr();
4734            } else {
4735                scheduleWriteSettingsLocked();
4736            }
4737        }
4738        return added;
4739    }
4740
4741    @Override
4742    public boolean addPermission(PermissionInfo info) {
4743        synchronized (mPackages) {
4744            return addPermissionLocked(info, false);
4745        }
4746    }
4747
4748    @Override
4749    public boolean addPermissionAsync(PermissionInfo info) {
4750        synchronized (mPackages) {
4751            return addPermissionLocked(info, true);
4752        }
4753    }
4754
4755    @Override
4756    public void removePermission(String name) {
4757        synchronized (mPackages) {
4758            checkPermissionTreeLP(name);
4759            BasePermission bp = mSettings.mPermissions.get(name);
4760            if (bp != null) {
4761                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4762                    throw new SecurityException(
4763                            "Not allowed to modify non-dynamic permission "
4764                            + name);
4765                }
4766                mSettings.mPermissions.remove(name);
4767                mSettings.writeLPr();
4768            }
4769        }
4770    }
4771
4772    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4773            BasePermission bp) {
4774        int index = pkg.requestedPermissions.indexOf(bp.name);
4775        if (index == -1) {
4776            throw new SecurityException("Package " + pkg.packageName
4777                    + " has not requested permission " + bp.name);
4778        }
4779        if (!bp.isRuntime() && !bp.isDevelopment()) {
4780            throw new SecurityException("Permission " + bp.name
4781                    + " is not a changeable permission type");
4782        }
4783    }
4784
4785    @Override
4786    public void grantRuntimePermission(String packageName, String name, final int userId) {
4787        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4788    }
4789
4790    private void grantRuntimePermission(String packageName, String name, final int userId,
4791            boolean overridePolicy) {
4792        if (!sUserManager.exists(userId)) {
4793            Log.e(TAG, "No such user:" + userId);
4794            return;
4795        }
4796
4797        mContext.enforceCallingOrSelfPermission(
4798                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4799                "grantRuntimePermission");
4800
4801        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4802                true /* requireFullPermission */, true /* checkShell */,
4803                "grantRuntimePermission");
4804
4805        final int uid;
4806        final SettingBase sb;
4807
4808        synchronized (mPackages) {
4809            final PackageParser.Package pkg = mPackages.get(packageName);
4810            if (pkg == null) {
4811                throw new IllegalArgumentException("Unknown package: " + packageName);
4812            }
4813
4814            final BasePermission bp = mSettings.mPermissions.get(name);
4815            if (bp == null) {
4816                throw new IllegalArgumentException("Unknown permission: " + name);
4817            }
4818
4819            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4820
4821            // If a permission review is required for legacy apps we represent
4822            // their permissions as always granted runtime ones since we need
4823            // to keep the review required permission flag per user while an
4824            // install permission's state is shared across all users.
4825            if (mPermissionReviewRequired
4826                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4827                    && bp.isRuntime()) {
4828                return;
4829            }
4830
4831            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4832            sb = (SettingBase) pkg.mExtras;
4833            if (sb == null) {
4834                throw new IllegalArgumentException("Unknown package: " + packageName);
4835            }
4836
4837            final PermissionsState permissionsState = sb.getPermissionsState();
4838
4839            final int flags = permissionsState.getPermissionFlags(name, userId);
4840            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4841                throw new SecurityException("Cannot grant system fixed permission "
4842                        + name + " for package " + packageName);
4843            }
4844            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4845                throw new SecurityException("Cannot grant policy fixed permission "
4846                        + name + " for package " + packageName);
4847            }
4848
4849            if (bp.isDevelopment()) {
4850                // Development permissions must be handled specially, since they are not
4851                // normal runtime permissions.  For now they apply to all users.
4852                if (permissionsState.grantInstallPermission(bp) !=
4853                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4854                    scheduleWriteSettingsLocked();
4855                }
4856                return;
4857            }
4858
4859            final PackageSetting ps = mSettings.mPackages.get(packageName);
4860            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4861                throw new SecurityException("Cannot grant non-ephemeral permission"
4862                        + name + " for package " + packageName);
4863            }
4864
4865            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4866                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4867                return;
4868            }
4869
4870            final int result = permissionsState.grantRuntimePermission(bp, userId);
4871            switch (result) {
4872                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4873                    return;
4874                }
4875
4876                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4877                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4878                    mHandler.post(new Runnable() {
4879                        @Override
4880                        public void run() {
4881                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4882                        }
4883                    });
4884                }
4885                break;
4886            }
4887
4888            if (bp.isRuntime()) {
4889                logPermissionGranted(mContext, name, packageName);
4890            }
4891
4892            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4893
4894            // Not critical if that is lost - app has to request again.
4895            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4896        }
4897
4898        // Only need to do this if user is initialized. Otherwise it's a new user
4899        // and there are no processes running as the user yet and there's no need
4900        // to make an expensive call to remount processes for the changed permissions.
4901        if (READ_EXTERNAL_STORAGE.equals(name)
4902                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4903            final long token = Binder.clearCallingIdentity();
4904            try {
4905                if (sUserManager.isInitialized(userId)) {
4906                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4907                            StorageManagerInternal.class);
4908                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4909                }
4910            } finally {
4911                Binder.restoreCallingIdentity(token);
4912            }
4913        }
4914    }
4915
4916    @Override
4917    public void revokeRuntimePermission(String packageName, String name, int userId) {
4918        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4919    }
4920
4921    private void revokeRuntimePermission(String packageName, String name, int userId,
4922            boolean overridePolicy) {
4923        if (!sUserManager.exists(userId)) {
4924            Log.e(TAG, "No such user:" + userId);
4925            return;
4926        }
4927
4928        mContext.enforceCallingOrSelfPermission(
4929                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4930                "revokeRuntimePermission");
4931
4932        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4933                true /* requireFullPermission */, true /* checkShell */,
4934                "revokeRuntimePermission");
4935
4936        final int appId;
4937
4938        synchronized (mPackages) {
4939            final PackageParser.Package pkg = mPackages.get(packageName);
4940            if (pkg == null) {
4941                throw new IllegalArgumentException("Unknown package: " + packageName);
4942            }
4943
4944            final BasePermission bp = mSettings.mPermissions.get(name);
4945            if (bp == null) {
4946                throw new IllegalArgumentException("Unknown permission: " + name);
4947            }
4948
4949            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4950
4951            // If a permission review is required for legacy apps we represent
4952            // their permissions as always granted runtime ones since we need
4953            // to keep the review required permission flag per user while an
4954            // install permission's state is shared across all users.
4955            if (mPermissionReviewRequired
4956                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4957                    && bp.isRuntime()) {
4958                return;
4959            }
4960
4961            SettingBase sb = (SettingBase) pkg.mExtras;
4962            if (sb == null) {
4963                throw new IllegalArgumentException("Unknown package: " + packageName);
4964            }
4965
4966            final PermissionsState permissionsState = sb.getPermissionsState();
4967
4968            final int flags = permissionsState.getPermissionFlags(name, userId);
4969            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4970                throw new SecurityException("Cannot revoke system fixed permission "
4971                        + name + " for package " + packageName);
4972            }
4973            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4974                throw new SecurityException("Cannot revoke policy fixed permission "
4975                        + name + " for package " + packageName);
4976            }
4977
4978            if (bp.isDevelopment()) {
4979                // Development permissions must be handled specially, since they are not
4980                // normal runtime permissions.  For now they apply to all users.
4981                if (permissionsState.revokeInstallPermission(bp) !=
4982                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4983                    scheduleWriteSettingsLocked();
4984                }
4985                return;
4986            }
4987
4988            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4989                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4990                return;
4991            }
4992
4993            if (bp.isRuntime()) {
4994                logPermissionRevoked(mContext, name, packageName);
4995            }
4996
4997            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4998
4999            // Critical, after this call app should never have the permission.
5000            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5001
5002            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5003        }
5004
5005        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5006    }
5007
5008    /**
5009     * Get the first event id for the permission.
5010     *
5011     * <p>There are four events for each permission: <ul>
5012     *     <li>Request permission: first id + 0</li>
5013     *     <li>Grant permission: first id + 1</li>
5014     *     <li>Request for permission denied: first id + 2</li>
5015     *     <li>Revoke permission: first id + 3</li>
5016     * </ul></p>
5017     *
5018     * @param name name of the permission
5019     *
5020     * @return The first event id for the permission
5021     */
5022    private static int getBaseEventId(@NonNull String name) {
5023        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5024
5025        if (eventIdIndex == -1) {
5026            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5027                    || "user".equals(Build.TYPE)) {
5028                Log.i(TAG, "Unknown permission " + name);
5029
5030                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5031            } else {
5032                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5033                //
5034                // Also update
5035                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5036                // - metrics_constants.proto
5037                throw new IllegalStateException("Unknown permission " + name);
5038            }
5039        }
5040
5041        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5042    }
5043
5044    /**
5045     * Log that a permission was revoked.
5046     *
5047     * @param context Context of the caller
5048     * @param name name of the permission
5049     * @param packageName package permission if for
5050     */
5051    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5052            @NonNull String packageName) {
5053        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5054    }
5055
5056    /**
5057     * Log that a permission request was granted.
5058     *
5059     * @param context Context of the caller
5060     * @param name name of the permission
5061     * @param packageName package permission if for
5062     */
5063    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5064            @NonNull String packageName) {
5065        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5066    }
5067
5068    @Override
5069    public void resetRuntimePermissions() {
5070        mContext.enforceCallingOrSelfPermission(
5071                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5072                "revokeRuntimePermission");
5073
5074        int callingUid = Binder.getCallingUid();
5075        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5076            mContext.enforceCallingOrSelfPermission(
5077                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5078                    "resetRuntimePermissions");
5079        }
5080
5081        synchronized (mPackages) {
5082            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5083            for (int userId : UserManagerService.getInstance().getUserIds()) {
5084                final int packageCount = mPackages.size();
5085                for (int i = 0; i < packageCount; i++) {
5086                    PackageParser.Package pkg = mPackages.valueAt(i);
5087                    if (!(pkg.mExtras instanceof PackageSetting)) {
5088                        continue;
5089                    }
5090                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5091                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5092                }
5093            }
5094        }
5095    }
5096
5097    @Override
5098    public int getPermissionFlags(String name, String packageName, int userId) {
5099        if (!sUserManager.exists(userId)) {
5100            return 0;
5101        }
5102
5103        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5104
5105        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5106                true /* requireFullPermission */, false /* checkShell */,
5107                "getPermissionFlags");
5108
5109        synchronized (mPackages) {
5110            final PackageParser.Package pkg = mPackages.get(packageName);
5111            if (pkg == null) {
5112                return 0;
5113            }
5114
5115            final BasePermission bp = mSettings.mPermissions.get(name);
5116            if (bp == null) {
5117                return 0;
5118            }
5119
5120            SettingBase sb = (SettingBase) pkg.mExtras;
5121            if (sb == null) {
5122                return 0;
5123            }
5124
5125            PermissionsState permissionsState = sb.getPermissionsState();
5126            return permissionsState.getPermissionFlags(name, userId);
5127        }
5128    }
5129
5130    @Override
5131    public void updatePermissionFlags(String name, String packageName, int flagMask,
5132            int flagValues, int userId) {
5133        if (!sUserManager.exists(userId)) {
5134            return;
5135        }
5136
5137        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5138
5139        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5140                true /* requireFullPermission */, true /* checkShell */,
5141                "updatePermissionFlags");
5142
5143        // Only the system can change these flags and nothing else.
5144        if (getCallingUid() != Process.SYSTEM_UID) {
5145            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5146            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5147            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5148            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5149            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5150        }
5151
5152        synchronized (mPackages) {
5153            final PackageParser.Package pkg = mPackages.get(packageName);
5154            if (pkg == null) {
5155                throw new IllegalArgumentException("Unknown package: " + packageName);
5156            }
5157
5158            final BasePermission bp = mSettings.mPermissions.get(name);
5159            if (bp == null) {
5160                throw new IllegalArgumentException("Unknown permission: " + name);
5161            }
5162
5163            SettingBase sb = (SettingBase) pkg.mExtras;
5164            if (sb == null) {
5165                throw new IllegalArgumentException("Unknown package: " + packageName);
5166            }
5167
5168            PermissionsState permissionsState = sb.getPermissionsState();
5169
5170            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5171
5172            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5173                // Install and runtime permissions are stored in different places,
5174                // so figure out what permission changed and persist the change.
5175                if (permissionsState.getInstallPermissionState(name) != null) {
5176                    scheduleWriteSettingsLocked();
5177                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5178                        || hadState) {
5179                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5180                }
5181            }
5182        }
5183    }
5184
5185    /**
5186     * Update the permission flags for all packages and runtime permissions of a user in order
5187     * to allow device or profile owner to remove POLICY_FIXED.
5188     */
5189    @Override
5190    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5191        if (!sUserManager.exists(userId)) {
5192            return;
5193        }
5194
5195        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5196
5197        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5198                true /* requireFullPermission */, true /* checkShell */,
5199                "updatePermissionFlagsForAllApps");
5200
5201        // Only the system can change system fixed flags.
5202        if (getCallingUid() != Process.SYSTEM_UID) {
5203            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5204            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5205        }
5206
5207        synchronized (mPackages) {
5208            boolean changed = false;
5209            final int packageCount = mPackages.size();
5210            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5211                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5212                SettingBase sb = (SettingBase) pkg.mExtras;
5213                if (sb == null) {
5214                    continue;
5215                }
5216                PermissionsState permissionsState = sb.getPermissionsState();
5217                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5218                        userId, flagMask, flagValues);
5219            }
5220            if (changed) {
5221                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5222            }
5223        }
5224    }
5225
5226    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5227        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5228                != PackageManager.PERMISSION_GRANTED
5229            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5230                != PackageManager.PERMISSION_GRANTED) {
5231            throw new SecurityException(message + " requires "
5232                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5233                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5234        }
5235    }
5236
5237    @Override
5238    public boolean shouldShowRequestPermissionRationale(String permissionName,
5239            String packageName, int userId) {
5240        if (UserHandle.getCallingUserId() != userId) {
5241            mContext.enforceCallingPermission(
5242                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5243                    "canShowRequestPermissionRationale for user " + userId);
5244        }
5245
5246        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5247        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5248            return false;
5249        }
5250
5251        if (checkPermission(permissionName, packageName, userId)
5252                == PackageManager.PERMISSION_GRANTED) {
5253            return false;
5254        }
5255
5256        final int flags;
5257
5258        final long identity = Binder.clearCallingIdentity();
5259        try {
5260            flags = getPermissionFlags(permissionName,
5261                    packageName, userId);
5262        } finally {
5263            Binder.restoreCallingIdentity(identity);
5264        }
5265
5266        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5267                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5268                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5269
5270        if ((flags & fixedFlags) != 0) {
5271            return false;
5272        }
5273
5274        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5275    }
5276
5277    @Override
5278    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5279        mContext.enforceCallingOrSelfPermission(
5280                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5281                "addOnPermissionsChangeListener");
5282
5283        synchronized (mPackages) {
5284            mOnPermissionChangeListeners.addListenerLocked(listener);
5285        }
5286    }
5287
5288    @Override
5289    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5290        synchronized (mPackages) {
5291            mOnPermissionChangeListeners.removeListenerLocked(listener);
5292        }
5293    }
5294
5295    @Override
5296    public boolean isProtectedBroadcast(String actionName) {
5297        synchronized (mPackages) {
5298            if (mProtectedBroadcasts.contains(actionName)) {
5299                return true;
5300            } else if (actionName != null) {
5301                // TODO: remove these terrible hacks
5302                if (actionName.startsWith("android.net.netmon.lingerExpired")
5303                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5304                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5305                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5306                    return true;
5307                }
5308            }
5309        }
5310        return false;
5311    }
5312
5313    @Override
5314    public int checkSignatures(String pkg1, String pkg2) {
5315        synchronized (mPackages) {
5316            final PackageParser.Package p1 = mPackages.get(pkg1);
5317            final PackageParser.Package p2 = mPackages.get(pkg2);
5318            if (p1 == null || p1.mExtras == null
5319                    || p2 == null || p2.mExtras == null) {
5320                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5321            }
5322            return compareSignatures(p1.mSignatures, p2.mSignatures);
5323        }
5324    }
5325
5326    @Override
5327    public int checkUidSignatures(int uid1, int uid2) {
5328        // Map to base uids.
5329        uid1 = UserHandle.getAppId(uid1);
5330        uid2 = UserHandle.getAppId(uid2);
5331        // reader
5332        synchronized (mPackages) {
5333            Signature[] s1;
5334            Signature[] s2;
5335            Object obj = mSettings.getUserIdLPr(uid1);
5336            if (obj != null) {
5337                if (obj instanceof SharedUserSetting) {
5338                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5339                } else if (obj instanceof PackageSetting) {
5340                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5341                } else {
5342                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5343                }
5344            } else {
5345                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5346            }
5347            obj = mSettings.getUserIdLPr(uid2);
5348            if (obj != null) {
5349                if (obj instanceof SharedUserSetting) {
5350                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5351                } else if (obj instanceof PackageSetting) {
5352                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5353                } else {
5354                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5355                }
5356            } else {
5357                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5358            }
5359            return compareSignatures(s1, s2);
5360        }
5361    }
5362
5363    /**
5364     * This method should typically only be used when granting or revoking
5365     * permissions, since the app may immediately restart after this call.
5366     * <p>
5367     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5368     * guard your work against the app being relaunched.
5369     */
5370    private void killUid(int appId, int userId, String reason) {
5371        final long identity = Binder.clearCallingIdentity();
5372        try {
5373            IActivityManager am = ActivityManager.getService();
5374            if (am != null) {
5375                try {
5376                    am.killUid(appId, userId, reason);
5377                } catch (RemoteException e) {
5378                    /* ignore - same process */
5379                }
5380            }
5381        } finally {
5382            Binder.restoreCallingIdentity(identity);
5383        }
5384    }
5385
5386    /**
5387     * Compares two sets of signatures. Returns:
5388     * <br />
5389     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5390     * <br />
5391     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5392     * <br />
5393     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5394     * <br />
5395     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5396     * <br />
5397     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5398     */
5399    static int compareSignatures(Signature[] s1, Signature[] s2) {
5400        if (s1 == null) {
5401            return s2 == null
5402                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5403                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5404        }
5405
5406        if (s2 == null) {
5407            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5408        }
5409
5410        if (s1.length != s2.length) {
5411            return PackageManager.SIGNATURE_NO_MATCH;
5412        }
5413
5414        // Since both signature sets are of size 1, we can compare without HashSets.
5415        if (s1.length == 1) {
5416            return s1[0].equals(s2[0]) ?
5417                    PackageManager.SIGNATURE_MATCH :
5418                    PackageManager.SIGNATURE_NO_MATCH;
5419        }
5420
5421        ArraySet<Signature> set1 = new ArraySet<Signature>();
5422        for (Signature sig : s1) {
5423            set1.add(sig);
5424        }
5425        ArraySet<Signature> set2 = new ArraySet<Signature>();
5426        for (Signature sig : s2) {
5427            set2.add(sig);
5428        }
5429        // Make sure s2 contains all signatures in s1.
5430        if (set1.equals(set2)) {
5431            return PackageManager.SIGNATURE_MATCH;
5432        }
5433        return PackageManager.SIGNATURE_NO_MATCH;
5434    }
5435
5436    /**
5437     * If the database version for this type of package (internal storage or
5438     * external storage) is less than the version where package signatures
5439     * were updated, return true.
5440     */
5441    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5442        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5443        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5444    }
5445
5446    /**
5447     * Used for backward compatibility to make sure any packages with
5448     * certificate chains get upgraded to the new style. {@code existingSigs}
5449     * will be in the old format (since they were stored on disk from before the
5450     * system upgrade) and {@code scannedSigs} will be in the newer format.
5451     */
5452    private int compareSignaturesCompat(PackageSignatures existingSigs,
5453            PackageParser.Package scannedPkg) {
5454        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5455            return PackageManager.SIGNATURE_NO_MATCH;
5456        }
5457
5458        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5459        for (Signature sig : existingSigs.mSignatures) {
5460            existingSet.add(sig);
5461        }
5462        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5463        for (Signature sig : scannedPkg.mSignatures) {
5464            try {
5465                Signature[] chainSignatures = sig.getChainSignatures();
5466                for (Signature chainSig : chainSignatures) {
5467                    scannedCompatSet.add(chainSig);
5468                }
5469            } catch (CertificateEncodingException e) {
5470                scannedCompatSet.add(sig);
5471            }
5472        }
5473        /*
5474         * Make sure the expanded scanned set contains all signatures in the
5475         * existing one.
5476         */
5477        if (scannedCompatSet.equals(existingSet)) {
5478            // Migrate the old signatures to the new scheme.
5479            existingSigs.assignSignatures(scannedPkg.mSignatures);
5480            // The new KeySets will be re-added later in the scanning process.
5481            synchronized (mPackages) {
5482                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5483            }
5484            return PackageManager.SIGNATURE_MATCH;
5485        }
5486        return PackageManager.SIGNATURE_NO_MATCH;
5487    }
5488
5489    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5490        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5491        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5492    }
5493
5494    private int compareSignaturesRecover(PackageSignatures existingSigs,
5495            PackageParser.Package scannedPkg) {
5496        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5497            return PackageManager.SIGNATURE_NO_MATCH;
5498        }
5499
5500        String msg = null;
5501        try {
5502            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5503                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5504                        + scannedPkg.packageName);
5505                return PackageManager.SIGNATURE_MATCH;
5506            }
5507        } catch (CertificateException e) {
5508            msg = e.getMessage();
5509        }
5510
5511        logCriticalInfo(Log.INFO,
5512                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5513        return PackageManager.SIGNATURE_NO_MATCH;
5514    }
5515
5516    @Override
5517    public List<String> getAllPackages() {
5518        synchronized (mPackages) {
5519            return new ArrayList<String>(mPackages.keySet());
5520        }
5521    }
5522
5523    @Override
5524    public String[] getPackagesForUid(int uid) {
5525        final int userId = UserHandle.getUserId(uid);
5526        uid = UserHandle.getAppId(uid);
5527        // reader
5528        synchronized (mPackages) {
5529            Object obj = mSettings.getUserIdLPr(uid);
5530            if (obj instanceof SharedUserSetting) {
5531                final SharedUserSetting sus = (SharedUserSetting) obj;
5532                final int N = sus.packages.size();
5533                String[] res = new String[N];
5534                final Iterator<PackageSetting> it = sus.packages.iterator();
5535                int i = 0;
5536                while (it.hasNext()) {
5537                    PackageSetting ps = it.next();
5538                    if (ps.getInstalled(userId)) {
5539                        res[i++] = ps.name;
5540                    } else {
5541                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5542                    }
5543                }
5544                return res;
5545            } else if (obj instanceof PackageSetting) {
5546                final PackageSetting ps = (PackageSetting) obj;
5547                if (ps.getInstalled(userId)) {
5548                    return new String[]{ps.name};
5549                }
5550            }
5551        }
5552        return null;
5553    }
5554
5555    @Override
5556    public String getNameForUid(int uid) {
5557        // reader
5558        synchronized (mPackages) {
5559            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5560            if (obj instanceof SharedUserSetting) {
5561                final SharedUserSetting sus = (SharedUserSetting) obj;
5562                return sus.name + ":" + sus.userId;
5563            } else if (obj instanceof PackageSetting) {
5564                final PackageSetting ps = (PackageSetting) obj;
5565                return ps.name;
5566            }
5567        }
5568        return null;
5569    }
5570
5571    @Override
5572    public int getUidForSharedUser(String sharedUserName) {
5573        if(sharedUserName == null) {
5574            return -1;
5575        }
5576        // reader
5577        synchronized (mPackages) {
5578            SharedUserSetting suid;
5579            try {
5580                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5581                if (suid != null) {
5582                    return suid.userId;
5583                }
5584            } catch (PackageManagerException ignore) {
5585                // can't happen, but, still need to catch it
5586            }
5587            return -1;
5588        }
5589    }
5590
5591    @Override
5592    public int getFlagsForUid(int uid) {
5593        synchronized (mPackages) {
5594            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5595            if (obj instanceof SharedUserSetting) {
5596                final SharedUserSetting sus = (SharedUserSetting) obj;
5597                return sus.pkgFlags;
5598            } else if (obj instanceof PackageSetting) {
5599                final PackageSetting ps = (PackageSetting) obj;
5600                return ps.pkgFlags;
5601            }
5602        }
5603        return 0;
5604    }
5605
5606    @Override
5607    public int getPrivateFlagsForUid(int uid) {
5608        synchronized (mPackages) {
5609            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5610            if (obj instanceof SharedUserSetting) {
5611                final SharedUserSetting sus = (SharedUserSetting) obj;
5612                return sus.pkgPrivateFlags;
5613            } else if (obj instanceof PackageSetting) {
5614                final PackageSetting ps = (PackageSetting) obj;
5615                return ps.pkgPrivateFlags;
5616            }
5617        }
5618        return 0;
5619    }
5620
5621    @Override
5622    public boolean isUidPrivileged(int uid) {
5623        uid = UserHandle.getAppId(uid);
5624        // reader
5625        synchronized (mPackages) {
5626            Object obj = mSettings.getUserIdLPr(uid);
5627            if (obj instanceof SharedUserSetting) {
5628                final SharedUserSetting sus = (SharedUserSetting) obj;
5629                final Iterator<PackageSetting> it = sus.packages.iterator();
5630                while (it.hasNext()) {
5631                    if (it.next().isPrivileged()) {
5632                        return true;
5633                    }
5634                }
5635            } else if (obj instanceof PackageSetting) {
5636                final PackageSetting ps = (PackageSetting) obj;
5637                return ps.isPrivileged();
5638            }
5639        }
5640        return false;
5641    }
5642
5643    @Override
5644    public String[] getAppOpPermissionPackages(String permissionName) {
5645        synchronized (mPackages) {
5646            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5647            if (pkgs == null) {
5648                return null;
5649            }
5650            return pkgs.toArray(new String[pkgs.size()]);
5651        }
5652    }
5653
5654    @Override
5655    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5656            int flags, int userId) {
5657        return resolveIntentInternal(
5658                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
5659    }
5660
5661    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5662            int flags, int userId, boolean includeInstantApps) {
5663        try {
5664            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5665
5666            if (!sUserManager.exists(userId)) return null;
5667            final int callingUid = Binder.getCallingUid();
5668            flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
5669            enforceCrossUserPermission(callingUid, userId,
5670                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5671
5672            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5673            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5674                    flags, userId, includeInstantApps);
5675            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5676
5677            final ResolveInfo bestChoice =
5678                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5679            return bestChoice;
5680        } finally {
5681            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5682        }
5683    }
5684
5685    @Override
5686    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5687        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5688            throw new SecurityException(
5689                    "findPersistentPreferredActivity can only be run by the system");
5690        }
5691        if (!sUserManager.exists(userId)) {
5692            return null;
5693        }
5694        final int callingUid = Binder.getCallingUid();
5695        intent = updateIntentForResolve(intent);
5696        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5697        final int flags = updateFlagsForResolve(
5698                0, userId, intent, callingUid, false /*includeInstantApps*/);
5699        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5700                userId);
5701        synchronized (mPackages) {
5702            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5703                    userId);
5704        }
5705    }
5706
5707    @Override
5708    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5709            IntentFilter filter, int match, ComponentName activity) {
5710        final int userId = UserHandle.getCallingUserId();
5711        if (DEBUG_PREFERRED) {
5712            Log.v(TAG, "setLastChosenActivity intent=" + intent
5713                + " resolvedType=" + resolvedType
5714                + " flags=" + flags
5715                + " filter=" + filter
5716                + " match=" + match
5717                + " activity=" + activity);
5718            filter.dump(new PrintStreamPrinter(System.out), "    ");
5719        }
5720        intent.setComponent(null);
5721        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5722                userId);
5723        // Find any earlier preferred or last chosen entries and nuke them
5724        findPreferredActivity(intent, resolvedType,
5725                flags, query, 0, false, true, false, userId);
5726        // Add the new activity as the last chosen for this filter
5727        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5728                "Setting last chosen");
5729    }
5730
5731    @Override
5732    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5733        final int userId = UserHandle.getCallingUserId();
5734        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5735        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5736                userId);
5737        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5738                false, false, false, userId);
5739    }
5740
5741    /**
5742     * Returns whether or not instant apps have been disabled remotely.
5743     */
5744    private boolean isEphemeralDisabled() {
5745        return mEphemeralAppsDisabled;
5746    }
5747
5748    private boolean isEphemeralAllowed(
5749            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5750            boolean skipPackageCheck) {
5751        final int callingUser = UserHandle.getCallingUserId();
5752        if (mInstantAppResolverConnection == null) {
5753            return false;
5754        }
5755        if (mInstantAppInstallerActivity == null) {
5756            return false;
5757        }
5758        if (intent.getComponent() != null) {
5759            return false;
5760        }
5761        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5762            return false;
5763        }
5764        if (!skipPackageCheck && intent.getPackage() != null) {
5765            return false;
5766        }
5767        final boolean isWebUri = hasWebURI(intent);
5768        if (!isWebUri || intent.getData().getHost() == null) {
5769            return false;
5770        }
5771        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5772        // Or if there's already an ephemeral app installed that handles the action
5773        synchronized (mPackages) {
5774            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5775            for (int n = 0; n < count; n++) {
5776                final ResolveInfo info = resolvedActivities.get(n);
5777                final String packageName = info.activityInfo.packageName;
5778                final PackageSetting ps = mSettings.mPackages.get(packageName);
5779                if (ps != null) {
5780                    // only check domain verification status if the app is not a browser
5781                    if (!info.handleAllWebDataURI) {
5782                        // Try to get the status from User settings first
5783                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5784                        final int status = (int) (packedStatus >> 32);
5785                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5786                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5787                            if (DEBUG_EPHEMERAL) {
5788                                Slog.v(TAG, "DENY instant app;"
5789                                    + " pkg: " + packageName + ", status: " + status);
5790                            }
5791                            return false;
5792                        }
5793                    }
5794                    if (ps.getInstantApp(userId)) {
5795                        if (DEBUG_EPHEMERAL) {
5796                            Slog.v(TAG, "DENY instant app installed;"
5797                                    + " pkg: " + packageName);
5798                        }
5799                        return false;
5800                    }
5801                }
5802            }
5803        }
5804        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5805        return true;
5806    }
5807
5808    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5809            Intent origIntent, String resolvedType, String callingPackage,
5810            int userId) {
5811        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5812                new InstantAppRequest(responseObj, origIntent, resolvedType,
5813                        callingPackage, userId));
5814        mHandler.sendMessage(msg);
5815    }
5816
5817    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5818            int flags, List<ResolveInfo> query, int userId) {
5819        if (query != null) {
5820            final int N = query.size();
5821            if (N == 1) {
5822                return query.get(0);
5823            } else if (N > 1) {
5824                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5825                // If there is more than one activity with the same priority,
5826                // then let the user decide between them.
5827                ResolveInfo r0 = query.get(0);
5828                ResolveInfo r1 = query.get(1);
5829                if (DEBUG_INTENT_MATCHING || debug) {
5830                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5831                            + r1.activityInfo.name + "=" + r1.priority);
5832                }
5833                // If the first activity has a higher priority, or a different
5834                // default, then it is always desirable to pick it.
5835                if (r0.priority != r1.priority
5836                        || r0.preferredOrder != r1.preferredOrder
5837                        || r0.isDefault != r1.isDefault) {
5838                    return query.get(0);
5839                }
5840                // If we have saved a preference for a preferred activity for
5841                // this Intent, use that.
5842                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5843                        flags, query, r0.priority, true, false, debug, userId);
5844                if (ri != null) {
5845                    return ri;
5846                }
5847                // If we have an ephemeral app, use it
5848                for (int i = 0; i < N; i++) {
5849                    ri = query.get(i);
5850                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5851                        return ri;
5852                    }
5853                }
5854                ri = new ResolveInfo(mResolveInfo);
5855                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5856                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5857                // If all of the options come from the same package, show the application's
5858                // label and icon instead of the generic resolver's.
5859                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5860                // and then throw away the ResolveInfo itself, meaning that the caller loses
5861                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5862                // a fallback for this case; we only set the target package's resources on
5863                // the ResolveInfo, not the ActivityInfo.
5864                final String intentPackage = intent.getPackage();
5865                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5866                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5867                    ri.resolvePackageName = intentPackage;
5868                    if (userNeedsBadging(userId)) {
5869                        ri.noResourceId = true;
5870                    } else {
5871                        ri.icon = appi.icon;
5872                    }
5873                    ri.iconResourceId = appi.icon;
5874                    ri.labelRes = appi.labelRes;
5875                }
5876                ri.activityInfo.applicationInfo = new ApplicationInfo(
5877                        ri.activityInfo.applicationInfo);
5878                if (userId != 0) {
5879                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5880                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5881                }
5882                // Make sure that the resolver is displayable in car mode
5883                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5884                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5885                return ri;
5886            }
5887        }
5888        return null;
5889    }
5890
5891    /**
5892     * Return true if the given list is not empty and all of its contents have
5893     * an activityInfo with the given package name.
5894     */
5895    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5896        if (ArrayUtils.isEmpty(list)) {
5897            return false;
5898        }
5899        for (int i = 0, N = list.size(); i < N; i++) {
5900            final ResolveInfo ri = list.get(i);
5901            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5902            if (ai == null || !packageName.equals(ai.packageName)) {
5903                return false;
5904            }
5905        }
5906        return true;
5907    }
5908
5909    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5910            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5911        final int N = query.size();
5912        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5913                .get(userId);
5914        // Get the list of persistent preferred activities that handle the intent
5915        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5916        List<PersistentPreferredActivity> pprefs = ppir != null
5917                ? ppir.queryIntent(intent, resolvedType,
5918                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5919                        userId)
5920                : null;
5921        if (pprefs != null && pprefs.size() > 0) {
5922            final int M = pprefs.size();
5923            for (int i=0; i<M; i++) {
5924                final PersistentPreferredActivity ppa = pprefs.get(i);
5925                if (DEBUG_PREFERRED || debug) {
5926                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5927                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5928                            + "\n  component=" + ppa.mComponent);
5929                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5930                }
5931                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5932                        flags | MATCH_DISABLED_COMPONENTS, userId);
5933                if (DEBUG_PREFERRED || debug) {
5934                    Slog.v(TAG, "Found persistent preferred activity:");
5935                    if (ai != null) {
5936                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5937                    } else {
5938                        Slog.v(TAG, "  null");
5939                    }
5940                }
5941                if (ai == null) {
5942                    // This previously registered persistent preferred activity
5943                    // component is no longer known. Ignore it and do NOT remove it.
5944                    continue;
5945                }
5946                for (int j=0; j<N; j++) {
5947                    final ResolveInfo ri = query.get(j);
5948                    if (!ri.activityInfo.applicationInfo.packageName
5949                            .equals(ai.applicationInfo.packageName)) {
5950                        continue;
5951                    }
5952                    if (!ri.activityInfo.name.equals(ai.name)) {
5953                        continue;
5954                    }
5955                    //  Found a persistent preference that can handle the intent.
5956                    if (DEBUG_PREFERRED || debug) {
5957                        Slog.v(TAG, "Returning persistent preferred activity: " +
5958                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5959                    }
5960                    return ri;
5961                }
5962            }
5963        }
5964        return null;
5965    }
5966
5967    // TODO: handle preferred activities missing while user has amnesia
5968    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5969            List<ResolveInfo> query, int priority, boolean always,
5970            boolean removeMatches, boolean debug, int userId) {
5971        if (!sUserManager.exists(userId)) return null;
5972        final int callingUid = Binder.getCallingUid();
5973        flags = updateFlagsForResolve(
5974                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5975        intent = updateIntentForResolve(intent);
5976        // writer
5977        synchronized (mPackages) {
5978            // Try to find a matching persistent preferred activity.
5979            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5980                    debug, userId);
5981
5982            // If a persistent preferred activity matched, use it.
5983            if (pri != null) {
5984                return pri;
5985            }
5986
5987            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5988            // Get the list of preferred activities that handle the intent
5989            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5990            List<PreferredActivity> prefs = pir != null
5991                    ? pir.queryIntent(intent, resolvedType,
5992                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5993                            userId)
5994                    : null;
5995            if (prefs != null && prefs.size() > 0) {
5996                boolean changed = false;
5997                try {
5998                    // First figure out how good the original match set is.
5999                    // We will only allow preferred activities that came
6000                    // from the same match quality.
6001                    int match = 0;
6002
6003                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6004
6005                    final int N = query.size();
6006                    for (int j=0; j<N; j++) {
6007                        final ResolveInfo ri = query.get(j);
6008                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6009                                + ": 0x" + Integer.toHexString(match));
6010                        if (ri.match > match) {
6011                            match = ri.match;
6012                        }
6013                    }
6014
6015                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6016                            + Integer.toHexString(match));
6017
6018                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6019                    final int M = prefs.size();
6020                    for (int i=0; i<M; i++) {
6021                        final PreferredActivity pa = prefs.get(i);
6022                        if (DEBUG_PREFERRED || debug) {
6023                            Slog.v(TAG, "Checking PreferredActivity ds="
6024                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6025                                    + "\n  component=" + pa.mPref.mComponent);
6026                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6027                        }
6028                        if (pa.mPref.mMatch != match) {
6029                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6030                                    + Integer.toHexString(pa.mPref.mMatch));
6031                            continue;
6032                        }
6033                        // If it's not an "always" type preferred activity and that's what we're
6034                        // looking for, skip it.
6035                        if (always && !pa.mPref.mAlways) {
6036                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6037                            continue;
6038                        }
6039                        final ActivityInfo ai = getActivityInfo(
6040                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6041                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6042                                userId);
6043                        if (DEBUG_PREFERRED || debug) {
6044                            Slog.v(TAG, "Found preferred activity:");
6045                            if (ai != null) {
6046                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6047                            } else {
6048                                Slog.v(TAG, "  null");
6049                            }
6050                        }
6051                        if (ai == null) {
6052                            // This previously registered preferred activity
6053                            // component is no longer known.  Most likely an update
6054                            // to the app was installed and in the new version this
6055                            // component no longer exists.  Clean it up by removing
6056                            // it from the preferred activities list, and skip it.
6057                            Slog.w(TAG, "Removing dangling preferred activity: "
6058                                    + pa.mPref.mComponent);
6059                            pir.removeFilter(pa);
6060                            changed = true;
6061                            continue;
6062                        }
6063                        for (int j=0; j<N; j++) {
6064                            final ResolveInfo ri = query.get(j);
6065                            if (!ri.activityInfo.applicationInfo.packageName
6066                                    .equals(ai.applicationInfo.packageName)) {
6067                                continue;
6068                            }
6069                            if (!ri.activityInfo.name.equals(ai.name)) {
6070                                continue;
6071                            }
6072
6073                            if (removeMatches) {
6074                                pir.removeFilter(pa);
6075                                changed = true;
6076                                if (DEBUG_PREFERRED) {
6077                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6078                                }
6079                                break;
6080                            }
6081
6082                            // Okay we found a previously set preferred or last chosen app.
6083                            // If the result set is different from when this
6084                            // was created, we need to clear it and re-ask the
6085                            // user their preference, if we're looking for an "always" type entry.
6086                            if (always && !pa.mPref.sameSet(query)) {
6087                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6088                                        + intent + " type " + resolvedType);
6089                                if (DEBUG_PREFERRED) {
6090                                    Slog.v(TAG, "Removing preferred activity since set changed "
6091                                            + pa.mPref.mComponent);
6092                                }
6093                                pir.removeFilter(pa);
6094                                // Re-add the filter as a "last chosen" entry (!always)
6095                                PreferredActivity lastChosen = new PreferredActivity(
6096                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6097                                pir.addFilter(lastChosen);
6098                                changed = true;
6099                                return null;
6100                            }
6101
6102                            // Yay! Either the set matched or we're looking for the last chosen
6103                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6104                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6105                            return ri;
6106                        }
6107                    }
6108                } finally {
6109                    if (changed) {
6110                        if (DEBUG_PREFERRED) {
6111                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6112                        }
6113                        scheduleWritePackageRestrictionsLocked(userId);
6114                    }
6115                }
6116            }
6117        }
6118        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6119        return null;
6120    }
6121
6122    /*
6123     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6124     */
6125    @Override
6126    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6127            int targetUserId) {
6128        mContext.enforceCallingOrSelfPermission(
6129                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6130        List<CrossProfileIntentFilter> matches =
6131                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6132        if (matches != null) {
6133            int size = matches.size();
6134            for (int i = 0; i < size; i++) {
6135                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6136            }
6137        }
6138        if (hasWebURI(intent)) {
6139            // cross-profile app linking works only towards the parent.
6140            final int callingUid = Binder.getCallingUid();
6141            final UserInfo parent = getProfileParent(sourceUserId);
6142            synchronized(mPackages) {
6143                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6144                        false /*includeInstantApps*/);
6145                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6146                        intent, resolvedType, flags, sourceUserId, parent.id);
6147                return xpDomainInfo != null;
6148            }
6149        }
6150        return false;
6151    }
6152
6153    private UserInfo getProfileParent(int userId) {
6154        final long identity = Binder.clearCallingIdentity();
6155        try {
6156            return sUserManager.getProfileParent(userId);
6157        } finally {
6158            Binder.restoreCallingIdentity(identity);
6159        }
6160    }
6161
6162    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6163            String resolvedType, int userId) {
6164        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6165        if (resolver != null) {
6166            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6167        }
6168        return null;
6169    }
6170
6171    @Override
6172    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6173            String resolvedType, int flags, int userId) {
6174        try {
6175            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6176
6177            return new ParceledListSlice<>(
6178                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6179        } finally {
6180            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6181        }
6182    }
6183
6184    /**
6185     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6186     * instant, returns {@code null}.
6187     */
6188    private String getInstantAppPackageName(int callingUid) {
6189        // If the caller is an isolated app use the owner's uid for the lookup.
6190        if (Process.isIsolated(callingUid)) {
6191            callingUid = mIsolatedOwners.get(callingUid);
6192        }
6193        final int appId = UserHandle.getAppId(callingUid);
6194        synchronized (mPackages) {
6195            final Object obj = mSettings.getUserIdLPr(appId);
6196            if (obj instanceof PackageSetting) {
6197                final PackageSetting ps = (PackageSetting) obj;
6198                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6199                return isInstantApp ? ps.pkg.packageName : null;
6200            }
6201        }
6202        return null;
6203    }
6204
6205    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6206            String resolvedType, int flags, int userId) {
6207        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6208    }
6209
6210    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6211            String resolvedType, int flags, int userId, boolean includeInstantApps) {
6212        if (!sUserManager.exists(userId)) return Collections.emptyList();
6213        final int callingUid = Binder.getCallingUid();
6214        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6215        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
6216        enforceCrossUserPermission(callingUid, userId,
6217                false /* requireFullPermission */, false /* checkShell */,
6218                "query intent activities");
6219        ComponentName comp = intent.getComponent();
6220        if (comp == null) {
6221            if (intent.getSelector() != null) {
6222                intent = intent.getSelector();
6223                comp = intent.getComponent();
6224            }
6225        }
6226
6227        if (comp != null) {
6228            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6229            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6230            if (ai != null) {
6231                // When specifying an explicit component, we prevent the activity from being
6232                // used when either 1) the calling package is normal and the activity is within
6233                // an ephemeral application or 2) the calling package is ephemeral and the
6234                // activity is not visible to ephemeral applications.
6235                final boolean matchInstantApp =
6236                        (flags & PackageManager.MATCH_INSTANT) != 0;
6237                final boolean matchVisibleToInstantAppOnly =
6238                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6239                final boolean isCallerInstantApp =
6240                        instantAppPkgName != null;
6241                final boolean isTargetSameInstantApp =
6242                        comp.getPackageName().equals(instantAppPkgName);
6243                final boolean isTargetInstantApp =
6244                        (ai.applicationInfo.privateFlags
6245                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6246                final boolean isTargetHiddenFromInstantApp =
6247                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6248                final boolean blockResolution =
6249                        !isTargetSameInstantApp
6250                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6251                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6252                                        && isTargetHiddenFromInstantApp));
6253                if (!blockResolution) {
6254                    final ResolveInfo ri = new ResolveInfo();
6255                    ri.activityInfo = ai;
6256                    list.add(ri);
6257                }
6258            }
6259            return applyPostResolutionFilter(list, instantAppPkgName);
6260        }
6261
6262        // reader
6263        boolean sortResult = false;
6264        boolean addEphemeral = false;
6265        List<ResolveInfo> result;
6266        final String pkgName = intent.getPackage();
6267        final boolean ephemeralDisabled = isEphemeralDisabled();
6268        synchronized (mPackages) {
6269            if (pkgName == null) {
6270                List<CrossProfileIntentFilter> matchingFilters =
6271                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6272                // Check for results that need to skip the current profile.
6273                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6274                        resolvedType, flags, userId);
6275                if (xpResolveInfo != null) {
6276                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6277                    xpResult.add(xpResolveInfo);
6278                    return applyPostResolutionFilter(
6279                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6280                }
6281
6282                // Check for results in the current profile.
6283                result = filterIfNotSystemUser(mActivities.queryIntent(
6284                        intent, resolvedType, flags, userId), userId);
6285                addEphemeral = !ephemeralDisabled
6286                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6287                // Check for cross profile results.
6288                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6289                xpResolveInfo = queryCrossProfileIntents(
6290                        matchingFilters, intent, resolvedType, flags, userId,
6291                        hasNonNegativePriorityResult);
6292                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6293                    boolean isVisibleToUser = filterIfNotSystemUser(
6294                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6295                    if (isVisibleToUser) {
6296                        result.add(xpResolveInfo);
6297                        sortResult = true;
6298                    }
6299                }
6300                if (hasWebURI(intent)) {
6301                    CrossProfileDomainInfo xpDomainInfo = null;
6302                    final UserInfo parent = getProfileParent(userId);
6303                    if (parent != null) {
6304                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6305                                flags, userId, parent.id);
6306                    }
6307                    if (xpDomainInfo != null) {
6308                        if (xpResolveInfo != null) {
6309                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6310                            // in the result.
6311                            result.remove(xpResolveInfo);
6312                        }
6313                        if (result.size() == 0 && !addEphemeral) {
6314                            // No result in current profile, but found candidate in parent user.
6315                            // And we are not going to add emphemeral app, so we can return the
6316                            // result straight away.
6317                            result.add(xpDomainInfo.resolveInfo);
6318                            return applyPostResolutionFilter(result, instantAppPkgName);
6319                        }
6320                    } else if (result.size() <= 1 && !addEphemeral) {
6321                        // No result in parent user and <= 1 result in current profile, and we
6322                        // are not going to add emphemeral app, so we can return the result without
6323                        // further processing.
6324                        return applyPostResolutionFilter(result, instantAppPkgName);
6325                    }
6326                    // We have more than one candidate (combining results from current and parent
6327                    // profile), so we need filtering and sorting.
6328                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6329                            intent, flags, result, xpDomainInfo, userId);
6330                    sortResult = true;
6331                }
6332            } else {
6333                final PackageParser.Package pkg = mPackages.get(pkgName);
6334                if (pkg != null) {
6335                    return applyPostResolutionFilter(filterIfNotSystemUser(
6336                            mActivities.queryIntentForPackage(
6337                                    intent, resolvedType, flags, pkg.activities, userId),
6338                            userId), instantAppPkgName);
6339                } else {
6340                    // the caller wants to resolve for a particular package; however, there
6341                    // were no installed results, so, try to find an ephemeral result
6342                    addEphemeral = !ephemeralDisabled
6343                            && isEphemeralAllowed(
6344                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6345                    result = new ArrayList<ResolveInfo>();
6346                }
6347            }
6348        }
6349        if (addEphemeral) {
6350            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6351            final InstantAppRequest requestObject = new InstantAppRequest(
6352                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6353                    null /*callingPackage*/, userId);
6354            final AuxiliaryResolveInfo auxiliaryResponse =
6355                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6356                            mContext, mInstantAppResolverConnection, requestObject);
6357            if (auxiliaryResponse != null) {
6358                if (DEBUG_EPHEMERAL) {
6359                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6360                }
6361                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6362                final PackageSetting ps =
6363                        mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6364                if (ps != null) {
6365                    ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6366                            mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6367                    ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6368                    ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6369                    // make sure this resolver is the default
6370                    ephemeralInstaller.isDefault = true;
6371                    ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6372                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6373                    // add a non-generic filter
6374                    ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6375                    ephemeralInstaller.filter.addDataPath(
6376                            intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6377                    ephemeralInstaller.instantAppAvailable = true;
6378                    result.add(ephemeralInstaller);
6379                }
6380            }
6381            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6382        }
6383        if (sortResult) {
6384            Collections.sort(result, mResolvePrioritySorter);
6385        }
6386        return applyPostResolutionFilter(result, instantAppPkgName);
6387    }
6388
6389    private static class CrossProfileDomainInfo {
6390        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6391        ResolveInfo resolveInfo;
6392        /* Best domain verification status of the activities found in the other profile */
6393        int bestDomainVerificationStatus;
6394    }
6395
6396    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6397            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6398        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6399                sourceUserId)) {
6400            return null;
6401        }
6402        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6403                resolvedType, flags, parentUserId);
6404
6405        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6406            return null;
6407        }
6408        CrossProfileDomainInfo result = null;
6409        int size = resultTargetUser.size();
6410        for (int i = 0; i < size; i++) {
6411            ResolveInfo riTargetUser = resultTargetUser.get(i);
6412            // Intent filter verification is only for filters that specify a host. So don't return
6413            // those that handle all web uris.
6414            if (riTargetUser.handleAllWebDataURI) {
6415                continue;
6416            }
6417            String packageName = riTargetUser.activityInfo.packageName;
6418            PackageSetting ps = mSettings.mPackages.get(packageName);
6419            if (ps == null) {
6420                continue;
6421            }
6422            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6423            int status = (int)(verificationState >> 32);
6424            if (result == null) {
6425                result = new CrossProfileDomainInfo();
6426                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6427                        sourceUserId, parentUserId);
6428                result.bestDomainVerificationStatus = status;
6429            } else {
6430                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6431                        result.bestDomainVerificationStatus);
6432            }
6433        }
6434        // Don't consider matches with status NEVER across profiles.
6435        if (result != null && result.bestDomainVerificationStatus
6436                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6437            return null;
6438        }
6439        return result;
6440    }
6441
6442    /**
6443     * Verification statuses are ordered from the worse to the best, except for
6444     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6445     */
6446    private int bestDomainVerificationStatus(int status1, int status2) {
6447        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6448            return status2;
6449        }
6450        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6451            return status1;
6452        }
6453        return (int) MathUtils.max(status1, status2);
6454    }
6455
6456    private boolean isUserEnabled(int userId) {
6457        long callingId = Binder.clearCallingIdentity();
6458        try {
6459            UserInfo userInfo = sUserManager.getUserInfo(userId);
6460            return userInfo != null && userInfo.isEnabled();
6461        } finally {
6462            Binder.restoreCallingIdentity(callingId);
6463        }
6464    }
6465
6466    /**
6467     * Filter out activities with systemUserOnly flag set, when current user is not System.
6468     *
6469     * @return filtered list
6470     */
6471    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6472        if (userId == UserHandle.USER_SYSTEM) {
6473            return resolveInfos;
6474        }
6475        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6476            ResolveInfo info = resolveInfos.get(i);
6477            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6478                resolveInfos.remove(i);
6479            }
6480        }
6481        return resolveInfos;
6482    }
6483
6484    /**
6485     * Filters out ephemeral activities.
6486     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6487     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6488     *
6489     * @param resolveInfos The pre-filtered list of resolved activities
6490     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6491     *          is performed.
6492     * @return A filtered list of resolved activities.
6493     */
6494    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6495            String ephemeralPkgName) {
6496        // TODO: When adding on-demand split support for non-instant apps, remove this check
6497        // and always apply post filtering
6498        if (ephemeralPkgName == null) {
6499            return resolveInfos;
6500        }
6501        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6502            final ResolveInfo info = resolveInfos.get(i);
6503            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6504            // allow activities that are defined in the provided package
6505            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6506                if (info.activityInfo.splitName != null
6507                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6508                                info.activityInfo.splitName)) {
6509                    // requested activity is defined in a split that hasn't been installed yet.
6510                    // add the installer to the resolve list
6511                    if (DEBUG_EPHEMERAL) {
6512                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6513                    }
6514                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6515                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6516                            info.activityInfo.packageName, info.activityInfo.splitName,
6517                            info.activityInfo.applicationInfo.versionCode);
6518                    // make sure this resolver is the default
6519                    installerInfo.isDefault = true;
6520                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6521                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6522                    // add a non-generic filter
6523                    installerInfo.filter = new IntentFilter();
6524                    // load resources from the correct package
6525                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6526                    resolveInfos.set(i, installerInfo);
6527                }
6528                continue;
6529            }
6530            // allow activities that have been explicitly exposed to ephemeral apps
6531            if (!isEphemeralApp
6532                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6533                continue;
6534            }
6535            resolveInfos.remove(i);
6536        }
6537        return resolveInfos;
6538    }
6539
6540    /**
6541     * @param resolveInfos list of resolve infos in descending priority order
6542     * @return if the list contains a resolve info with non-negative priority
6543     */
6544    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6545        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6546    }
6547
6548    private static boolean hasWebURI(Intent intent) {
6549        if (intent.getData() == null) {
6550            return false;
6551        }
6552        final String scheme = intent.getScheme();
6553        if (TextUtils.isEmpty(scheme)) {
6554            return false;
6555        }
6556        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6557    }
6558
6559    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6560            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6561            int userId) {
6562        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6563
6564        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6565            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6566                    candidates.size());
6567        }
6568
6569        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6570        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6571        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6572        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6573        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6574        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6575
6576        synchronized (mPackages) {
6577            final int count = candidates.size();
6578            // First, try to use linked apps. Partition the candidates into four lists:
6579            // one for the final results, one for the "do not use ever", one for "undefined status"
6580            // and finally one for "browser app type".
6581            for (int n=0; n<count; n++) {
6582                ResolveInfo info = candidates.get(n);
6583                String packageName = info.activityInfo.packageName;
6584                PackageSetting ps = mSettings.mPackages.get(packageName);
6585                if (ps != null) {
6586                    // Add to the special match all list (Browser use case)
6587                    if (info.handleAllWebDataURI) {
6588                        matchAllList.add(info);
6589                        continue;
6590                    }
6591                    // Try to get the status from User settings first
6592                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6593                    int status = (int)(packedStatus >> 32);
6594                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6595                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6596                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6597                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6598                                    + " : linkgen=" + linkGeneration);
6599                        }
6600                        // Use link-enabled generation as preferredOrder, i.e.
6601                        // prefer newly-enabled over earlier-enabled.
6602                        info.preferredOrder = linkGeneration;
6603                        alwaysList.add(info);
6604                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6605                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6606                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6607                        }
6608                        neverList.add(info);
6609                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6610                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6611                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6612                        }
6613                        alwaysAskList.add(info);
6614                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6615                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6616                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6617                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6618                        }
6619                        undefinedList.add(info);
6620                    }
6621                }
6622            }
6623
6624            // We'll want to include browser possibilities in a few cases
6625            boolean includeBrowser = false;
6626
6627            // First try to add the "always" resolution(s) for the current user, if any
6628            if (alwaysList.size() > 0) {
6629                result.addAll(alwaysList);
6630            } else {
6631                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6632                result.addAll(undefinedList);
6633                // Maybe add one for the other profile.
6634                if (xpDomainInfo != null && (
6635                        xpDomainInfo.bestDomainVerificationStatus
6636                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6637                    result.add(xpDomainInfo.resolveInfo);
6638                }
6639                includeBrowser = true;
6640            }
6641
6642            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6643            // If there were 'always' entries their preferred order has been set, so we also
6644            // back that off to make the alternatives equivalent
6645            if (alwaysAskList.size() > 0) {
6646                for (ResolveInfo i : result) {
6647                    i.preferredOrder = 0;
6648                }
6649                result.addAll(alwaysAskList);
6650                includeBrowser = true;
6651            }
6652
6653            if (includeBrowser) {
6654                // Also add browsers (all of them or only the default one)
6655                if (DEBUG_DOMAIN_VERIFICATION) {
6656                    Slog.v(TAG, "   ...including browsers in candidate set");
6657                }
6658                if ((matchFlags & MATCH_ALL) != 0) {
6659                    result.addAll(matchAllList);
6660                } else {
6661                    // Browser/generic handling case.  If there's a default browser, go straight
6662                    // to that (but only if there is no other higher-priority match).
6663                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6664                    int maxMatchPrio = 0;
6665                    ResolveInfo defaultBrowserMatch = null;
6666                    final int numCandidates = matchAllList.size();
6667                    for (int n = 0; n < numCandidates; n++) {
6668                        ResolveInfo info = matchAllList.get(n);
6669                        // track the highest overall match priority...
6670                        if (info.priority > maxMatchPrio) {
6671                            maxMatchPrio = info.priority;
6672                        }
6673                        // ...and the highest-priority default browser match
6674                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6675                            if (defaultBrowserMatch == null
6676                                    || (defaultBrowserMatch.priority < info.priority)) {
6677                                if (debug) {
6678                                    Slog.v(TAG, "Considering default browser match " + info);
6679                                }
6680                                defaultBrowserMatch = info;
6681                            }
6682                        }
6683                    }
6684                    if (defaultBrowserMatch != null
6685                            && defaultBrowserMatch.priority >= maxMatchPrio
6686                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6687                    {
6688                        if (debug) {
6689                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6690                        }
6691                        result.add(defaultBrowserMatch);
6692                    } else {
6693                        result.addAll(matchAllList);
6694                    }
6695                }
6696
6697                // If there is nothing selected, add all candidates and remove the ones that the user
6698                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6699                if (result.size() == 0) {
6700                    result.addAll(candidates);
6701                    result.removeAll(neverList);
6702                }
6703            }
6704        }
6705        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6706            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6707                    result.size());
6708            for (ResolveInfo info : result) {
6709                Slog.v(TAG, "  + " + info.activityInfo);
6710            }
6711        }
6712        return result;
6713    }
6714
6715    // Returns a packed value as a long:
6716    //
6717    // high 'int'-sized word: link status: undefined/ask/never/always.
6718    // low 'int'-sized word: relative priority among 'always' results.
6719    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6720        long result = ps.getDomainVerificationStatusForUser(userId);
6721        // if none available, get the master status
6722        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6723            if (ps.getIntentFilterVerificationInfo() != null) {
6724                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6725            }
6726        }
6727        return result;
6728    }
6729
6730    private ResolveInfo querySkipCurrentProfileIntents(
6731            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6732            int flags, int sourceUserId) {
6733        if (matchingFilters != null) {
6734            int size = matchingFilters.size();
6735            for (int i = 0; i < size; i ++) {
6736                CrossProfileIntentFilter filter = matchingFilters.get(i);
6737                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6738                    // Checking if there are activities in the target user that can handle the
6739                    // intent.
6740                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6741                            resolvedType, flags, sourceUserId);
6742                    if (resolveInfo != null) {
6743                        return resolveInfo;
6744                    }
6745                }
6746            }
6747        }
6748        return null;
6749    }
6750
6751    // Return matching ResolveInfo in target user if any.
6752    private ResolveInfo queryCrossProfileIntents(
6753            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6754            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6755        if (matchingFilters != null) {
6756            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6757            // match the same intent. For performance reasons, it is better not to
6758            // run queryIntent twice for the same userId
6759            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6760            int size = matchingFilters.size();
6761            for (int i = 0; i < size; i++) {
6762                CrossProfileIntentFilter filter = matchingFilters.get(i);
6763                int targetUserId = filter.getTargetUserId();
6764                boolean skipCurrentProfile =
6765                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6766                boolean skipCurrentProfileIfNoMatchFound =
6767                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6768                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6769                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6770                    // Checking if there are activities in the target user that can handle the
6771                    // intent.
6772                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6773                            resolvedType, flags, sourceUserId);
6774                    if (resolveInfo != null) return resolveInfo;
6775                    alreadyTriedUserIds.put(targetUserId, true);
6776                }
6777            }
6778        }
6779        return null;
6780    }
6781
6782    /**
6783     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6784     * will forward the intent to the filter's target user.
6785     * Otherwise, returns null.
6786     */
6787    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6788            String resolvedType, int flags, int sourceUserId) {
6789        int targetUserId = filter.getTargetUserId();
6790        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6791                resolvedType, flags, targetUserId);
6792        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6793            // If all the matches in the target profile are suspended, return null.
6794            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6795                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6796                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6797                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6798                            targetUserId);
6799                }
6800            }
6801        }
6802        return null;
6803    }
6804
6805    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6806            int sourceUserId, int targetUserId) {
6807        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6808        long ident = Binder.clearCallingIdentity();
6809        boolean targetIsProfile;
6810        try {
6811            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6812        } finally {
6813            Binder.restoreCallingIdentity(ident);
6814        }
6815        String className;
6816        if (targetIsProfile) {
6817            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6818        } else {
6819            className = FORWARD_INTENT_TO_PARENT;
6820        }
6821        ComponentName forwardingActivityComponentName = new ComponentName(
6822                mAndroidApplication.packageName, className);
6823        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6824                sourceUserId);
6825        if (!targetIsProfile) {
6826            forwardingActivityInfo.showUserIcon = targetUserId;
6827            forwardingResolveInfo.noResourceId = true;
6828        }
6829        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6830        forwardingResolveInfo.priority = 0;
6831        forwardingResolveInfo.preferredOrder = 0;
6832        forwardingResolveInfo.match = 0;
6833        forwardingResolveInfo.isDefault = true;
6834        forwardingResolveInfo.filter = filter;
6835        forwardingResolveInfo.targetUserId = targetUserId;
6836        return forwardingResolveInfo;
6837    }
6838
6839    @Override
6840    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6841            Intent[] specifics, String[] specificTypes, Intent intent,
6842            String resolvedType, int flags, int userId) {
6843        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6844                specificTypes, intent, resolvedType, flags, userId));
6845    }
6846
6847    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6848            Intent[] specifics, String[] specificTypes, Intent intent,
6849            String resolvedType, int flags, int userId) {
6850        if (!sUserManager.exists(userId)) return Collections.emptyList();
6851        final int callingUid = Binder.getCallingUid();
6852        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
6853                false /*includeInstantApps*/);
6854        enforceCrossUserPermission(callingUid, userId,
6855                false /*requireFullPermission*/, false /*checkShell*/,
6856                "query intent activity options");
6857        final String resultsAction = intent.getAction();
6858
6859        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6860                | PackageManager.GET_RESOLVED_FILTER, userId);
6861
6862        if (DEBUG_INTENT_MATCHING) {
6863            Log.v(TAG, "Query " + intent + ": " + results);
6864        }
6865
6866        int specificsPos = 0;
6867        int N;
6868
6869        // todo: note that the algorithm used here is O(N^2).  This
6870        // isn't a problem in our current environment, but if we start running
6871        // into situations where we have more than 5 or 10 matches then this
6872        // should probably be changed to something smarter...
6873
6874        // First we go through and resolve each of the specific items
6875        // that were supplied, taking care of removing any corresponding
6876        // duplicate items in the generic resolve list.
6877        if (specifics != null) {
6878            for (int i=0; i<specifics.length; i++) {
6879                final Intent sintent = specifics[i];
6880                if (sintent == null) {
6881                    continue;
6882                }
6883
6884                if (DEBUG_INTENT_MATCHING) {
6885                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6886                }
6887
6888                String action = sintent.getAction();
6889                if (resultsAction != null && resultsAction.equals(action)) {
6890                    // If this action was explicitly requested, then don't
6891                    // remove things that have it.
6892                    action = null;
6893                }
6894
6895                ResolveInfo ri = null;
6896                ActivityInfo ai = null;
6897
6898                ComponentName comp = sintent.getComponent();
6899                if (comp == null) {
6900                    ri = resolveIntent(
6901                        sintent,
6902                        specificTypes != null ? specificTypes[i] : null,
6903                            flags, userId);
6904                    if (ri == null) {
6905                        continue;
6906                    }
6907                    if (ri == mResolveInfo) {
6908                        // ACK!  Must do something better with this.
6909                    }
6910                    ai = ri.activityInfo;
6911                    comp = new ComponentName(ai.applicationInfo.packageName,
6912                            ai.name);
6913                } else {
6914                    ai = getActivityInfo(comp, flags, userId);
6915                    if (ai == null) {
6916                        continue;
6917                    }
6918                }
6919
6920                // Look for any generic query activities that are duplicates
6921                // of this specific one, and remove them from the results.
6922                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6923                N = results.size();
6924                int j;
6925                for (j=specificsPos; j<N; j++) {
6926                    ResolveInfo sri = results.get(j);
6927                    if ((sri.activityInfo.name.equals(comp.getClassName())
6928                            && sri.activityInfo.applicationInfo.packageName.equals(
6929                                    comp.getPackageName()))
6930                        || (action != null && sri.filter.matchAction(action))) {
6931                        results.remove(j);
6932                        if (DEBUG_INTENT_MATCHING) Log.v(
6933                            TAG, "Removing duplicate item from " + j
6934                            + " due to specific " + specificsPos);
6935                        if (ri == null) {
6936                            ri = sri;
6937                        }
6938                        j--;
6939                        N--;
6940                    }
6941                }
6942
6943                // Add this specific item to its proper place.
6944                if (ri == null) {
6945                    ri = new ResolveInfo();
6946                    ri.activityInfo = ai;
6947                }
6948                results.add(specificsPos, ri);
6949                ri.specificIndex = i;
6950                specificsPos++;
6951            }
6952        }
6953
6954        // Now we go through the remaining generic results and remove any
6955        // duplicate actions that are found here.
6956        N = results.size();
6957        for (int i=specificsPos; i<N-1; i++) {
6958            final ResolveInfo rii = results.get(i);
6959            if (rii.filter == null) {
6960                continue;
6961            }
6962
6963            // Iterate over all of the actions of this result's intent
6964            // filter...  typically this should be just one.
6965            final Iterator<String> it = rii.filter.actionsIterator();
6966            if (it == null) {
6967                continue;
6968            }
6969            while (it.hasNext()) {
6970                final String action = it.next();
6971                if (resultsAction != null && resultsAction.equals(action)) {
6972                    // If this action was explicitly requested, then don't
6973                    // remove things that have it.
6974                    continue;
6975                }
6976                for (int j=i+1; j<N; j++) {
6977                    final ResolveInfo rij = results.get(j);
6978                    if (rij.filter != null && rij.filter.hasAction(action)) {
6979                        results.remove(j);
6980                        if (DEBUG_INTENT_MATCHING) Log.v(
6981                            TAG, "Removing duplicate item from " + j
6982                            + " due to action " + action + " at " + i);
6983                        j--;
6984                        N--;
6985                    }
6986                }
6987            }
6988
6989            // If the caller didn't request filter information, drop it now
6990            // so we don't have to marshall/unmarshall it.
6991            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6992                rii.filter = null;
6993            }
6994        }
6995
6996        // Filter out the caller activity if so requested.
6997        if (caller != null) {
6998            N = results.size();
6999            for (int i=0; i<N; i++) {
7000                ActivityInfo ainfo = results.get(i).activityInfo;
7001                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7002                        && caller.getClassName().equals(ainfo.name)) {
7003                    results.remove(i);
7004                    break;
7005                }
7006            }
7007        }
7008
7009        // If the caller didn't request filter information,
7010        // drop them now so we don't have to
7011        // marshall/unmarshall it.
7012        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7013            N = results.size();
7014            for (int i=0; i<N; i++) {
7015                results.get(i).filter = null;
7016            }
7017        }
7018
7019        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7020        return results;
7021    }
7022
7023    @Override
7024    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7025            String resolvedType, int flags, int userId) {
7026        return new ParceledListSlice<>(
7027                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7028    }
7029
7030    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7031            String resolvedType, int flags, int userId) {
7032        if (!sUserManager.exists(userId)) return Collections.emptyList();
7033        final int callingUid = Binder.getCallingUid();
7034        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7035                false /*includeInstantApps*/);
7036        ComponentName comp = intent.getComponent();
7037        if (comp == null) {
7038            if (intent.getSelector() != null) {
7039                intent = intent.getSelector();
7040                comp = intent.getComponent();
7041            }
7042        }
7043        if (comp != null) {
7044            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7045            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7046            if (ai != null) {
7047                ResolveInfo ri = new ResolveInfo();
7048                ri.activityInfo = ai;
7049                list.add(ri);
7050            }
7051            return list;
7052        }
7053
7054        // reader
7055        synchronized (mPackages) {
7056            String pkgName = intent.getPackage();
7057            if (pkgName == null) {
7058                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7059            }
7060            final PackageParser.Package pkg = mPackages.get(pkgName);
7061            if (pkg != null) {
7062                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7063                        userId);
7064            }
7065            return Collections.emptyList();
7066        }
7067    }
7068
7069    @Override
7070    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7071        final int callingUid = Binder.getCallingUid();
7072        return resolveServiceInternal(
7073                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7074    }
7075
7076    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7077            int userId, int callingUid, boolean includeInstantApps) {
7078        if (!sUserManager.exists(userId)) return null;
7079        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7080        List<ResolveInfo> query = queryIntentServicesInternal(
7081                intent, resolvedType, flags, userId, callingUid, includeInstantApps);
7082        if (query != null) {
7083            if (query.size() >= 1) {
7084                // If there is more than one service with the same priority,
7085                // just arbitrarily pick the first one.
7086                return query.get(0);
7087            }
7088        }
7089        return null;
7090    }
7091
7092    @Override
7093    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7094            String resolvedType, int flags, int userId) {
7095        final int callingUid = Binder.getCallingUid();
7096        return new ParceledListSlice<>(queryIntentServicesInternal(
7097                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7098    }
7099
7100    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7101            String resolvedType, int flags, int userId, int callingUid,
7102            boolean includeInstantApps) {
7103        if (!sUserManager.exists(userId)) return Collections.emptyList();
7104        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7105        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7106        ComponentName comp = intent.getComponent();
7107        if (comp == null) {
7108            if (intent.getSelector() != null) {
7109                intent = intent.getSelector();
7110                comp = intent.getComponent();
7111            }
7112        }
7113        if (comp != null) {
7114            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7115            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7116            if (si != null) {
7117                // When specifying an explicit component, we prevent the service from being
7118                // used when either 1) the service is in an instant application and the
7119                // caller is not the same instant application or 2) the calling package is
7120                // ephemeral and the activity is not visible to ephemeral applications.
7121                final boolean matchInstantApp =
7122                        (flags & PackageManager.MATCH_INSTANT) != 0;
7123                final boolean matchVisibleToInstantAppOnly =
7124                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7125                final boolean isCallerInstantApp =
7126                        instantAppPkgName != null;
7127                final boolean isTargetSameInstantApp =
7128                        comp.getPackageName().equals(instantAppPkgName);
7129                final boolean isTargetInstantApp =
7130                        (si.applicationInfo.privateFlags
7131                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7132                final boolean isTargetHiddenFromInstantApp =
7133                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
7134                final boolean blockResolution =
7135                        !isTargetSameInstantApp
7136                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7137                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7138                                        && isTargetHiddenFromInstantApp));
7139                if (!blockResolution) {
7140                    final ResolveInfo ri = new ResolveInfo();
7141                    ri.serviceInfo = si;
7142                    list.add(ri);
7143                }
7144            }
7145            return list;
7146        }
7147
7148        // reader
7149        synchronized (mPackages) {
7150            String pkgName = intent.getPackage();
7151            if (pkgName == null) {
7152                return applyPostServiceResolutionFilter(
7153                        mServices.queryIntent(intent, resolvedType, flags, userId),
7154                        instantAppPkgName);
7155            }
7156            final PackageParser.Package pkg = mPackages.get(pkgName);
7157            if (pkg != null) {
7158                return applyPostServiceResolutionFilter(
7159                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7160                                userId),
7161                        instantAppPkgName);
7162            }
7163            return Collections.emptyList();
7164        }
7165    }
7166
7167    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7168            String instantAppPkgName) {
7169        // TODO: When adding on-demand split support for non-instant apps, remove this check
7170        // and always apply post filtering
7171        if (instantAppPkgName == null) {
7172            return resolveInfos;
7173        }
7174        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7175            final ResolveInfo info = resolveInfos.get(i);
7176            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7177            // allow services that are defined in the provided package
7178            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7179                if (info.serviceInfo.splitName != null
7180                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7181                                info.serviceInfo.splitName)) {
7182                    // requested service is defined in a split that hasn't been installed yet.
7183                    // add the installer to the resolve list
7184                    if (DEBUG_EPHEMERAL) {
7185                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7186                    }
7187                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7188                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7189                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7190                            info.serviceInfo.applicationInfo.versionCode);
7191                    // make sure this resolver is the default
7192                    installerInfo.isDefault = true;
7193                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7194                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7195                    // add a non-generic filter
7196                    installerInfo.filter = new IntentFilter();
7197                    // load resources from the correct package
7198                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7199                    resolveInfos.set(i, installerInfo);
7200                }
7201                continue;
7202            }
7203            // allow services that have been explicitly exposed to ephemeral apps
7204            if (!isEphemeralApp
7205                    && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
7206                continue;
7207            }
7208            resolveInfos.remove(i);
7209        }
7210        return resolveInfos;
7211    }
7212
7213    @Override
7214    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7215            String resolvedType, int flags, int userId) {
7216        return new ParceledListSlice<>(
7217                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7218    }
7219
7220    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7221            Intent intent, String resolvedType, int flags, int userId) {
7222        if (!sUserManager.exists(userId)) return Collections.emptyList();
7223        final int callingUid = Binder.getCallingUid();
7224        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7225        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7226                false /*includeInstantApps*/);
7227        ComponentName comp = intent.getComponent();
7228        if (comp == null) {
7229            if (intent.getSelector() != null) {
7230                intent = intent.getSelector();
7231                comp = intent.getComponent();
7232            }
7233        }
7234        if (comp != null) {
7235            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7236            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7237            if (pi != null) {
7238                // When specifying an explicit component, we prevent the provider from being
7239                // used when either 1) the provider is in an instant application and the
7240                // caller is not the same instant application or 2) the calling package is an
7241                // instant application and the provider is not visible to instant applications.
7242                final boolean matchInstantApp =
7243                        (flags & PackageManager.MATCH_INSTANT) != 0;
7244                final boolean matchVisibleToInstantAppOnly =
7245                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7246                final boolean isCallerInstantApp =
7247                        instantAppPkgName != null;
7248                final boolean isTargetSameInstantApp =
7249                        comp.getPackageName().equals(instantAppPkgName);
7250                final boolean isTargetInstantApp =
7251                        (pi.applicationInfo.privateFlags
7252                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7253                final boolean isTargetHiddenFromInstantApp =
7254                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
7255                final boolean blockResolution =
7256                        !isTargetSameInstantApp
7257                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7258                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7259                                        && isTargetHiddenFromInstantApp));
7260                if (!blockResolution) {
7261                    final ResolveInfo ri = new ResolveInfo();
7262                    ri.providerInfo = pi;
7263                    list.add(ri);
7264                }
7265            }
7266            return list;
7267        }
7268
7269        // reader
7270        synchronized (mPackages) {
7271            String pkgName = intent.getPackage();
7272            if (pkgName == null) {
7273                return applyPostContentProviderResolutionFilter(
7274                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7275                        instantAppPkgName);
7276            }
7277            final PackageParser.Package pkg = mPackages.get(pkgName);
7278            if (pkg != null) {
7279                return applyPostContentProviderResolutionFilter(
7280                        mProviders.queryIntentForPackage(
7281                        intent, resolvedType, flags, pkg.providers, userId),
7282                        instantAppPkgName);
7283            }
7284            return Collections.emptyList();
7285        }
7286    }
7287
7288    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7289            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7290        // TODO: When adding on-demand split support for non-instant applications, remove
7291        // this check and always apply post filtering
7292        if (instantAppPkgName == null) {
7293            return resolveInfos;
7294        }
7295        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7296            final ResolveInfo info = resolveInfos.get(i);
7297            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7298            // allow providers that are defined in the provided package
7299            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7300                if (info.providerInfo.splitName != null
7301                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7302                                info.providerInfo.splitName)) {
7303                    // requested provider is defined in a split that hasn't been installed yet.
7304                    // add the installer to the resolve list
7305                    if (DEBUG_EPHEMERAL) {
7306                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7307                    }
7308                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7309                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7310                            info.providerInfo.packageName, info.providerInfo.splitName,
7311                            info.providerInfo.applicationInfo.versionCode);
7312                    // make sure this resolver is the default
7313                    installerInfo.isDefault = true;
7314                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7315                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7316                    // add a non-generic filter
7317                    installerInfo.filter = new IntentFilter();
7318                    // load resources from the correct package
7319                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7320                    resolveInfos.set(i, installerInfo);
7321                }
7322                continue;
7323            }
7324            // allow providers that have been explicitly exposed to instant applications
7325            if (!isEphemeralApp
7326                    && ((info.providerInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
7327                continue;
7328            }
7329            resolveInfos.remove(i);
7330        }
7331        return resolveInfos;
7332    }
7333
7334    @Override
7335    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7336        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7337        flags = updateFlagsForPackage(flags, userId, null);
7338        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7339        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7340                true /* requireFullPermission */, false /* checkShell */,
7341                "get installed packages");
7342
7343        // writer
7344        synchronized (mPackages) {
7345            ArrayList<PackageInfo> list;
7346            if (listUninstalled) {
7347                list = new ArrayList<>(mSettings.mPackages.size());
7348                for (PackageSetting ps : mSettings.mPackages.values()) {
7349                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7350                        continue;
7351                    }
7352                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7353                    if (pi != null) {
7354                        list.add(pi);
7355                    }
7356                }
7357            } else {
7358                list = new ArrayList<>(mPackages.size());
7359                for (PackageParser.Package p : mPackages.values()) {
7360                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7361                            Binder.getCallingUid(), userId)) {
7362                        continue;
7363                    }
7364                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7365                            p.mExtras, flags, userId);
7366                    if (pi != null) {
7367                        list.add(pi);
7368                    }
7369                }
7370            }
7371
7372            return new ParceledListSlice<>(list);
7373        }
7374    }
7375
7376    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7377            String[] permissions, boolean[] tmp, int flags, int userId) {
7378        int numMatch = 0;
7379        final PermissionsState permissionsState = ps.getPermissionsState();
7380        for (int i=0; i<permissions.length; i++) {
7381            final String permission = permissions[i];
7382            if (permissionsState.hasPermission(permission, userId)) {
7383                tmp[i] = true;
7384                numMatch++;
7385            } else {
7386                tmp[i] = false;
7387            }
7388        }
7389        if (numMatch == 0) {
7390            return;
7391        }
7392        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7393
7394        // The above might return null in cases of uninstalled apps or install-state
7395        // skew across users/profiles.
7396        if (pi != null) {
7397            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7398                if (numMatch == permissions.length) {
7399                    pi.requestedPermissions = permissions;
7400                } else {
7401                    pi.requestedPermissions = new String[numMatch];
7402                    numMatch = 0;
7403                    for (int i=0; i<permissions.length; i++) {
7404                        if (tmp[i]) {
7405                            pi.requestedPermissions[numMatch] = permissions[i];
7406                            numMatch++;
7407                        }
7408                    }
7409                }
7410            }
7411            list.add(pi);
7412        }
7413    }
7414
7415    @Override
7416    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7417            String[] permissions, int flags, int userId) {
7418        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7419        flags = updateFlagsForPackage(flags, userId, permissions);
7420        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7421                true /* requireFullPermission */, false /* checkShell */,
7422                "get packages holding permissions");
7423        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7424
7425        // writer
7426        synchronized (mPackages) {
7427            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7428            boolean[] tmpBools = new boolean[permissions.length];
7429            if (listUninstalled) {
7430                for (PackageSetting ps : mSettings.mPackages.values()) {
7431                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7432                            userId);
7433                }
7434            } else {
7435                for (PackageParser.Package pkg : mPackages.values()) {
7436                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7437                    if (ps != null) {
7438                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7439                                userId);
7440                    }
7441                }
7442            }
7443
7444            return new ParceledListSlice<PackageInfo>(list);
7445        }
7446    }
7447
7448    @Override
7449    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7450        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7451        flags = updateFlagsForApplication(flags, userId, null);
7452        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7453
7454        // writer
7455        synchronized (mPackages) {
7456            ArrayList<ApplicationInfo> list;
7457            if (listUninstalled) {
7458                list = new ArrayList<>(mSettings.mPackages.size());
7459                for (PackageSetting ps : mSettings.mPackages.values()) {
7460                    ApplicationInfo ai;
7461                    int effectiveFlags = flags;
7462                    if (ps.isSystem()) {
7463                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7464                    }
7465                    if (ps.pkg != null) {
7466                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7467                            continue;
7468                        }
7469                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7470                                ps.readUserState(userId), userId);
7471                        if (ai != null) {
7472                            rebaseEnabledOverlays(ai, userId);
7473                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7474                        }
7475                    } else {
7476                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7477                        // and already converts to externally visible package name
7478                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7479                                Binder.getCallingUid(), effectiveFlags, userId);
7480                    }
7481                    if (ai != null) {
7482                        list.add(ai);
7483                    }
7484                }
7485            } else {
7486                list = new ArrayList<>(mPackages.size());
7487                for (PackageParser.Package p : mPackages.values()) {
7488                    if (p.mExtras != null) {
7489                        PackageSetting ps = (PackageSetting) p.mExtras;
7490                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7491                            continue;
7492                        }
7493                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7494                                ps.readUserState(userId), userId);
7495                        if (ai != null) {
7496                            rebaseEnabledOverlays(ai, userId);
7497                            ai.packageName = resolveExternalPackageNameLPr(p);
7498                            list.add(ai);
7499                        }
7500                    }
7501                }
7502            }
7503
7504            return new ParceledListSlice<>(list);
7505        }
7506    }
7507
7508    @Override
7509    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7510        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7511            return null;
7512        }
7513
7514        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7515                "getEphemeralApplications");
7516        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7517                true /* requireFullPermission */, false /* checkShell */,
7518                "getEphemeralApplications");
7519        synchronized (mPackages) {
7520            List<InstantAppInfo> instantApps = mInstantAppRegistry
7521                    .getInstantAppsLPr(userId);
7522            if (instantApps != null) {
7523                return new ParceledListSlice<>(instantApps);
7524            }
7525        }
7526        return null;
7527    }
7528
7529    @Override
7530    public boolean isInstantApp(String packageName, int userId) {
7531        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7532                true /* requireFullPermission */, false /* checkShell */,
7533                "isInstantApp");
7534        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7535            return false;
7536        }
7537        int uid = Binder.getCallingUid();
7538        if (Process.isIsolated(uid)) {
7539            uid = mIsolatedOwners.get(uid);
7540        }
7541
7542        synchronized (mPackages) {
7543            final PackageSetting ps = mSettings.mPackages.get(packageName);
7544            PackageParser.Package pkg = mPackages.get(packageName);
7545            final boolean returnAllowed =
7546                    ps != null
7547                    && (isCallerSameApp(packageName, uid)
7548                            || mContext.checkCallingOrSelfPermission(
7549                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7550                                            == PERMISSION_GRANTED
7551                            || mInstantAppRegistry.isInstantAccessGranted(
7552                                    userId, UserHandle.getAppId(uid), ps.appId));
7553            if (returnAllowed) {
7554                return ps.getInstantApp(userId);
7555            }
7556        }
7557        return false;
7558    }
7559
7560    @Override
7561    public byte[] getInstantAppCookie(String packageName, int userId) {
7562        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7563            return null;
7564        }
7565
7566        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7567                true /* requireFullPermission */, false /* checkShell */,
7568                "getInstantAppCookie");
7569        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7570            return null;
7571        }
7572        synchronized (mPackages) {
7573            return mInstantAppRegistry.getInstantAppCookieLPw(
7574                    packageName, userId);
7575        }
7576    }
7577
7578    @Override
7579    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7580        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7581            return true;
7582        }
7583
7584        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7585                true /* requireFullPermission */, true /* checkShell */,
7586                "setInstantAppCookie");
7587        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7588            return false;
7589        }
7590        synchronized (mPackages) {
7591            return mInstantAppRegistry.setInstantAppCookieLPw(
7592                    packageName, cookie, userId);
7593        }
7594    }
7595
7596    @Override
7597    public Bitmap getInstantAppIcon(String packageName, int userId) {
7598        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7599            return null;
7600        }
7601
7602        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7603                "getInstantAppIcon");
7604
7605        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7606                true /* requireFullPermission */, false /* checkShell */,
7607                "getInstantAppIcon");
7608
7609        synchronized (mPackages) {
7610            return mInstantAppRegistry.getInstantAppIconLPw(
7611                    packageName, userId);
7612        }
7613    }
7614
7615    private boolean isCallerSameApp(String packageName, int uid) {
7616        PackageParser.Package pkg = mPackages.get(packageName);
7617        return pkg != null
7618                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7619    }
7620
7621    @Override
7622    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7623        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7624    }
7625
7626    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7627        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7628
7629        // reader
7630        synchronized (mPackages) {
7631            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7632            final int userId = UserHandle.getCallingUserId();
7633            while (i.hasNext()) {
7634                final PackageParser.Package p = i.next();
7635                if (p.applicationInfo == null) continue;
7636
7637                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7638                        && !p.applicationInfo.isDirectBootAware();
7639                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7640                        && p.applicationInfo.isDirectBootAware();
7641
7642                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7643                        && (!mSafeMode || isSystemApp(p))
7644                        && (matchesUnaware || matchesAware)) {
7645                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7646                    if (ps != null) {
7647                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7648                                ps.readUserState(userId), userId);
7649                        if (ai != null) {
7650                            rebaseEnabledOverlays(ai, userId);
7651                            finalList.add(ai);
7652                        }
7653                    }
7654                }
7655            }
7656        }
7657
7658        return finalList;
7659    }
7660
7661    @Override
7662    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7663        if (!sUserManager.exists(userId)) return null;
7664        flags = updateFlagsForComponent(flags, userId, name);
7665        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7666        // reader
7667        synchronized (mPackages) {
7668            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7669            PackageSetting ps = provider != null
7670                    ? mSettings.mPackages.get(provider.owner.packageName)
7671                    : null;
7672            if (ps != null) {
7673                final boolean isInstantApp = ps.getInstantApp(userId);
7674                // normal application; filter out instant application provider
7675                if (instantAppPkgName == null && isInstantApp) {
7676                    return null;
7677                }
7678                // instant application; filter out other instant applications
7679                if (instantAppPkgName != null
7680                        && isInstantApp
7681                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7682                    return null;
7683                }
7684                // instant application; filter out non-exposed provider
7685                if (instantAppPkgName != null
7686                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0) {
7687                    return null;
7688                }
7689                // provider not enabled
7690                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7691                    return null;
7692                }
7693                return PackageParser.generateProviderInfo(
7694                        provider, flags, ps.readUserState(userId), userId);
7695            }
7696            return null;
7697        }
7698    }
7699
7700    /**
7701     * @deprecated
7702     */
7703    @Deprecated
7704    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7705        // reader
7706        synchronized (mPackages) {
7707            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7708                    .entrySet().iterator();
7709            final int userId = UserHandle.getCallingUserId();
7710            while (i.hasNext()) {
7711                Map.Entry<String, PackageParser.Provider> entry = i.next();
7712                PackageParser.Provider p = entry.getValue();
7713                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7714
7715                if (ps != null && p.syncable
7716                        && (!mSafeMode || (p.info.applicationInfo.flags
7717                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7718                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7719                            ps.readUserState(userId), userId);
7720                    if (info != null) {
7721                        outNames.add(entry.getKey());
7722                        outInfo.add(info);
7723                    }
7724                }
7725            }
7726        }
7727    }
7728
7729    @Override
7730    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7731            int uid, int flags, String metaDataKey) {
7732        final int userId = processName != null ? UserHandle.getUserId(uid)
7733                : UserHandle.getCallingUserId();
7734        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7735        flags = updateFlagsForComponent(flags, userId, processName);
7736
7737        ArrayList<ProviderInfo> finalList = null;
7738        // reader
7739        synchronized (mPackages) {
7740            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7741            while (i.hasNext()) {
7742                final PackageParser.Provider p = i.next();
7743                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7744                if (ps != null && p.info.authority != null
7745                        && (processName == null
7746                                || (p.info.processName.equals(processName)
7747                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7748                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7749
7750                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7751                    // parameter.
7752                    if (metaDataKey != null
7753                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7754                        continue;
7755                    }
7756
7757                    if (finalList == null) {
7758                        finalList = new ArrayList<ProviderInfo>(3);
7759                    }
7760                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7761                            ps.readUserState(userId), userId);
7762                    if (info != null) {
7763                        finalList.add(info);
7764                    }
7765                }
7766            }
7767        }
7768
7769        if (finalList != null) {
7770            Collections.sort(finalList, mProviderInitOrderSorter);
7771            return new ParceledListSlice<ProviderInfo>(finalList);
7772        }
7773
7774        return ParceledListSlice.emptyList();
7775    }
7776
7777    @Override
7778    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7779        // reader
7780        synchronized (mPackages) {
7781            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7782            return PackageParser.generateInstrumentationInfo(i, flags);
7783        }
7784    }
7785
7786    @Override
7787    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7788            String targetPackage, int flags) {
7789        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7790    }
7791
7792    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7793            int flags) {
7794        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7795
7796        // reader
7797        synchronized (mPackages) {
7798            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7799            while (i.hasNext()) {
7800                final PackageParser.Instrumentation p = i.next();
7801                if (targetPackage == null
7802                        || targetPackage.equals(p.info.targetPackage)) {
7803                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7804                            flags);
7805                    if (ii != null) {
7806                        finalList.add(ii);
7807                    }
7808                }
7809            }
7810        }
7811
7812        return finalList;
7813    }
7814
7815    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7816        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7817        try {
7818            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7819        } finally {
7820            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7821        }
7822    }
7823
7824    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7825        final File[] files = dir.listFiles();
7826        if (ArrayUtils.isEmpty(files)) {
7827            Log.d(TAG, "No files in app dir " + dir);
7828            return;
7829        }
7830
7831        if (DEBUG_PACKAGE_SCANNING) {
7832            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7833                    + " flags=0x" + Integer.toHexString(parseFlags));
7834        }
7835        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7836                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7837
7838        // Submit files for parsing in parallel
7839        int fileCount = 0;
7840        for (File file : files) {
7841            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7842                    && !PackageInstallerService.isStageName(file.getName());
7843            if (!isPackage) {
7844                // Ignore entries which are not packages
7845                continue;
7846            }
7847            parallelPackageParser.submit(file, parseFlags);
7848            fileCount++;
7849        }
7850
7851        // Process results one by one
7852        for (; fileCount > 0; fileCount--) {
7853            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7854            Throwable throwable = parseResult.throwable;
7855            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7856
7857            if (throwable == null) {
7858                // Static shared libraries have synthetic package names
7859                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7860                    renameStaticSharedLibraryPackage(parseResult.pkg);
7861                }
7862                try {
7863                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7864                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7865                                currentTime, null);
7866                    }
7867                } catch (PackageManagerException e) {
7868                    errorCode = e.error;
7869                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7870                }
7871            } else if (throwable instanceof PackageParser.PackageParserException) {
7872                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7873                        throwable;
7874                errorCode = e.error;
7875                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7876            } else {
7877                throw new IllegalStateException("Unexpected exception occurred while parsing "
7878                        + parseResult.scanFile, throwable);
7879            }
7880
7881            // Delete invalid userdata apps
7882            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7883                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7884                logCriticalInfo(Log.WARN,
7885                        "Deleting invalid package at " + parseResult.scanFile);
7886                removeCodePathLI(parseResult.scanFile);
7887            }
7888        }
7889        parallelPackageParser.close();
7890    }
7891
7892    private static File getSettingsProblemFile() {
7893        File dataDir = Environment.getDataDirectory();
7894        File systemDir = new File(dataDir, "system");
7895        File fname = new File(systemDir, "uiderrors.txt");
7896        return fname;
7897    }
7898
7899    static void reportSettingsProblem(int priority, String msg) {
7900        logCriticalInfo(priority, msg);
7901    }
7902
7903    public static void logCriticalInfo(int priority, String msg) {
7904        Slog.println(priority, TAG, msg);
7905        EventLogTags.writePmCriticalInfo(msg);
7906        try {
7907            File fname = getSettingsProblemFile();
7908            FileOutputStream out = new FileOutputStream(fname, true);
7909            PrintWriter pw = new FastPrintWriter(out);
7910            SimpleDateFormat formatter = new SimpleDateFormat();
7911            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7912            pw.println(dateString + ": " + msg);
7913            pw.close();
7914            FileUtils.setPermissions(
7915                    fname.toString(),
7916                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7917                    -1, -1);
7918        } catch (java.io.IOException e) {
7919        }
7920    }
7921
7922    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7923        if (srcFile.isDirectory()) {
7924            final File baseFile = new File(pkg.baseCodePath);
7925            long maxModifiedTime = baseFile.lastModified();
7926            if (pkg.splitCodePaths != null) {
7927                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7928                    final File splitFile = new File(pkg.splitCodePaths[i]);
7929                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7930                }
7931            }
7932            return maxModifiedTime;
7933        }
7934        return srcFile.lastModified();
7935    }
7936
7937    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7938            final int policyFlags) throws PackageManagerException {
7939        // When upgrading from pre-N MR1, verify the package time stamp using the package
7940        // directory and not the APK file.
7941        final long lastModifiedTime = mIsPreNMR1Upgrade
7942                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7943        if (ps != null
7944                && ps.codePath.equals(srcFile)
7945                && ps.timeStamp == lastModifiedTime
7946                && !isCompatSignatureUpdateNeeded(pkg)
7947                && !isRecoverSignatureUpdateNeeded(pkg)) {
7948            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7949            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7950            ArraySet<PublicKey> signingKs;
7951            synchronized (mPackages) {
7952                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7953            }
7954            if (ps.signatures.mSignatures != null
7955                    && ps.signatures.mSignatures.length != 0
7956                    && signingKs != null) {
7957                // Optimization: reuse the existing cached certificates
7958                // if the package appears to be unchanged.
7959                pkg.mSignatures = ps.signatures.mSignatures;
7960                pkg.mSigningKeys = signingKs;
7961                return;
7962            }
7963
7964            Slog.w(TAG, "PackageSetting for " + ps.name
7965                    + " is missing signatures.  Collecting certs again to recover them.");
7966        } else {
7967            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7968        }
7969
7970        try {
7971            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7972            PackageParser.collectCertificates(pkg, policyFlags);
7973        } catch (PackageParserException e) {
7974            throw PackageManagerException.from(e);
7975        } finally {
7976            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7977        }
7978    }
7979
7980    /**
7981     *  Traces a package scan.
7982     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7983     */
7984    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7985            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7986        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7987        try {
7988            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7989        } finally {
7990            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7991        }
7992    }
7993
7994    /**
7995     *  Scans a package and returns the newly parsed package.
7996     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7997     */
7998    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7999            long currentTime, UserHandle user) throws PackageManagerException {
8000        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8001        PackageParser pp = new PackageParser();
8002        pp.setSeparateProcesses(mSeparateProcesses);
8003        pp.setOnlyCoreApps(mOnlyCore);
8004        pp.setDisplayMetrics(mMetrics);
8005        pp.setCallback(mPackageParserCallback);
8006
8007        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8008            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8009        }
8010
8011        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8012        final PackageParser.Package pkg;
8013        try {
8014            pkg = pp.parsePackage(scanFile, parseFlags);
8015        } catch (PackageParserException e) {
8016            throw PackageManagerException.from(e);
8017        } finally {
8018            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8019        }
8020
8021        // Static shared libraries have synthetic package names
8022        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8023            renameStaticSharedLibraryPackage(pkg);
8024        }
8025
8026        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8027    }
8028
8029    /**
8030     *  Scans a package and returns the newly parsed package.
8031     *  @throws PackageManagerException on a parse error.
8032     */
8033    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8034            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8035            throws PackageManagerException {
8036        // If the package has children and this is the first dive in the function
8037        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8038        // packages (parent and children) would be successfully scanned before the
8039        // actual scan since scanning mutates internal state and we want to atomically
8040        // install the package and its children.
8041        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8042            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8043                scanFlags |= SCAN_CHECK_ONLY;
8044            }
8045        } else {
8046            scanFlags &= ~SCAN_CHECK_ONLY;
8047        }
8048
8049        // Scan the parent
8050        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8051                scanFlags, currentTime, user);
8052
8053        // Scan the children
8054        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8055        for (int i = 0; i < childCount; i++) {
8056            PackageParser.Package childPackage = pkg.childPackages.get(i);
8057            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8058                    currentTime, user);
8059        }
8060
8061
8062        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8063            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8064        }
8065
8066        return scannedPkg;
8067    }
8068
8069    /**
8070     *  Scans a package and returns the newly parsed package.
8071     *  @throws PackageManagerException on a parse error.
8072     */
8073    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8074            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8075            throws PackageManagerException {
8076        PackageSetting ps = null;
8077        PackageSetting updatedPkg;
8078        // reader
8079        synchronized (mPackages) {
8080            // Look to see if we already know about this package.
8081            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8082            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8083                // This package has been renamed to its original name.  Let's
8084                // use that.
8085                ps = mSettings.getPackageLPr(oldName);
8086            }
8087            // If there was no original package, see one for the real package name.
8088            if (ps == null) {
8089                ps = mSettings.getPackageLPr(pkg.packageName);
8090            }
8091            // Check to see if this package could be hiding/updating a system
8092            // package.  Must look for it either under the original or real
8093            // package name depending on our state.
8094            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8095            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8096
8097            // If this is a package we don't know about on the system partition, we
8098            // may need to remove disabled child packages on the system partition
8099            // or may need to not add child packages if the parent apk is updated
8100            // on the data partition and no longer defines this child package.
8101            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8102                // If this is a parent package for an updated system app and this system
8103                // app got an OTA update which no longer defines some of the child packages
8104                // we have to prune them from the disabled system packages.
8105                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8106                if (disabledPs != null) {
8107                    final int scannedChildCount = (pkg.childPackages != null)
8108                            ? pkg.childPackages.size() : 0;
8109                    final int disabledChildCount = disabledPs.childPackageNames != null
8110                            ? disabledPs.childPackageNames.size() : 0;
8111                    for (int i = 0; i < disabledChildCount; i++) {
8112                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8113                        boolean disabledPackageAvailable = false;
8114                        for (int j = 0; j < scannedChildCount; j++) {
8115                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8116                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8117                                disabledPackageAvailable = true;
8118                                break;
8119                            }
8120                         }
8121                         if (!disabledPackageAvailable) {
8122                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8123                         }
8124                    }
8125                }
8126            }
8127        }
8128
8129        boolean updatedPkgBetter = false;
8130        // First check if this is a system package that may involve an update
8131        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8132            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8133            // it needs to drop FLAG_PRIVILEGED.
8134            if (locationIsPrivileged(scanFile)) {
8135                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8136            } else {
8137                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8138            }
8139
8140            if (ps != null && !ps.codePath.equals(scanFile)) {
8141                // The path has changed from what was last scanned...  check the
8142                // version of the new path against what we have stored to determine
8143                // what to do.
8144                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8145                if (pkg.mVersionCode <= ps.versionCode) {
8146                    // The system package has been updated and the code path does not match
8147                    // Ignore entry. Skip it.
8148                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8149                            + " ignored: updated version " + ps.versionCode
8150                            + " better than this " + pkg.mVersionCode);
8151                    if (!updatedPkg.codePath.equals(scanFile)) {
8152                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8153                                + ps.name + " changing from " + updatedPkg.codePathString
8154                                + " to " + scanFile);
8155                        updatedPkg.codePath = scanFile;
8156                        updatedPkg.codePathString = scanFile.toString();
8157                        updatedPkg.resourcePath = scanFile;
8158                        updatedPkg.resourcePathString = scanFile.toString();
8159                    }
8160                    updatedPkg.pkg = pkg;
8161                    updatedPkg.versionCode = pkg.mVersionCode;
8162
8163                    // Update the disabled system child packages to point to the package too.
8164                    final int childCount = updatedPkg.childPackageNames != null
8165                            ? updatedPkg.childPackageNames.size() : 0;
8166                    for (int i = 0; i < childCount; i++) {
8167                        String childPackageName = updatedPkg.childPackageNames.get(i);
8168                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8169                                childPackageName);
8170                        if (updatedChildPkg != null) {
8171                            updatedChildPkg.pkg = pkg;
8172                            updatedChildPkg.versionCode = pkg.mVersionCode;
8173                        }
8174                    }
8175
8176                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8177                            + scanFile + " ignored: updated version " + ps.versionCode
8178                            + " better than this " + pkg.mVersionCode);
8179                } else {
8180                    // The current app on the system partition is better than
8181                    // what we have updated to on the data partition; switch
8182                    // back to the system partition version.
8183                    // At this point, its safely assumed that package installation for
8184                    // apps in system partition will go through. If not there won't be a working
8185                    // version of the app
8186                    // writer
8187                    synchronized (mPackages) {
8188                        // Just remove the loaded entries from package lists.
8189                        mPackages.remove(ps.name);
8190                    }
8191
8192                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8193                            + " reverting from " + ps.codePathString
8194                            + ": new version " + pkg.mVersionCode
8195                            + " better than installed " + ps.versionCode);
8196
8197                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8198                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8199                    synchronized (mInstallLock) {
8200                        args.cleanUpResourcesLI();
8201                    }
8202                    synchronized (mPackages) {
8203                        mSettings.enableSystemPackageLPw(ps.name);
8204                    }
8205                    updatedPkgBetter = true;
8206                }
8207            }
8208        }
8209
8210        if (updatedPkg != null) {
8211            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8212            // initially
8213            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8214
8215            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8216            // flag set initially
8217            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8218                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8219            }
8220        }
8221
8222        // Verify certificates against what was last scanned
8223        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8224
8225        /*
8226         * A new system app appeared, but we already had a non-system one of the
8227         * same name installed earlier.
8228         */
8229        boolean shouldHideSystemApp = false;
8230        if (updatedPkg == null && ps != null
8231                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8232            /*
8233             * Check to make sure the signatures match first. If they don't,
8234             * wipe the installed application and its data.
8235             */
8236            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8237                    != PackageManager.SIGNATURE_MATCH) {
8238                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8239                        + " signatures don't match existing userdata copy; removing");
8240                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8241                        "scanPackageInternalLI")) {
8242                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8243                }
8244                ps = null;
8245            } else {
8246                /*
8247                 * If the newly-added system app is an older version than the
8248                 * already installed version, hide it. It will be scanned later
8249                 * and re-added like an update.
8250                 */
8251                if (pkg.mVersionCode <= ps.versionCode) {
8252                    shouldHideSystemApp = true;
8253                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8254                            + " but new version " + pkg.mVersionCode + " better than installed "
8255                            + ps.versionCode + "; hiding system");
8256                } else {
8257                    /*
8258                     * The newly found system app is a newer version that the
8259                     * one previously installed. Simply remove the
8260                     * already-installed application and replace it with our own
8261                     * while keeping the application data.
8262                     */
8263                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8264                            + " reverting from " + ps.codePathString + ": new version "
8265                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8266                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8267                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8268                    synchronized (mInstallLock) {
8269                        args.cleanUpResourcesLI();
8270                    }
8271                }
8272            }
8273        }
8274
8275        // The apk is forward locked (not public) if its code and resources
8276        // are kept in different files. (except for app in either system or
8277        // vendor path).
8278        // TODO grab this value from PackageSettings
8279        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8280            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8281                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8282            }
8283        }
8284
8285        // TODO: extend to support forward-locked splits
8286        String resourcePath = null;
8287        String baseResourcePath = null;
8288        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8289            if (ps != null && ps.resourcePathString != null) {
8290                resourcePath = ps.resourcePathString;
8291                baseResourcePath = ps.resourcePathString;
8292            } else {
8293                // Should not happen at all. Just log an error.
8294                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8295            }
8296        } else {
8297            resourcePath = pkg.codePath;
8298            baseResourcePath = pkg.baseCodePath;
8299        }
8300
8301        // Set application objects path explicitly.
8302        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8303        pkg.setApplicationInfoCodePath(pkg.codePath);
8304        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8305        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8306        pkg.setApplicationInfoResourcePath(resourcePath);
8307        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8308        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8309
8310        final int userId = ((user == null) ? 0 : user.getIdentifier());
8311        if (ps != null && ps.getInstantApp(userId)) {
8312            scanFlags |= SCAN_AS_INSTANT_APP;
8313        }
8314
8315        // Note that we invoke the following method only if we are about to unpack an application
8316        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8317                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8318
8319        /*
8320         * If the system app should be overridden by a previously installed
8321         * data, hide the system app now and let the /data/app scan pick it up
8322         * again.
8323         */
8324        if (shouldHideSystemApp) {
8325            synchronized (mPackages) {
8326                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8327            }
8328        }
8329
8330        return scannedPkg;
8331    }
8332
8333    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8334        // Derive the new package synthetic package name
8335        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8336                + pkg.staticSharedLibVersion);
8337    }
8338
8339    private static String fixProcessName(String defProcessName,
8340            String processName) {
8341        if (processName == null) {
8342            return defProcessName;
8343        }
8344        return processName;
8345    }
8346
8347    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8348            throws PackageManagerException {
8349        if (pkgSetting.signatures.mSignatures != null) {
8350            // Already existing package. Make sure signatures match
8351            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8352                    == PackageManager.SIGNATURE_MATCH;
8353            if (!match) {
8354                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8355                        == PackageManager.SIGNATURE_MATCH;
8356            }
8357            if (!match) {
8358                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8359                        == PackageManager.SIGNATURE_MATCH;
8360            }
8361            if (!match) {
8362                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8363                        + pkg.packageName + " signatures do not match the "
8364                        + "previously installed version; ignoring!");
8365            }
8366        }
8367
8368        // Check for shared user signatures
8369        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8370            // Already existing package. Make sure signatures match
8371            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8372                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8373            if (!match) {
8374                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8375                        == PackageManager.SIGNATURE_MATCH;
8376            }
8377            if (!match) {
8378                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8379                        == PackageManager.SIGNATURE_MATCH;
8380            }
8381            if (!match) {
8382                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8383                        "Package " + pkg.packageName
8384                        + " has no signatures that match those in shared user "
8385                        + pkgSetting.sharedUser.name + "; ignoring!");
8386            }
8387        }
8388    }
8389
8390    /**
8391     * Enforces that only the system UID or root's UID can call a method exposed
8392     * via Binder.
8393     *
8394     * @param message used as message if SecurityException is thrown
8395     * @throws SecurityException if the caller is not system or root
8396     */
8397    private static final void enforceSystemOrRoot(String message) {
8398        final int uid = Binder.getCallingUid();
8399        if (uid != Process.SYSTEM_UID && uid != 0) {
8400            throw new SecurityException(message);
8401        }
8402    }
8403
8404    @Override
8405    public void performFstrimIfNeeded() {
8406        enforceSystemOrRoot("Only the system can request fstrim");
8407
8408        // Before everything else, see whether we need to fstrim.
8409        try {
8410            IStorageManager sm = PackageHelper.getStorageManager();
8411            if (sm != null) {
8412                boolean doTrim = false;
8413                final long interval = android.provider.Settings.Global.getLong(
8414                        mContext.getContentResolver(),
8415                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8416                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8417                if (interval > 0) {
8418                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8419                    if (timeSinceLast > interval) {
8420                        doTrim = true;
8421                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8422                                + "; running immediately");
8423                    }
8424                }
8425                if (doTrim) {
8426                    final boolean dexOptDialogShown;
8427                    synchronized (mPackages) {
8428                        dexOptDialogShown = mDexOptDialogShown;
8429                    }
8430                    if (!isFirstBoot() && dexOptDialogShown) {
8431                        try {
8432                            ActivityManager.getService().showBootMessage(
8433                                    mContext.getResources().getString(
8434                                            R.string.android_upgrading_fstrim), true);
8435                        } catch (RemoteException e) {
8436                        }
8437                    }
8438                    sm.runMaintenance();
8439                }
8440            } else {
8441                Slog.e(TAG, "storageManager service unavailable!");
8442            }
8443        } catch (RemoteException e) {
8444            // Can't happen; StorageManagerService is local
8445        }
8446    }
8447
8448    @Override
8449    public void updatePackagesIfNeeded() {
8450        enforceSystemOrRoot("Only the system can request package update");
8451
8452        // We need to re-extract after an OTA.
8453        boolean causeUpgrade = isUpgrade();
8454
8455        // First boot or factory reset.
8456        // Note: we also handle devices that are upgrading to N right now as if it is their
8457        //       first boot, as they do not have profile data.
8458        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8459
8460        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8461        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8462
8463        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8464            return;
8465        }
8466
8467        List<PackageParser.Package> pkgs;
8468        synchronized (mPackages) {
8469            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8470        }
8471
8472        final long startTime = System.nanoTime();
8473        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8474                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8475
8476        final int elapsedTimeSeconds =
8477                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8478
8479        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8480        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8481        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8482        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8483        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8484    }
8485
8486    /**
8487     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8488     * containing statistics about the invocation. The array consists of three elements,
8489     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8490     * and {@code numberOfPackagesFailed}.
8491     */
8492    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8493            String compilerFilter) {
8494
8495        int numberOfPackagesVisited = 0;
8496        int numberOfPackagesOptimized = 0;
8497        int numberOfPackagesSkipped = 0;
8498        int numberOfPackagesFailed = 0;
8499        final int numberOfPackagesToDexopt = pkgs.size();
8500
8501        for (PackageParser.Package pkg : pkgs) {
8502            numberOfPackagesVisited++;
8503
8504            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8505                if (DEBUG_DEXOPT) {
8506                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8507                }
8508                numberOfPackagesSkipped++;
8509                continue;
8510            }
8511
8512            if (DEBUG_DEXOPT) {
8513                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8514                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8515            }
8516
8517            if (showDialog) {
8518                try {
8519                    ActivityManager.getService().showBootMessage(
8520                            mContext.getResources().getString(R.string.android_upgrading_apk,
8521                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8522                } catch (RemoteException e) {
8523                }
8524                synchronized (mPackages) {
8525                    mDexOptDialogShown = true;
8526                }
8527            }
8528
8529            // If the OTA updates a system app which was previously preopted to a non-preopted state
8530            // the app might end up being verified at runtime. That's because by default the apps
8531            // are verify-profile but for preopted apps there's no profile.
8532            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8533            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8534            // filter (by default interpret-only).
8535            // Note that at this stage unused apps are already filtered.
8536            if (isSystemApp(pkg) &&
8537                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8538                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8539                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8540            }
8541
8542            // checkProfiles is false to avoid merging profiles during boot which
8543            // might interfere with background compilation (b/28612421).
8544            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8545            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8546            // trade-off worth doing to save boot time work.
8547            int dexOptStatus = performDexOptTraced(pkg.packageName,
8548                    false /* checkProfiles */,
8549                    compilerFilter,
8550                    false /* force */);
8551            switch (dexOptStatus) {
8552                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8553                    numberOfPackagesOptimized++;
8554                    break;
8555                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8556                    numberOfPackagesSkipped++;
8557                    break;
8558                case PackageDexOptimizer.DEX_OPT_FAILED:
8559                    numberOfPackagesFailed++;
8560                    break;
8561                default:
8562                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8563                    break;
8564            }
8565        }
8566
8567        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8568                numberOfPackagesFailed };
8569    }
8570
8571    @Override
8572    public void notifyPackageUse(String packageName, int reason) {
8573        synchronized (mPackages) {
8574            PackageParser.Package p = mPackages.get(packageName);
8575            if (p == null) {
8576                return;
8577            }
8578            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8579        }
8580    }
8581
8582    @Override
8583    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8584        int userId = UserHandle.getCallingUserId();
8585        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8586        if (ai == null) {
8587            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8588                + loadingPackageName + ", user=" + userId);
8589            return;
8590        }
8591        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8592    }
8593
8594    @Override
8595    public boolean performDexOpt(String packageName,
8596            boolean checkProfiles, int compileReason, boolean force) {
8597        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8598                getCompilerFilterForReason(compileReason), force);
8599        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8600    }
8601
8602    @Override
8603    public boolean performDexOptMode(String packageName,
8604            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8605        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8606                targetCompilerFilter, force);
8607        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8608    }
8609
8610    private int performDexOptTraced(String packageName,
8611                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8612        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8613        try {
8614            return performDexOptInternal(packageName, checkProfiles,
8615                    targetCompilerFilter, force);
8616        } finally {
8617            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8618        }
8619    }
8620
8621    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8622    // if the package can now be considered up to date for the given filter.
8623    private int performDexOptInternal(String packageName,
8624                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8625        PackageParser.Package p;
8626        synchronized (mPackages) {
8627            p = mPackages.get(packageName);
8628            if (p == null) {
8629                // Package could not be found. Report failure.
8630                return PackageDexOptimizer.DEX_OPT_FAILED;
8631            }
8632            mPackageUsage.maybeWriteAsync(mPackages);
8633            mCompilerStats.maybeWriteAsync();
8634        }
8635        long callingId = Binder.clearCallingIdentity();
8636        try {
8637            synchronized (mInstallLock) {
8638                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8639                        targetCompilerFilter, force);
8640            }
8641        } finally {
8642            Binder.restoreCallingIdentity(callingId);
8643        }
8644    }
8645
8646    public ArraySet<String> getOptimizablePackages() {
8647        ArraySet<String> pkgs = new ArraySet<String>();
8648        synchronized (mPackages) {
8649            for (PackageParser.Package p : mPackages.values()) {
8650                if (PackageDexOptimizer.canOptimizePackage(p)) {
8651                    pkgs.add(p.packageName);
8652                }
8653            }
8654        }
8655        return pkgs;
8656    }
8657
8658    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8659            boolean checkProfiles, String targetCompilerFilter,
8660            boolean force) {
8661        // Select the dex optimizer based on the force parameter.
8662        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8663        //       allocate an object here.
8664        PackageDexOptimizer pdo = force
8665                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8666                : mPackageDexOptimizer;
8667
8668        // Dexopt all dependencies first. Note: we ignore the return value and march on
8669        // on errors.
8670        // Note that we are going to call performDexOpt on those libraries as many times as
8671        // they are referenced in packages. When we do a batch of performDexOpt (for example
8672        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8673        // and the first package that uses the library will dexopt it. The
8674        // others will see that the compiled code for the library is up to date.
8675        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8676        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8677        if (!deps.isEmpty()) {
8678            for (PackageParser.Package depPackage : deps) {
8679                // TODO: Analyze and investigate if we (should) profile libraries.
8680                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8681                        false /* checkProfiles */,
8682                        targetCompilerFilter,
8683                        getOrCreateCompilerPackageStats(depPackage),
8684                        true /* isUsedByOtherApps */);
8685            }
8686        }
8687        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8688                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8689                mDexManager.isUsedByOtherApps(p.packageName));
8690    }
8691
8692    // Performs dexopt on the used secondary dex files belonging to the given package.
8693    // Returns true if all dex files were process successfully (which could mean either dexopt or
8694    // skip). Returns false if any of the files caused errors.
8695    @Override
8696    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8697            boolean force) {
8698        mDexManager.reconcileSecondaryDexFiles(packageName);
8699        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8700    }
8701
8702    public boolean performDexOptSecondary(String packageName, int compileReason,
8703            boolean force) {
8704        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8705    }
8706
8707    /**
8708     * Reconcile the information we have about the secondary dex files belonging to
8709     * {@code packagName} and the actual dex files. For all dex files that were
8710     * deleted, update the internal records and delete the generated oat files.
8711     */
8712    @Override
8713    public void reconcileSecondaryDexFiles(String packageName) {
8714        mDexManager.reconcileSecondaryDexFiles(packageName);
8715    }
8716
8717    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8718    // a reference there.
8719    /*package*/ DexManager getDexManager() {
8720        return mDexManager;
8721    }
8722
8723    /**
8724     * Execute the background dexopt job immediately.
8725     */
8726    @Override
8727    public boolean runBackgroundDexoptJob() {
8728        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8729    }
8730
8731    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8732        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8733                || p.usesStaticLibraries != null) {
8734            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8735            Set<String> collectedNames = new HashSet<>();
8736            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8737
8738            retValue.remove(p);
8739
8740            return retValue;
8741        } else {
8742            return Collections.emptyList();
8743        }
8744    }
8745
8746    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8747            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8748        if (!collectedNames.contains(p.packageName)) {
8749            collectedNames.add(p.packageName);
8750            collected.add(p);
8751
8752            if (p.usesLibraries != null) {
8753                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8754                        null, collected, collectedNames);
8755            }
8756            if (p.usesOptionalLibraries != null) {
8757                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8758                        null, collected, collectedNames);
8759            }
8760            if (p.usesStaticLibraries != null) {
8761                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8762                        p.usesStaticLibrariesVersions, collected, collectedNames);
8763            }
8764        }
8765    }
8766
8767    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8768            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8769        final int libNameCount = libs.size();
8770        for (int i = 0; i < libNameCount; i++) {
8771            String libName = libs.get(i);
8772            int version = (versions != null && versions.length == libNameCount)
8773                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8774            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8775            if (libPkg != null) {
8776                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8777            }
8778        }
8779    }
8780
8781    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8782        synchronized (mPackages) {
8783            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8784            if (libEntry != null) {
8785                return mPackages.get(libEntry.apk);
8786            }
8787            return null;
8788        }
8789    }
8790
8791    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8792        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8793        if (versionedLib == null) {
8794            return null;
8795        }
8796        return versionedLib.get(version);
8797    }
8798
8799    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8800        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8801                pkg.staticSharedLibName);
8802        if (versionedLib == null) {
8803            return null;
8804        }
8805        int previousLibVersion = -1;
8806        final int versionCount = versionedLib.size();
8807        for (int i = 0; i < versionCount; i++) {
8808            final int libVersion = versionedLib.keyAt(i);
8809            if (libVersion < pkg.staticSharedLibVersion) {
8810                previousLibVersion = Math.max(previousLibVersion, libVersion);
8811            }
8812        }
8813        if (previousLibVersion >= 0) {
8814            return versionedLib.get(previousLibVersion);
8815        }
8816        return null;
8817    }
8818
8819    public void shutdown() {
8820        mPackageUsage.writeNow(mPackages);
8821        mCompilerStats.writeNow();
8822    }
8823
8824    @Override
8825    public void dumpProfiles(String packageName) {
8826        PackageParser.Package pkg;
8827        synchronized (mPackages) {
8828            pkg = mPackages.get(packageName);
8829            if (pkg == null) {
8830                throw new IllegalArgumentException("Unknown package: " + packageName);
8831            }
8832        }
8833        /* Only the shell, root, or the app user should be able to dump profiles. */
8834        int callingUid = Binder.getCallingUid();
8835        if (callingUid != Process.SHELL_UID &&
8836            callingUid != Process.ROOT_UID &&
8837            callingUid != pkg.applicationInfo.uid) {
8838            throw new SecurityException("dumpProfiles");
8839        }
8840
8841        synchronized (mInstallLock) {
8842            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8843            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8844            try {
8845                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8846                String codePaths = TextUtils.join(";", allCodePaths);
8847                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8848            } catch (InstallerException e) {
8849                Slog.w(TAG, "Failed to dump profiles", e);
8850            }
8851            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8852        }
8853    }
8854
8855    @Override
8856    public void forceDexOpt(String packageName) {
8857        enforceSystemOrRoot("forceDexOpt");
8858
8859        PackageParser.Package pkg;
8860        synchronized (mPackages) {
8861            pkg = mPackages.get(packageName);
8862            if (pkg == null) {
8863                throw new IllegalArgumentException("Unknown package: " + packageName);
8864            }
8865        }
8866
8867        synchronized (mInstallLock) {
8868            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8869
8870            // Whoever is calling forceDexOpt wants a compiled package.
8871            // Don't use profiles since that may cause compilation to be skipped.
8872            final int res = performDexOptInternalWithDependenciesLI(pkg,
8873                    false /* checkProfiles */, getDefaultCompilerFilter(),
8874                    true /* force */);
8875
8876            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8877            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8878                throw new IllegalStateException("Failed to dexopt: " + res);
8879            }
8880        }
8881    }
8882
8883    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8884        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8885            Slog.w(TAG, "Unable to update from " + oldPkg.name
8886                    + " to " + newPkg.packageName
8887                    + ": old package not in system partition");
8888            return false;
8889        } else if (mPackages.get(oldPkg.name) != null) {
8890            Slog.w(TAG, "Unable to update from " + oldPkg.name
8891                    + " to " + newPkg.packageName
8892                    + ": old package still exists");
8893            return false;
8894        }
8895        return true;
8896    }
8897
8898    void removeCodePathLI(File codePath) {
8899        if (codePath.isDirectory()) {
8900            try {
8901                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8902            } catch (InstallerException e) {
8903                Slog.w(TAG, "Failed to remove code path", e);
8904            }
8905        } else {
8906            codePath.delete();
8907        }
8908    }
8909
8910    private int[] resolveUserIds(int userId) {
8911        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8912    }
8913
8914    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8915        if (pkg == null) {
8916            Slog.wtf(TAG, "Package was null!", new Throwable());
8917            return;
8918        }
8919        clearAppDataLeafLIF(pkg, userId, flags);
8920        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8921        for (int i = 0; i < childCount; i++) {
8922            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8923        }
8924    }
8925
8926    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8927        final PackageSetting ps;
8928        synchronized (mPackages) {
8929            ps = mSettings.mPackages.get(pkg.packageName);
8930        }
8931        for (int realUserId : resolveUserIds(userId)) {
8932            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8933            try {
8934                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8935                        ceDataInode);
8936            } catch (InstallerException e) {
8937                Slog.w(TAG, String.valueOf(e));
8938            }
8939        }
8940    }
8941
8942    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8943        if (pkg == null) {
8944            Slog.wtf(TAG, "Package was null!", new Throwable());
8945            return;
8946        }
8947        destroyAppDataLeafLIF(pkg, userId, flags);
8948        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8949        for (int i = 0; i < childCount; i++) {
8950            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8951        }
8952    }
8953
8954    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8955        final PackageSetting ps;
8956        synchronized (mPackages) {
8957            ps = mSettings.mPackages.get(pkg.packageName);
8958        }
8959        for (int realUserId : resolveUserIds(userId)) {
8960            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8961            try {
8962                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8963                        ceDataInode);
8964            } catch (InstallerException e) {
8965                Slog.w(TAG, String.valueOf(e));
8966            }
8967            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8968        }
8969    }
8970
8971    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8972        if (pkg == null) {
8973            Slog.wtf(TAG, "Package was null!", new Throwable());
8974            return;
8975        }
8976        destroyAppProfilesLeafLIF(pkg);
8977        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8978        for (int i = 0; i < childCount; i++) {
8979            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8980        }
8981    }
8982
8983    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8984        try {
8985            mInstaller.destroyAppProfiles(pkg.packageName);
8986        } catch (InstallerException e) {
8987            Slog.w(TAG, String.valueOf(e));
8988        }
8989    }
8990
8991    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8992        if (pkg == null) {
8993            Slog.wtf(TAG, "Package was null!", new Throwable());
8994            return;
8995        }
8996        clearAppProfilesLeafLIF(pkg);
8997        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8998        for (int i = 0; i < childCount; i++) {
8999            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9000        }
9001    }
9002
9003    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9004        try {
9005            mInstaller.clearAppProfiles(pkg.packageName);
9006        } catch (InstallerException e) {
9007            Slog.w(TAG, String.valueOf(e));
9008        }
9009    }
9010
9011    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9012            long lastUpdateTime) {
9013        // Set parent install/update time
9014        PackageSetting ps = (PackageSetting) pkg.mExtras;
9015        if (ps != null) {
9016            ps.firstInstallTime = firstInstallTime;
9017            ps.lastUpdateTime = lastUpdateTime;
9018        }
9019        // Set children install/update time
9020        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9021        for (int i = 0; i < childCount; i++) {
9022            PackageParser.Package childPkg = pkg.childPackages.get(i);
9023            ps = (PackageSetting) childPkg.mExtras;
9024            if (ps != null) {
9025                ps.firstInstallTime = firstInstallTime;
9026                ps.lastUpdateTime = lastUpdateTime;
9027            }
9028        }
9029    }
9030
9031    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9032            PackageParser.Package changingLib) {
9033        if (file.path != null) {
9034            usesLibraryFiles.add(file.path);
9035            return;
9036        }
9037        PackageParser.Package p = mPackages.get(file.apk);
9038        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9039            // If we are doing this while in the middle of updating a library apk,
9040            // then we need to make sure to use that new apk for determining the
9041            // dependencies here.  (We haven't yet finished committing the new apk
9042            // to the package manager state.)
9043            if (p == null || p.packageName.equals(changingLib.packageName)) {
9044                p = changingLib;
9045            }
9046        }
9047        if (p != null) {
9048            usesLibraryFiles.addAll(p.getAllCodePaths());
9049        }
9050    }
9051
9052    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9053            PackageParser.Package changingLib) throws PackageManagerException {
9054        if (pkg == null) {
9055            return;
9056        }
9057        ArraySet<String> usesLibraryFiles = null;
9058        if (pkg.usesLibraries != null) {
9059            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9060                    null, null, pkg.packageName, changingLib, true, null);
9061        }
9062        if (pkg.usesStaticLibraries != null) {
9063            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9064                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9065                    pkg.packageName, changingLib, true, usesLibraryFiles);
9066        }
9067        if (pkg.usesOptionalLibraries != null) {
9068            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9069                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9070        }
9071        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9072            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9073        } else {
9074            pkg.usesLibraryFiles = null;
9075        }
9076    }
9077
9078    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9079            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9080            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9081            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9082            throws PackageManagerException {
9083        final int libCount = requestedLibraries.size();
9084        for (int i = 0; i < libCount; i++) {
9085            final String libName = requestedLibraries.get(i);
9086            final int libVersion = requiredVersions != null ? requiredVersions[i]
9087                    : SharedLibraryInfo.VERSION_UNDEFINED;
9088            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9089            if (libEntry == null) {
9090                if (required) {
9091                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9092                            "Package " + packageName + " requires unavailable shared library "
9093                                    + libName + "; failing!");
9094                } else {
9095                    Slog.w(TAG, "Package " + packageName
9096                            + " desires unavailable shared library "
9097                            + libName + "; ignoring!");
9098                }
9099            } else {
9100                if (requiredVersions != null && requiredCertDigests != null) {
9101                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9102                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9103                            "Package " + packageName + " requires unavailable static shared"
9104                                    + " library " + libName + " version "
9105                                    + libEntry.info.getVersion() + "; failing!");
9106                    }
9107
9108                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9109                    if (libPkg == null) {
9110                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9111                                "Package " + packageName + " requires unavailable static shared"
9112                                        + " library; failing!");
9113                    }
9114
9115                    String expectedCertDigest = requiredCertDigests[i];
9116                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9117                                libPkg.mSignatures[0]);
9118                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9119                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9120                                "Package " + packageName + " requires differently signed" +
9121                                        " static shared library; failing!");
9122                    }
9123                }
9124
9125                if (outUsedLibraries == null) {
9126                    outUsedLibraries = new ArraySet<>();
9127                }
9128                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9129            }
9130        }
9131        return outUsedLibraries;
9132    }
9133
9134    private static boolean hasString(List<String> list, List<String> which) {
9135        if (list == null) {
9136            return false;
9137        }
9138        for (int i=list.size()-1; i>=0; i--) {
9139            for (int j=which.size()-1; j>=0; j--) {
9140                if (which.get(j).equals(list.get(i))) {
9141                    return true;
9142                }
9143            }
9144        }
9145        return false;
9146    }
9147
9148    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9149            PackageParser.Package changingPkg) {
9150        ArrayList<PackageParser.Package> res = null;
9151        for (PackageParser.Package pkg : mPackages.values()) {
9152            if (changingPkg != null
9153                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9154                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9155                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9156                            changingPkg.staticSharedLibName)) {
9157                return null;
9158            }
9159            if (res == null) {
9160                res = new ArrayList<>();
9161            }
9162            res.add(pkg);
9163            try {
9164                updateSharedLibrariesLPr(pkg, changingPkg);
9165            } catch (PackageManagerException e) {
9166                // If a system app update or an app and a required lib missing we
9167                // delete the package and for updated system apps keep the data as
9168                // it is better for the user to reinstall than to be in an limbo
9169                // state. Also libs disappearing under an app should never happen
9170                // - just in case.
9171                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9172                    final int flags = pkg.isUpdatedSystemApp()
9173                            ? PackageManager.DELETE_KEEP_DATA : 0;
9174                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9175                            flags , null, true, null);
9176                }
9177                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9178            }
9179        }
9180        return res;
9181    }
9182
9183    /**
9184     * Derive the value of the {@code cpuAbiOverride} based on the provided
9185     * value and an optional stored value from the package settings.
9186     */
9187    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9188        String cpuAbiOverride = null;
9189
9190        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9191            cpuAbiOverride = null;
9192        } else if (abiOverride != null) {
9193            cpuAbiOverride = abiOverride;
9194        } else if (settings != null) {
9195            cpuAbiOverride = settings.cpuAbiOverrideString;
9196        }
9197
9198        return cpuAbiOverride;
9199    }
9200
9201    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9202            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9203                    throws PackageManagerException {
9204        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9205        // If the package has children and this is the first dive in the function
9206        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9207        // whether all packages (parent and children) would be successfully scanned
9208        // before the actual scan since scanning mutates internal state and we want
9209        // to atomically install the package and its children.
9210        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9211            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9212                scanFlags |= SCAN_CHECK_ONLY;
9213            }
9214        } else {
9215            scanFlags &= ~SCAN_CHECK_ONLY;
9216        }
9217
9218        final PackageParser.Package scannedPkg;
9219        try {
9220            // Scan the parent
9221            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9222            // Scan the children
9223            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9224            for (int i = 0; i < childCount; i++) {
9225                PackageParser.Package childPkg = pkg.childPackages.get(i);
9226                scanPackageLI(childPkg, policyFlags,
9227                        scanFlags, currentTime, user);
9228            }
9229        } finally {
9230            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9231        }
9232
9233        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9234            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9235        }
9236
9237        return scannedPkg;
9238    }
9239
9240    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9241            int scanFlags, long currentTime, @Nullable UserHandle user)
9242                    throws PackageManagerException {
9243        boolean success = false;
9244        try {
9245            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9246                    currentTime, user);
9247            success = true;
9248            return res;
9249        } finally {
9250            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9251                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9252                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9253                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9254                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9255            }
9256        }
9257    }
9258
9259    /**
9260     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9261     */
9262    private static boolean apkHasCode(String fileName) {
9263        StrictJarFile jarFile = null;
9264        try {
9265            jarFile = new StrictJarFile(fileName,
9266                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9267            return jarFile.findEntry("classes.dex") != null;
9268        } catch (IOException ignore) {
9269        } finally {
9270            try {
9271                if (jarFile != null) {
9272                    jarFile.close();
9273                }
9274            } catch (IOException ignore) {}
9275        }
9276        return false;
9277    }
9278
9279    /**
9280     * Enforces code policy for the package. This ensures that if an APK has
9281     * declared hasCode="true" in its manifest that the APK actually contains
9282     * code.
9283     *
9284     * @throws PackageManagerException If bytecode could not be found when it should exist
9285     */
9286    private static void assertCodePolicy(PackageParser.Package pkg)
9287            throws PackageManagerException {
9288        final boolean shouldHaveCode =
9289                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9290        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9291            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9292                    "Package " + pkg.baseCodePath + " code is missing");
9293        }
9294
9295        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9296            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9297                final boolean splitShouldHaveCode =
9298                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9299                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9300                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9301                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9302                }
9303            }
9304        }
9305    }
9306
9307    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9308            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9309                    throws PackageManagerException {
9310        if (DEBUG_PACKAGE_SCANNING) {
9311            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9312                Log.d(TAG, "Scanning package " + pkg.packageName);
9313        }
9314
9315        applyPolicy(pkg, policyFlags);
9316
9317        assertPackageIsValid(pkg, policyFlags, scanFlags);
9318
9319        // Initialize package source and resource directories
9320        final File scanFile = new File(pkg.codePath);
9321        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9322        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9323
9324        SharedUserSetting suid = null;
9325        PackageSetting pkgSetting = null;
9326
9327        // Getting the package setting may have a side-effect, so if we
9328        // are only checking if scan would succeed, stash a copy of the
9329        // old setting to restore at the end.
9330        PackageSetting nonMutatedPs = null;
9331
9332        // We keep references to the derived CPU Abis from settings in oder to reuse
9333        // them in the case where we're not upgrading or booting for the first time.
9334        String primaryCpuAbiFromSettings = null;
9335        String secondaryCpuAbiFromSettings = null;
9336
9337        // writer
9338        synchronized (mPackages) {
9339            if (pkg.mSharedUserId != null) {
9340                // SIDE EFFECTS; may potentially allocate a new shared user
9341                suid = mSettings.getSharedUserLPw(
9342                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9343                if (DEBUG_PACKAGE_SCANNING) {
9344                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9345                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9346                                + "): packages=" + suid.packages);
9347                }
9348            }
9349
9350            // Check if we are renaming from an original package name.
9351            PackageSetting origPackage = null;
9352            String realName = null;
9353            if (pkg.mOriginalPackages != null) {
9354                // This package may need to be renamed to a previously
9355                // installed name.  Let's check on that...
9356                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9357                if (pkg.mOriginalPackages.contains(renamed)) {
9358                    // This package had originally been installed as the
9359                    // original name, and we have already taken care of
9360                    // transitioning to the new one.  Just update the new
9361                    // one to continue using the old name.
9362                    realName = pkg.mRealPackage;
9363                    if (!pkg.packageName.equals(renamed)) {
9364                        // Callers into this function may have already taken
9365                        // care of renaming the package; only do it here if
9366                        // it is not already done.
9367                        pkg.setPackageName(renamed);
9368                    }
9369                } else {
9370                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9371                        if ((origPackage = mSettings.getPackageLPr(
9372                                pkg.mOriginalPackages.get(i))) != null) {
9373                            // We do have the package already installed under its
9374                            // original name...  should we use it?
9375                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9376                                // New package is not compatible with original.
9377                                origPackage = null;
9378                                continue;
9379                            } else if (origPackage.sharedUser != null) {
9380                                // Make sure uid is compatible between packages.
9381                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9382                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9383                                            + " to " + pkg.packageName + ": old uid "
9384                                            + origPackage.sharedUser.name
9385                                            + " differs from " + pkg.mSharedUserId);
9386                                    origPackage = null;
9387                                    continue;
9388                                }
9389                                // TODO: Add case when shared user id is added [b/28144775]
9390                            } else {
9391                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9392                                        + pkg.packageName + " to old name " + origPackage.name);
9393                            }
9394                            break;
9395                        }
9396                    }
9397                }
9398            }
9399
9400            if (mTransferedPackages.contains(pkg.packageName)) {
9401                Slog.w(TAG, "Package " + pkg.packageName
9402                        + " was transferred to another, but its .apk remains");
9403            }
9404
9405            // See comments in nonMutatedPs declaration
9406            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9407                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9408                if (foundPs != null) {
9409                    nonMutatedPs = new PackageSetting(foundPs);
9410                }
9411            }
9412
9413            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9414                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9415                if (foundPs != null) {
9416                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9417                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9418                }
9419            }
9420
9421            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9422            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9423                PackageManagerService.reportSettingsProblem(Log.WARN,
9424                        "Package " + pkg.packageName + " shared user changed from "
9425                                + (pkgSetting.sharedUser != null
9426                                        ? pkgSetting.sharedUser.name : "<nothing>")
9427                                + " to "
9428                                + (suid != null ? suid.name : "<nothing>")
9429                                + "; replacing with new");
9430                pkgSetting = null;
9431            }
9432            final PackageSetting oldPkgSetting =
9433                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9434            final PackageSetting disabledPkgSetting =
9435                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9436
9437            String[] usesStaticLibraries = null;
9438            if (pkg.usesStaticLibraries != null) {
9439                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9440                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9441            }
9442
9443            if (pkgSetting == null) {
9444                final String parentPackageName = (pkg.parentPackage != null)
9445                        ? pkg.parentPackage.packageName : null;
9446                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9447                // REMOVE SharedUserSetting from method; update in a separate call
9448                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9449                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9450                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9451                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9452                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9453                        true /*allowInstall*/, instantApp, parentPackageName,
9454                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9455                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9456                // SIDE EFFECTS; updates system state; move elsewhere
9457                if (origPackage != null) {
9458                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9459                }
9460                mSettings.addUserToSettingLPw(pkgSetting);
9461            } else {
9462                // REMOVE SharedUserSetting from method; update in a separate call.
9463                //
9464                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9465                // secondaryCpuAbi are not known at this point so we always update them
9466                // to null here, only to reset them at a later point.
9467                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9468                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9469                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9470                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9471                        UserManagerService.getInstance(), usesStaticLibraries,
9472                        pkg.usesStaticLibrariesVersions);
9473            }
9474            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9475            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9476
9477            // SIDE EFFECTS; modifies system state; move elsewhere
9478            if (pkgSetting.origPackage != null) {
9479                // If we are first transitioning from an original package,
9480                // fix up the new package's name now.  We need to do this after
9481                // looking up the package under its new name, so getPackageLP
9482                // can take care of fiddling things correctly.
9483                pkg.setPackageName(origPackage.name);
9484
9485                // File a report about this.
9486                String msg = "New package " + pkgSetting.realName
9487                        + " renamed to replace old package " + pkgSetting.name;
9488                reportSettingsProblem(Log.WARN, msg);
9489
9490                // Make a note of it.
9491                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9492                    mTransferedPackages.add(origPackage.name);
9493                }
9494
9495                // No longer need to retain this.
9496                pkgSetting.origPackage = null;
9497            }
9498
9499            // SIDE EFFECTS; modifies system state; move elsewhere
9500            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9501                // Make a note of it.
9502                mTransferedPackages.add(pkg.packageName);
9503            }
9504
9505            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9506                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9507            }
9508
9509            if ((scanFlags & SCAN_BOOTING) == 0
9510                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9511                // Check all shared libraries and map to their actual file path.
9512                // We only do this here for apps not on a system dir, because those
9513                // are the only ones that can fail an install due to this.  We
9514                // will take care of the system apps by updating all of their
9515                // library paths after the scan is done. Also during the initial
9516                // scan don't update any libs as we do this wholesale after all
9517                // apps are scanned to avoid dependency based scanning.
9518                updateSharedLibrariesLPr(pkg, null);
9519            }
9520
9521            if (mFoundPolicyFile) {
9522                SELinuxMMAC.assignSeInfoValue(pkg);
9523            }
9524            pkg.applicationInfo.uid = pkgSetting.appId;
9525            pkg.mExtras = pkgSetting;
9526
9527
9528            // Static shared libs have same package with different versions where
9529            // we internally use a synthetic package name to allow multiple versions
9530            // of the same package, therefore we need to compare signatures against
9531            // the package setting for the latest library version.
9532            PackageSetting signatureCheckPs = pkgSetting;
9533            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9534                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9535                if (libraryEntry != null) {
9536                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9537                }
9538            }
9539
9540            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9541                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9542                    // We just determined the app is signed correctly, so bring
9543                    // over the latest parsed certs.
9544                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9545                } else {
9546                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9547                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9548                                "Package " + pkg.packageName + " upgrade keys do not match the "
9549                                + "previously installed version");
9550                    } else {
9551                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9552                        String msg = "System package " + pkg.packageName
9553                                + " signature changed; retaining data.";
9554                        reportSettingsProblem(Log.WARN, msg);
9555                    }
9556                }
9557            } else {
9558                try {
9559                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9560                    verifySignaturesLP(signatureCheckPs, pkg);
9561                    // We just determined the app is signed correctly, so bring
9562                    // over the latest parsed certs.
9563                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9564                } catch (PackageManagerException e) {
9565                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9566                        throw e;
9567                    }
9568                    // The signature has changed, but this package is in the system
9569                    // image...  let's recover!
9570                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9571                    // However...  if this package is part of a shared user, but it
9572                    // doesn't match the signature of the shared user, let's fail.
9573                    // What this means is that you can't change the signatures
9574                    // associated with an overall shared user, which doesn't seem all
9575                    // that unreasonable.
9576                    if (signatureCheckPs.sharedUser != null) {
9577                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9578                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9579                            throw new PackageManagerException(
9580                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9581                                    "Signature mismatch for shared user: "
9582                                            + pkgSetting.sharedUser);
9583                        }
9584                    }
9585                    // File a report about this.
9586                    String msg = "System package " + pkg.packageName
9587                            + " signature changed; retaining data.";
9588                    reportSettingsProblem(Log.WARN, msg);
9589                }
9590            }
9591
9592            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9593                // This package wants to adopt ownership of permissions from
9594                // another package.
9595                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9596                    final String origName = pkg.mAdoptPermissions.get(i);
9597                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9598                    if (orig != null) {
9599                        if (verifyPackageUpdateLPr(orig, pkg)) {
9600                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9601                                    + pkg.packageName);
9602                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9603                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9604                        }
9605                    }
9606                }
9607            }
9608        }
9609
9610        pkg.applicationInfo.processName = fixProcessName(
9611                pkg.applicationInfo.packageName,
9612                pkg.applicationInfo.processName);
9613
9614        if (pkg != mPlatformPackage) {
9615            // Get all of our default paths setup
9616            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9617        }
9618
9619        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9620
9621        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9622            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9623                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9624                derivePackageAbi(
9625                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9626                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9627
9628                // Some system apps still use directory structure for native libraries
9629                // in which case we might end up not detecting abi solely based on apk
9630                // structure. Try to detect abi based on directory structure.
9631                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9632                        pkg.applicationInfo.primaryCpuAbi == null) {
9633                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9634                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9635                }
9636            } else {
9637                // This is not a first boot or an upgrade, don't bother deriving the
9638                // ABI during the scan. Instead, trust the value that was stored in the
9639                // package setting.
9640                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9641                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9642
9643                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9644
9645                if (DEBUG_ABI_SELECTION) {
9646                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9647                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9648                        pkg.applicationInfo.secondaryCpuAbi);
9649                }
9650            }
9651        } else {
9652            if ((scanFlags & SCAN_MOVE) != 0) {
9653                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9654                // but we already have this packages package info in the PackageSetting. We just
9655                // use that and derive the native library path based on the new codepath.
9656                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9657                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9658            }
9659
9660            // Set native library paths again. For moves, the path will be updated based on the
9661            // ABIs we've determined above. For non-moves, the path will be updated based on the
9662            // ABIs we determined during compilation, but the path will depend on the final
9663            // package path (after the rename away from the stage path).
9664            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9665        }
9666
9667        // This is a special case for the "system" package, where the ABI is
9668        // dictated by the zygote configuration (and init.rc). We should keep track
9669        // of this ABI so that we can deal with "normal" applications that run under
9670        // the same UID correctly.
9671        if (mPlatformPackage == pkg) {
9672            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9673                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9674        }
9675
9676        // If there's a mismatch between the abi-override in the package setting
9677        // and the abiOverride specified for the install. Warn about this because we
9678        // would've already compiled the app without taking the package setting into
9679        // account.
9680        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9681            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9682                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9683                        " for package " + pkg.packageName);
9684            }
9685        }
9686
9687        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9688        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9689        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9690
9691        // Copy the derived override back to the parsed package, so that we can
9692        // update the package settings accordingly.
9693        pkg.cpuAbiOverride = cpuAbiOverride;
9694
9695        if (DEBUG_ABI_SELECTION) {
9696            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9697                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9698                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9699        }
9700
9701        // Push the derived path down into PackageSettings so we know what to
9702        // clean up at uninstall time.
9703        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9704
9705        if (DEBUG_ABI_SELECTION) {
9706            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9707                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9708                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9709        }
9710
9711        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9712        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9713            // We don't do this here during boot because we can do it all
9714            // at once after scanning all existing packages.
9715            //
9716            // We also do this *before* we perform dexopt on this package, so that
9717            // we can avoid redundant dexopts, and also to make sure we've got the
9718            // code and package path correct.
9719            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9720        }
9721
9722        if (mFactoryTest && pkg.requestedPermissions.contains(
9723                android.Manifest.permission.FACTORY_TEST)) {
9724            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9725        }
9726
9727        if (isSystemApp(pkg)) {
9728            pkgSetting.isOrphaned = true;
9729        }
9730
9731        // Take care of first install / last update times.
9732        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9733        if (currentTime != 0) {
9734            if (pkgSetting.firstInstallTime == 0) {
9735                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9736            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9737                pkgSetting.lastUpdateTime = currentTime;
9738            }
9739        } else if (pkgSetting.firstInstallTime == 0) {
9740            // We need *something*.  Take time time stamp of the file.
9741            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9742        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9743            if (scanFileTime != pkgSetting.timeStamp) {
9744                // A package on the system image has changed; consider this
9745                // to be an update.
9746                pkgSetting.lastUpdateTime = scanFileTime;
9747            }
9748        }
9749        pkgSetting.setTimeStamp(scanFileTime);
9750
9751        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9752            if (nonMutatedPs != null) {
9753                synchronized (mPackages) {
9754                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9755                }
9756            }
9757        } else {
9758            final int userId = user == null ? 0 : user.getIdentifier();
9759            // Modify state for the given package setting
9760            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9761                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9762            if (pkgSetting.getInstantApp(userId)) {
9763                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9764            }
9765        }
9766        return pkg;
9767    }
9768
9769    /**
9770     * Applies policy to the parsed package based upon the given policy flags.
9771     * Ensures the package is in a good state.
9772     * <p>
9773     * Implementation detail: This method must NOT have any side effect. It would
9774     * ideally be static, but, it requires locks to read system state.
9775     */
9776    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9777        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9778            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9779            if (pkg.applicationInfo.isDirectBootAware()) {
9780                // we're direct boot aware; set for all components
9781                for (PackageParser.Service s : pkg.services) {
9782                    s.info.encryptionAware = s.info.directBootAware = true;
9783                }
9784                for (PackageParser.Provider p : pkg.providers) {
9785                    p.info.encryptionAware = p.info.directBootAware = true;
9786                }
9787                for (PackageParser.Activity a : pkg.activities) {
9788                    a.info.encryptionAware = a.info.directBootAware = true;
9789                }
9790                for (PackageParser.Activity r : pkg.receivers) {
9791                    r.info.encryptionAware = r.info.directBootAware = true;
9792                }
9793            }
9794        } else {
9795            // Only allow system apps to be flagged as core apps.
9796            pkg.coreApp = false;
9797            // clear flags not applicable to regular apps
9798            pkg.applicationInfo.privateFlags &=
9799                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9800            pkg.applicationInfo.privateFlags &=
9801                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9802        }
9803        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9804
9805        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9806            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9807        }
9808
9809        if (!isSystemApp(pkg)) {
9810            // Only system apps can use these features.
9811            pkg.mOriginalPackages = null;
9812            pkg.mRealPackage = null;
9813            pkg.mAdoptPermissions = null;
9814        }
9815    }
9816
9817    /**
9818     * Asserts the parsed package is valid according to the given policy. If the
9819     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9820     * <p>
9821     * Implementation detail: This method must NOT have any side effects. It would
9822     * ideally be static, but, it requires locks to read system state.
9823     *
9824     * @throws PackageManagerException If the package fails any of the validation checks
9825     */
9826    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9827            throws PackageManagerException {
9828        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9829            assertCodePolicy(pkg);
9830        }
9831
9832        if (pkg.applicationInfo.getCodePath() == null ||
9833                pkg.applicationInfo.getResourcePath() == null) {
9834            // Bail out. The resource and code paths haven't been set.
9835            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9836                    "Code and resource paths haven't been set correctly");
9837        }
9838
9839        // Make sure we're not adding any bogus keyset info
9840        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9841        ksms.assertScannedPackageValid(pkg);
9842
9843        synchronized (mPackages) {
9844            // The special "android" package can only be defined once
9845            if (pkg.packageName.equals("android")) {
9846                if (mAndroidApplication != null) {
9847                    Slog.w(TAG, "*************************************************");
9848                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9849                    Slog.w(TAG, " codePath=" + pkg.codePath);
9850                    Slog.w(TAG, "*************************************************");
9851                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9852                            "Core android package being redefined.  Skipping.");
9853                }
9854            }
9855
9856            // A package name must be unique; don't allow duplicates
9857            if (mPackages.containsKey(pkg.packageName)) {
9858                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9859                        "Application package " + pkg.packageName
9860                        + " already installed.  Skipping duplicate.");
9861            }
9862
9863            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9864                // Static libs have a synthetic package name containing the version
9865                // but we still want the base name to be unique.
9866                if (mPackages.containsKey(pkg.manifestPackageName)) {
9867                    throw new PackageManagerException(
9868                            "Duplicate static shared lib provider package");
9869                }
9870
9871                // Static shared libraries should have at least O target SDK
9872                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9873                    throw new PackageManagerException(
9874                            "Packages declaring static-shared libs must target O SDK or higher");
9875                }
9876
9877                // Package declaring static a shared lib cannot be instant apps
9878                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9879                    throw new PackageManagerException(
9880                            "Packages declaring static-shared libs cannot be instant apps");
9881                }
9882
9883                // Package declaring static a shared lib cannot be renamed since the package
9884                // name is synthetic and apps can't code around package manager internals.
9885                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9886                    throw new PackageManagerException(
9887                            "Packages declaring static-shared libs cannot be renamed");
9888                }
9889
9890                // Package declaring static a shared lib cannot declare child packages
9891                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9892                    throw new PackageManagerException(
9893                            "Packages declaring static-shared libs cannot have child packages");
9894                }
9895
9896                // Package declaring static a shared lib cannot declare dynamic libs
9897                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9898                    throw new PackageManagerException(
9899                            "Packages declaring static-shared libs cannot declare dynamic libs");
9900                }
9901
9902                // Package declaring static a shared lib cannot declare shared users
9903                if (pkg.mSharedUserId != null) {
9904                    throw new PackageManagerException(
9905                            "Packages declaring static-shared libs cannot declare shared users");
9906                }
9907
9908                // Static shared libs cannot declare activities
9909                if (!pkg.activities.isEmpty()) {
9910                    throw new PackageManagerException(
9911                            "Static shared libs cannot declare activities");
9912                }
9913
9914                // Static shared libs cannot declare services
9915                if (!pkg.services.isEmpty()) {
9916                    throw new PackageManagerException(
9917                            "Static shared libs cannot declare services");
9918                }
9919
9920                // Static shared libs cannot declare providers
9921                if (!pkg.providers.isEmpty()) {
9922                    throw new PackageManagerException(
9923                            "Static shared libs cannot declare content providers");
9924                }
9925
9926                // Static shared libs cannot declare receivers
9927                if (!pkg.receivers.isEmpty()) {
9928                    throw new PackageManagerException(
9929                            "Static shared libs cannot declare broadcast receivers");
9930                }
9931
9932                // Static shared libs cannot declare permission groups
9933                if (!pkg.permissionGroups.isEmpty()) {
9934                    throw new PackageManagerException(
9935                            "Static shared libs cannot declare permission groups");
9936                }
9937
9938                // Static shared libs cannot declare permissions
9939                if (!pkg.permissions.isEmpty()) {
9940                    throw new PackageManagerException(
9941                            "Static shared libs cannot declare permissions");
9942                }
9943
9944                // Static shared libs cannot declare protected broadcasts
9945                if (pkg.protectedBroadcasts != null) {
9946                    throw new PackageManagerException(
9947                            "Static shared libs cannot declare protected broadcasts");
9948                }
9949
9950                // Static shared libs cannot be overlay targets
9951                if (pkg.mOverlayTarget != null) {
9952                    throw new PackageManagerException(
9953                            "Static shared libs cannot be overlay targets");
9954                }
9955
9956                // The version codes must be ordered as lib versions
9957                int minVersionCode = Integer.MIN_VALUE;
9958                int maxVersionCode = Integer.MAX_VALUE;
9959
9960                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9961                        pkg.staticSharedLibName);
9962                if (versionedLib != null) {
9963                    final int versionCount = versionedLib.size();
9964                    for (int i = 0; i < versionCount; i++) {
9965                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9966                        // TODO: We will change version code to long, so in the new API it is long
9967                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9968                                .getVersionCode();
9969                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9970                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9971                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9972                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9973                        } else {
9974                            minVersionCode = maxVersionCode = libVersionCode;
9975                            break;
9976                        }
9977                    }
9978                }
9979                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9980                    throw new PackageManagerException("Static shared"
9981                            + " lib version codes must be ordered as lib versions");
9982                }
9983            }
9984
9985            // Only privileged apps and updated privileged apps can add child packages.
9986            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9987                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9988                    throw new PackageManagerException("Only privileged apps can add child "
9989                            + "packages. Ignoring package " + pkg.packageName);
9990                }
9991                final int childCount = pkg.childPackages.size();
9992                for (int i = 0; i < childCount; i++) {
9993                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9994                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9995                            childPkg.packageName)) {
9996                        throw new PackageManagerException("Can't override child of "
9997                                + "another disabled app. Ignoring package " + pkg.packageName);
9998                    }
9999                }
10000            }
10001
10002            // If we're only installing presumed-existing packages, require that the
10003            // scanned APK is both already known and at the path previously established
10004            // for it.  Previously unknown packages we pick up normally, but if we have an
10005            // a priori expectation about this package's install presence, enforce it.
10006            // With a singular exception for new system packages. When an OTA contains
10007            // a new system package, we allow the codepath to change from a system location
10008            // to the user-installed location. If we don't allow this change, any newer,
10009            // user-installed version of the application will be ignored.
10010            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10011                if (mExpectingBetter.containsKey(pkg.packageName)) {
10012                    logCriticalInfo(Log.WARN,
10013                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10014                } else {
10015                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10016                    if (known != null) {
10017                        if (DEBUG_PACKAGE_SCANNING) {
10018                            Log.d(TAG, "Examining " + pkg.codePath
10019                                    + " and requiring known paths " + known.codePathString
10020                                    + " & " + known.resourcePathString);
10021                        }
10022                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10023                                || !pkg.applicationInfo.getResourcePath().equals(
10024                                        known.resourcePathString)) {
10025                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10026                                    "Application package " + pkg.packageName
10027                                    + " found at " + pkg.applicationInfo.getCodePath()
10028                                    + " but expected at " + known.codePathString
10029                                    + "; ignoring.");
10030                        }
10031                    }
10032                }
10033            }
10034
10035            // Verify that this new package doesn't have any content providers
10036            // that conflict with existing packages.  Only do this if the
10037            // package isn't already installed, since we don't want to break
10038            // things that are installed.
10039            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10040                final int N = pkg.providers.size();
10041                int i;
10042                for (i=0; i<N; i++) {
10043                    PackageParser.Provider p = pkg.providers.get(i);
10044                    if (p.info.authority != null) {
10045                        String names[] = p.info.authority.split(";");
10046                        for (int j = 0; j < names.length; j++) {
10047                            if (mProvidersByAuthority.containsKey(names[j])) {
10048                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10049                                final String otherPackageName =
10050                                        ((other != null && other.getComponentName() != null) ?
10051                                                other.getComponentName().getPackageName() : "?");
10052                                throw new PackageManagerException(
10053                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10054                                        "Can't install because provider name " + names[j]
10055                                                + " (in package " + pkg.applicationInfo.packageName
10056                                                + ") is already used by " + otherPackageName);
10057                            }
10058                        }
10059                    }
10060                }
10061            }
10062        }
10063    }
10064
10065    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10066            int type, String declaringPackageName, int declaringVersionCode) {
10067        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10068        if (versionedLib == null) {
10069            versionedLib = new SparseArray<>();
10070            mSharedLibraries.put(name, versionedLib);
10071            if (type == SharedLibraryInfo.TYPE_STATIC) {
10072                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10073            }
10074        } else if (versionedLib.indexOfKey(version) >= 0) {
10075            return false;
10076        }
10077        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10078                version, type, declaringPackageName, declaringVersionCode);
10079        versionedLib.put(version, libEntry);
10080        return true;
10081    }
10082
10083    private boolean removeSharedLibraryLPw(String name, int version) {
10084        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10085        if (versionedLib == null) {
10086            return false;
10087        }
10088        final int libIdx = versionedLib.indexOfKey(version);
10089        if (libIdx < 0) {
10090            return false;
10091        }
10092        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10093        versionedLib.remove(version);
10094        if (versionedLib.size() <= 0) {
10095            mSharedLibraries.remove(name);
10096            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10097                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10098                        .getPackageName());
10099            }
10100        }
10101        return true;
10102    }
10103
10104    /**
10105     * Adds a scanned package to the system. When this method is finished, the package will
10106     * be available for query, resolution, etc...
10107     */
10108    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10109            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10110        final String pkgName = pkg.packageName;
10111        if (mCustomResolverComponentName != null &&
10112                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10113            setUpCustomResolverActivity(pkg);
10114        }
10115
10116        if (pkg.packageName.equals("android")) {
10117            synchronized (mPackages) {
10118                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10119                    // Set up information for our fall-back user intent resolution activity.
10120                    mPlatformPackage = pkg;
10121                    pkg.mVersionCode = mSdkVersion;
10122                    mAndroidApplication = pkg.applicationInfo;
10123                    if (!mResolverReplaced) {
10124                        mResolveActivity.applicationInfo = mAndroidApplication;
10125                        mResolveActivity.name = ResolverActivity.class.getName();
10126                        mResolveActivity.packageName = mAndroidApplication.packageName;
10127                        mResolveActivity.processName = "system:ui";
10128                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10129                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10130                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10131                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10132                        mResolveActivity.exported = true;
10133                        mResolveActivity.enabled = true;
10134                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10135                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10136                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10137                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10138                                | ActivityInfo.CONFIG_ORIENTATION
10139                                | ActivityInfo.CONFIG_KEYBOARD
10140                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10141                        mResolveInfo.activityInfo = mResolveActivity;
10142                        mResolveInfo.priority = 0;
10143                        mResolveInfo.preferredOrder = 0;
10144                        mResolveInfo.match = 0;
10145                        mResolveComponentName = new ComponentName(
10146                                mAndroidApplication.packageName, mResolveActivity.name);
10147                    }
10148                }
10149            }
10150        }
10151
10152        ArrayList<PackageParser.Package> clientLibPkgs = null;
10153        // writer
10154        synchronized (mPackages) {
10155            boolean hasStaticSharedLibs = false;
10156
10157            // Any app can add new static shared libraries
10158            if (pkg.staticSharedLibName != null) {
10159                // Static shared libs don't allow renaming as they have synthetic package
10160                // names to allow install of multiple versions, so use name from manifest.
10161                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10162                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10163                        pkg.manifestPackageName, pkg.mVersionCode)) {
10164                    hasStaticSharedLibs = true;
10165                } else {
10166                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10167                                + pkg.staticSharedLibName + " already exists; skipping");
10168                }
10169                // Static shared libs cannot be updated once installed since they
10170                // use synthetic package name which includes the version code, so
10171                // not need to update other packages's shared lib dependencies.
10172            }
10173
10174            if (!hasStaticSharedLibs
10175                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10176                // Only system apps can add new dynamic shared libraries.
10177                if (pkg.libraryNames != null) {
10178                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10179                        String name = pkg.libraryNames.get(i);
10180                        boolean allowed = false;
10181                        if (pkg.isUpdatedSystemApp()) {
10182                            // New library entries can only be added through the
10183                            // system image.  This is important to get rid of a lot
10184                            // of nasty edge cases: for example if we allowed a non-
10185                            // system update of the app to add a library, then uninstalling
10186                            // the update would make the library go away, and assumptions
10187                            // we made such as through app install filtering would now
10188                            // have allowed apps on the device which aren't compatible
10189                            // with it.  Better to just have the restriction here, be
10190                            // conservative, and create many fewer cases that can negatively
10191                            // impact the user experience.
10192                            final PackageSetting sysPs = mSettings
10193                                    .getDisabledSystemPkgLPr(pkg.packageName);
10194                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10195                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10196                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10197                                        allowed = true;
10198                                        break;
10199                                    }
10200                                }
10201                            }
10202                        } else {
10203                            allowed = true;
10204                        }
10205                        if (allowed) {
10206                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10207                                    SharedLibraryInfo.VERSION_UNDEFINED,
10208                                    SharedLibraryInfo.TYPE_DYNAMIC,
10209                                    pkg.packageName, pkg.mVersionCode)) {
10210                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10211                                        + name + " already exists; skipping");
10212                            }
10213                        } else {
10214                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10215                                    + name + " that is not declared on system image; skipping");
10216                        }
10217                    }
10218
10219                    if ((scanFlags & SCAN_BOOTING) == 0) {
10220                        // If we are not booting, we need to update any applications
10221                        // that are clients of our shared library.  If we are booting,
10222                        // this will all be done once the scan is complete.
10223                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10224                    }
10225                }
10226            }
10227        }
10228
10229        if ((scanFlags & SCAN_BOOTING) != 0) {
10230            // No apps can run during boot scan, so they don't need to be frozen
10231        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10232            // Caller asked to not kill app, so it's probably not frozen
10233        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10234            // Caller asked us to ignore frozen check for some reason; they
10235            // probably didn't know the package name
10236        } else {
10237            // We're doing major surgery on this package, so it better be frozen
10238            // right now to keep it from launching
10239            checkPackageFrozen(pkgName);
10240        }
10241
10242        // Also need to kill any apps that are dependent on the library.
10243        if (clientLibPkgs != null) {
10244            for (int i=0; i<clientLibPkgs.size(); i++) {
10245                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10246                killApplication(clientPkg.applicationInfo.packageName,
10247                        clientPkg.applicationInfo.uid, "update lib");
10248            }
10249        }
10250
10251        // writer
10252        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10253
10254        synchronized (mPackages) {
10255            // We don't expect installation to fail beyond this point
10256
10257            // Add the new setting to mSettings
10258            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10259            // Add the new setting to mPackages
10260            mPackages.put(pkg.applicationInfo.packageName, pkg);
10261            // Make sure we don't accidentally delete its data.
10262            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10263            while (iter.hasNext()) {
10264                PackageCleanItem item = iter.next();
10265                if (pkgName.equals(item.packageName)) {
10266                    iter.remove();
10267                }
10268            }
10269
10270            // Add the package's KeySets to the global KeySetManagerService
10271            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10272            ksms.addScannedPackageLPw(pkg);
10273
10274            int N = pkg.providers.size();
10275            StringBuilder r = null;
10276            int i;
10277            for (i=0; i<N; i++) {
10278                PackageParser.Provider p = pkg.providers.get(i);
10279                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10280                        p.info.processName);
10281                mProviders.addProvider(p);
10282                p.syncable = p.info.isSyncable;
10283                if (p.info.authority != null) {
10284                    String names[] = p.info.authority.split(";");
10285                    p.info.authority = null;
10286                    for (int j = 0; j < names.length; j++) {
10287                        if (j == 1 && p.syncable) {
10288                            // We only want the first authority for a provider to possibly be
10289                            // syncable, so if we already added this provider using a different
10290                            // authority clear the syncable flag. We copy the provider before
10291                            // changing it because the mProviders object contains a reference
10292                            // to a provider that we don't want to change.
10293                            // Only do this for the second authority since the resulting provider
10294                            // object can be the same for all future authorities for this provider.
10295                            p = new PackageParser.Provider(p);
10296                            p.syncable = false;
10297                        }
10298                        if (!mProvidersByAuthority.containsKey(names[j])) {
10299                            mProvidersByAuthority.put(names[j], p);
10300                            if (p.info.authority == null) {
10301                                p.info.authority = names[j];
10302                            } else {
10303                                p.info.authority = p.info.authority + ";" + names[j];
10304                            }
10305                            if (DEBUG_PACKAGE_SCANNING) {
10306                                if (chatty)
10307                                    Log.d(TAG, "Registered content provider: " + names[j]
10308                                            + ", className = " + p.info.name + ", isSyncable = "
10309                                            + p.info.isSyncable);
10310                            }
10311                        } else {
10312                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10313                            Slog.w(TAG, "Skipping provider name " + names[j] +
10314                                    " (in package " + pkg.applicationInfo.packageName +
10315                                    "): name already used by "
10316                                    + ((other != null && other.getComponentName() != null)
10317                                            ? other.getComponentName().getPackageName() : "?"));
10318                        }
10319                    }
10320                }
10321                if (chatty) {
10322                    if (r == null) {
10323                        r = new StringBuilder(256);
10324                    } else {
10325                        r.append(' ');
10326                    }
10327                    r.append(p.info.name);
10328                }
10329            }
10330            if (r != null) {
10331                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10332            }
10333
10334            N = pkg.services.size();
10335            r = null;
10336            for (i=0; i<N; i++) {
10337                PackageParser.Service s = pkg.services.get(i);
10338                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10339                        s.info.processName);
10340                mServices.addService(s);
10341                if (chatty) {
10342                    if (r == null) {
10343                        r = new StringBuilder(256);
10344                    } else {
10345                        r.append(' ');
10346                    }
10347                    r.append(s.info.name);
10348                }
10349            }
10350            if (r != null) {
10351                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10352            }
10353
10354            N = pkg.receivers.size();
10355            r = null;
10356            for (i=0; i<N; i++) {
10357                PackageParser.Activity a = pkg.receivers.get(i);
10358                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10359                        a.info.processName);
10360                mReceivers.addActivity(a, "receiver");
10361                if (chatty) {
10362                    if (r == null) {
10363                        r = new StringBuilder(256);
10364                    } else {
10365                        r.append(' ');
10366                    }
10367                    r.append(a.info.name);
10368                }
10369            }
10370            if (r != null) {
10371                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10372            }
10373
10374            N = pkg.activities.size();
10375            r = null;
10376            for (i=0; i<N; i++) {
10377                PackageParser.Activity a = pkg.activities.get(i);
10378                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10379                        a.info.processName);
10380                mActivities.addActivity(a, "activity");
10381                if (chatty) {
10382                    if (r == null) {
10383                        r = new StringBuilder(256);
10384                    } else {
10385                        r.append(' ');
10386                    }
10387                    r.append(a.info.name);
10388                }
10389            }
10390            if (r != null) {
10391                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10392            }
10393
10394            N = pkg.permissionGroups.size();
10395            r = null;
10396            for (i=0; i<N; i++) {
10397                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10398                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10399                final String curPackageName = cur == null ? null : cur.info.packageName;
10400                // Dont allow ephemeral apps to define new permission groups.
10401                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10402                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10403                            + pg.info.packageName
10404                            + " ignored: instant apps cannot define new permission groups.");
10405                    continue;
10406                }
10407                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10408                if (cur == null || isPackageUpdate) {
10409                    mPermissionGroups.put(pg.info.name, pg);
10410                    if (chatty) {
10411                        if (r == null) {
10412                            r = new StringBuilder(256);
10413                        } else {
10414                            r.append(' ');
10415                        }
10416                        if (isPackageUpdate) {
10417                            r.append("UPD:");
10418                        }
10419                        r.append(pg.info.name);
10420                    }
10421                } else {
10422                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10423                            + pg.info.packageName + " ignored: original from "
10424                            + cur.info.packageName);
10425                    if (chatty) {
10426                        if (r == null) {
10427                            r = new StringBuilder(256);
10428                        } else {
10429                            r.append(' ');
10430                        }
10431                        r.append("DUP:");
10432                        r.append(pg.info.name);
10433                    }
10434                }
10435            }
10436            if (r != null) {
10437                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10438            }
10439
10440            N = pkg.permissions.size();
10441            r = null;
10442            for (i=0; i<N; i++) {
10443                PackageParser.Permission p = pkg.permissions.get(i);
10444
10445                // Dont allow ephemeral apps to define new permissions.
10446                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10447                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10448                            + p.info.packageName
10449                            + " ignored: instant apps cannot define new permissions.");
10450                    continue;
10451                }
10452
10453                // Assume by default that we did not install this permission into the system.
10454                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10455
10456                // Now that permission groups have a special meaning, we ignore permission
10457                // groups for legacy apps to prevent unexpected behavior. In particular,
10458                // permissions for one app being granted to someone just becase they happen
10459                // to be in a group defined by another app (before this had no implications).
10460                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10461                    p.group = mPermissionGroups.get(p.info.group);
10462                    // Warn for a permission in an unknown group.
10463                    if (p.info.group != null && p.group == null) {
10464                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10465                                + p.info.packageName + " in an unknown group " + p.info.group);
10466                    }
10467                }
10468
10469                ArrayMap<String, BasePermission> permissionMap =
10470                        p.tree ? mSettings.mPermissionTrees
10471                                : mSettings.mPermissions;
10472                BasePermission bp = permissionMap.get(p.info.name);
10473
10474                // Allow system apps to redefine non-system permissions
10475                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10476                    final boolean currentOwnerIsSystem = (bp.perm != null
10477                            && isSystemApp(bp.perm.owner));
10478                    if (isSystemApp(p.owner)) {
10479                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10480                            // It's a built-in permission and no owner, take ownership now
10481                            bp.packageSetting = pkgSetting;
10482                            bp.perm = p;
10483                            bp.uid = pkg.applicationInfo.uid;
10484                            bp.sourcePackage = p.info.packageName;
10485                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10486                        } else if (!currentOwnerIsSystem) {
10487                            String msg = "New decl " + p.owner + " of permission  "
10488                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10489                            reportSettingsProblem(Log.WARN, msg);
10490                            bp = null;
10491                        }
10492                    }
10493                }
10494
10495                if (bp == null) {
10496                    bp = new BasePermission(p.info.name, p.info.packageName,
10497                            BasePermission.TYPE_NORMAL);
10498                    permissionMap.put(p.info.name, bp);
10499                }
10500
10501                if (bp.perm == null) {
10502                    if (bp.sourcePackage == null
10503                            || bp.sourcePackage.equals(p.info.packageName)) {
10504                        BasePermission tree = findPermissionTreeLP(p.info.name);
10505                        if (tree == null
10506                                || tree.sourcePackage.equals(p.info.packageName)) {
10507                            bp.packageSetting = pkgSetting;
10508                            bp.perm = p;
10509                            bp.uid = pkg.applicationInfo.uid;
10510                            bp.sourcePackage = p.info.packageName;
10511                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10512                            if (chatty) {
10513                                if (r == null) {
10514                                    r = new StringBuilder(256);
10515                                } else {
10516                                    r.append(' ');
10517                                }
10518                                r.append(p.info.name);
10519                            }
10520                        } else {
10521                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10522                                    + p.info.packageName + " ignored: base tree "
10523                                    + tree.name + " is from package "
10524                                    + tree.sourcePackage);
10525                        }
10526                    } else {
10527                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10528                                + p.info.packageName + " ignored: original from "
10529                                + bp.sourcePackage);
10530                    }
10531                } else if (chatty) {
10532                    if (r == null) {
10533                        r = new StringBuilder(256);
10534                    } else {
10535                        r.append(' ');
10536                    }
10537                    r.append("DUP:");
10538                    r.append(p.info.name);
10539                }
10540                if (bp.perm == p) {
10541                    bp.protectionLevel = p.info.protectionLevel;
10542                }
10543            }
10544
10545            if (r != null) {
10546                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10547            }
10548
10549            N = pkg.instrumentation.size();
10550            r = null;
10551            for (i=0; i<N; i++) {
10552                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10553                a.info.packageName = pkg.applicationInfo.packageName;
10554                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10555                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10556                a.info.splitNames = pkg.splitNames;
10557                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10558                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10559                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10560                a.info.dataDir = pkg.applicationInfo.dataDir;
10561                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10562                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10563                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10564                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10565                mInstrumentation.put(a.getComponentName(), a);
10566                if (chatty) {
10567                    if (r == null) {
10568                        r = new StringBuilder(256);
10569                    } else {
10570                        r.append(' ');
10571                    }
10572                    r.append(a.info.name);
10573                }
10574            }
10575            if (r != null) {
10576                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10577            }
10578
10579            if (pkg.protectedBroadcasts != null) {
10580                N = pkg.protectedBroadcasts.size();
10581                for (i=0; i<N; i++) {
10582                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10583                }
10584            }
10585        }
10586
10587        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10588    }
10589
10590    /**
10591     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10592     * is derived purely on the basis of the contents of {@code scanFile} and
10593     * {@code cpuAbiOverride}.
10594     *
10595     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10596     */
10597    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10598                                 String cpuAbiOverride, boolean extractLibs,
10599                                 File appLib32InstallDir)
10600            throws PackageManagerException {
10601        // Give ourselves some initial paths; we'll come back for another
10602        // pass once we've determined ABI below.
10603        setNativeLibraryPaths(pkg, appLib32InstallDir);
10604
10605        // We would never need to extract libs for forward-locked and external packages,
10606        // since the container service will do it for us. We shouldn't attempt to
10607        // extract libs from system app when it was not updated.
10608        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10609                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10610            extractLibs = false;
10611        }
10612
10613        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10614        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10615
10616        NativeLibraryHelper.Handle handle = null;
10617        try {
10618            handle = NativeLibraryHelper.Handle.create(pkg);
10619            // TODO(multiArch): This can be null for apps that didn't go through the
10620            // usual installation process. We can calculate it again, like we
10621            // do during install time.
10622            //
10623            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10624            // unnecessary.
10625            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10626
10627            // Null out the abis so that they can be recalculated.
10628            pkg.applicationInfo.primaryCpuAbi = null;
10629            pkg.applicationInfo.secondaryCpuAbi = null;
10630            if (isMultiArch(pkg.applicationInfo)) {
10631                // Warn if we've set an abiOverride for multi-lib packages..
10632                // By definition, we need to copy both 32 and 64 bit libraries for
10633                // such packages.
10634                if (pkg.cpuAbiOverride != null
10635                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10636                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10637                }
10638
10639                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10640                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10641                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10642                    if (extractLibs) {
10643                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10644                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10645                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10646                                useIsaSpecificSubdirs);
10647                    } else {
10648                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10649                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10650                    }
10651                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10652                }
10653
10654                maybeThrowExceptionForMultiArchCopy(
10655                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10656
10657                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10658                    if (extractLibs) {
10659                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10660                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10661                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10662                                useIsaSpecificSubdirs);
10663                    } else {
10664                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10665                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10666                    }
10667                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10668                }
10669
10670                maybeThrowExceptionForMultiArchCopy(
10671                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10672
10673                if (abi64 >= 0) {
10674                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10675                }
10676
10677                if (abi32 >= 0) {
10678                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10679                    if (abi64 >= 0) {
10680                        if (pkg.use32bitAbi) {
10681                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10682                            pkg.applicationInfo.primaryCpuAbi = abi;
10683                        } else {
10684                            pkg.applicationInfo.secondaryCpuAbi = abi;
10685                        }
10686                    } else {
10687                        pkg.applicationInfo.primaryCpuAbi = abi;
10688                    }
10689                }
10690
10691            } else {
10692                String[] abiList = (cpuAbiOverride != null) ?
10693                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10694
10695                // Enable gross and lame hacks for apps that are built with old
10696                // SDK tools. We must scan their APKs for renderscript bitcode and
10697                // not launch them if it's present. Don't bother checking on devices
10698                // that don't have 64 bit support.
10699                boolean needsRenderScriptOverride = false;
10700                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10701                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10702                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10703                    needsRenderScriptOverride = true;
10704                }
10705
10706                final int copyRet;
10707                if (extractLibs) {
10708                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10709                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10710                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10711                } else {
10712                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10713                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10714                }
10715                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10716
10717                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10718                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10719                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10720                }
10721
10722                if (copyRet >= 0) {
10723                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10724                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10725                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10726                } else if (needsRenderScriptOverride) {
10727                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10728                }
10729            }
10730        } catch (IOException ioe) {
10731            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10732        } finally {
10733            IoUtils.closeQuietly(handle);
10734        }
10735
10736        // Now that we've calculated the ABIs and determined if it's an internal app,
10737        // we will go ahead and populate the nativeLibraryPath.
10738        setNativeLibraryPaths(pkg, appLib32InstallDir);
10739    }
10740
10741    /**
10742     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10743     * i.e, so that all packages can be run inside a single process if required.
10744     *
10745     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10746     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10747     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10748     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10749     * updating a package that belongs to a shared user.
10750     *
10751     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10752     * adds unnecessary complexity.
10753     */
10754    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10755            PackageParser.Package scannedPackage) {
10756        String requiredInstructionSet = null;
10757        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10758            requiredInstructionSet = VMRuntime.getInstructionSet(
10759                     scannedPackage.applicationInfo.primaryCpuAbi);
10760        }
10761
10762        PackageSetting requirer = null;
10763        for (PackageSetting ps : packagesForUser) {
10764            // If packagesForUser contains scannedPackage, we skip it. This will happen
10765            // when scannedPackage is an update of an existing package. Without this check,
10766            // we will never be able to change the ABI of any package belonging to a shared
10767            // user, even if it's compatible with other packages.
10768            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10769                if (ps.primaryCpuAbiString == null) {
10770                    continue;
10771                }
10772
10773                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10774                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10775                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10776                    // this but there's not much we can do.
10777                    String errorMessage = "Instruction set mismatch, "
10778                            + ((requirer == null) ? "[caller]" : requirer)
10779                            + " requires " + requiredInstructionSet + " whereas " + ps
10780                            + " requires " + instructionSet;
10781                    Slog.w(TAG, errorMessage);
10782                }
10783
10784                if (requiredInstructionSet == null) {
10785                    requiredInstructionSet = instructionSet;
10786                    requirer = ps;
10787                }
10788            }
10789        }
10790
10791        if (requiredInstructionSet != null) {
10792            String adjustedAbi;
10793            if (requirer != null) {
10794                // requirer != null implies that either scannedPackage was null or that scannedPackage
10795                // did not require an ABI, in which case we have to adjust scannedPackage to match
10796                // the ABI of the set (which is the same as requirer's ABI)
10797                adjustedAbi = requirer.primaryCpuAbiString;
10798                if (scannedPackage != null) {
10799                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10800                }
10801            } else {
10802                // requirer == null implies that we're updating all ABIs in the set to
10803                // match scannedPackage.
10804                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10805            }
10806
10807            for (PackageSetting ps : packagesForUser) {
10808                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10809                    if (ps.primaryCpuAbiString != null) {
10810                        continue;
10811                    }
10812
10813                    ps.primaryCpuAbiString = adjustedAbi;
10814                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10815                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10816                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10817                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10818                                + " (requirer="
10819                                + (requirer != null ? requirer.pkg : "null")
10820                                + ", scannedPackage="
10821                                + (scannedPackage != null ? scannedPackage : "null")
10822                                + ")");
10823                        try {
10824                            mInstaller.rmdex(ps.codePathString,
10825                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10826                        } catch (InstallerException ignored) {
10827                        }
10828                    }
10829                }
10830            }
10831        }
10832    }
10833
10834    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10835        synchronized (mPackages) {
10836            mResolverReplaced = true;
10837            // Set up information for custom user intent resolution activity.
10838            mResolveActivity.applicationInfo = pkg.applicationInfo;
10839            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10840            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10841            mResolveActivity.processName = pkg.applicationInfo.packageName;
10842            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10843            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10844                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10845            mResolveActivity.theme = 0;
10846            mResolveActivity.exported = true;
10847            mResolveActivity.enabled = true;
10848            mResolveInfo.activityInfo = mResolveActivity;
10849            mResolveInfo.priority = 0;
10850            mResolveInfo.preferredOrder = 0;
10851            mResolveInfo.match = 0;
10852            mResolveComponentName = mCustomResolverComponentName;
10853            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10854                    mResolveComponentName);
10855        }
10856    }
10857
10858    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
10859        if (installerActivity == null) {
10860            if (DEBUG_EPHEMERAL) {
10861                Slog.d(TAG, "Clear ephemeral installer activity");
10862            }
10863            mInstantAppInstallerActivity = null;
10864            return;
10865        }
10866
10867        if (DEBUG_EPHEMERAL) {
10868            Slog.d(TAG, "Set ephemeral installer activity: "
10869                    + installerActivity.getComponentName());
10870        }
10871        // Set up information for ephemeral installer activity
10872        mInstantAppInstallerActivity = installerActivity;
10873        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10874                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10875        mInstantAppInstallerActivity.exported = true;
10876        mInstantAppInstallerActivity.enabled = true;
10877        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10878        mInstantAppInstallerInfo.priority = 0;
10879        mInstantAppInstallerInfo.preferredOrder = 1;
10880        mInstantAppInstallerInfo.isDefault = true;
10881        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10882                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10883    }
10884
10885    private static String calculateBundledApkRoot(final String codePathString) {
10886        final File codePath = new File(codePathString);
10887        final File codeRoot;
10888        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10889            codeRoot = Environment.getRootDirectory();
10890        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10891            codeRoot = Environment.getOemDirectory();
10892        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10893            codeRoot = Environment.getVendorDirectory();
10894        } else {
10895            // Unrecognized code path; take its top real segment as the apk root:
10896            // e.g. /something/app/blah.apk => /something
10897            try {
10898                File f = codePath.getCanonicalFile();
10899                File parent = f.getParentFile();    // non-null because codePath is a file
10900                File tmp;
10901                while ((tmp = parent.getParentFile()) != null) {
10902                    f = parent;
10903                    parent = tmp;
10904                }
10905                codeRoot = f;
10906                Slog.w(TAG, "Unrecognized code path "
10907                        + codePath + " - using " + codeRoot);
10908            } catch (IOException e) {
10909                // Can't canonicalize the code path -- shenanigans?
10910                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10911                return Environment.getRootDirectory().getPath();
10912            }
10913        }
10914        return codeRoot.getPath();
10915    }
10916
10917    /**
10918     * Derive and set the location of native libraries for the given package,
10919     * which varies depending on where and how the package was installed.
10920     */
10921    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10922        final ApplicationInfo info = pkg.applicationInfo;
10923        final String codePath = pkg.codePath;
10924        final File codeFile = new File(codePath);
10925        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10926        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10927
10928        info.nativeLibraryRootDir = null;
10929        info.nativeLibraryRootRequiresIsa = false;
10930        info.nativeLibraryDir = null;
10931        info.secondaryNativeLibraryDir = null;
10932
10933        if (isApkFile(codeFile)) {
10934            // Monolithic install
10935            if (bundledApp) {
10936                // If "/system/lib64/apkname" exists, assume that is the per-package
10937                // native library directory to use; otherwise use "/system/lib/apkname".
10938                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10939                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10940                        getPrimaryInstructionSet(info));
10941
10942                // This is a bundled system app so choose the path based on the ABI.
10943                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10944                // is just the default path.
10945                final String apkName = deriveCodePathName(codePath);
10946                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10947                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10948                        apkName).getAbsolutePath();
10949
10950                if (info.secondaryCpuAbi != null) {
10951                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10952                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10953                            secondaryLibDir, apkName).getAbsolutePath();
10954                }
10955            } else if (asecApp) {
10956                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10957                        .getAbsolutePath();
10958            } else {
10959                final String apkName = deriveCodePathName(codePath);
10960                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10961                        .getAbsolutePath();
10962            }
10963
10964            info.nativeLibraryRootRequiresIsa = false;
10965            info.nativeLibraryDir = info.nativeLibraryRootDir;
10966        } else {
10967            // Cluster install
10968            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10969            info.nativeLibraryRootRequiresIsa = true;
10970
10971            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10972                    getPrimaryInstructionSet(info)).getAbsolutePath();
10973
10974            if (info.secondaryCpuAbi != null) {
10975                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10976                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10977            }
10978        }
10979    }
10980
10981    /**
10982     * Calculate the abis and roots for a bundled app. These can uniquely
10983     * be determined from the contents of the system partition, i.e whether
10984     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10985     * of this information, and instead assume that the system was built
10986     * sensibly.
10987     */
10988    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10989                                           PackageSetting pkgSetting) {
10990        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10991
10992        // If "/system/lib64/apkname" exists, assume that is the per-package
10993        // native library directory to use; otherwise use "/system/lib/apkname".
10994        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10995        setBundledAppAbi(pkg, apkRoot, apkName);
10996        // pkgSetting might be null during rescan following uninstall of updates
10997        // to a bundled app, so accommodate that possibility.  The settings in
10998        // that case will be established later from the parsed package.
10999        //
11000        // If the settings aren't null, sync them up with what we've just derived.
11001        // note that apkRoot isn't stored in the package settings.
11002        if (pkgSetting != null) {
11003            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11004            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11005        }
11006    }
11007
11008    /**
11009     * Deduces the ABI of a bundled app and sets the relevant fields on the
11010     * parsed pkg object.
11011     *
11012     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11013     *        under which system libraries are installed.
11014     * @param apkName the name of the installed package.
11015     */
11016    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11017        final File codeFile = new File(pkg.codePath);
11018
11019        final boolean has64BitLibs;
11020        final boolean has32BitLibs;
11021        if (isApkFile(codeFile)) {
11022            // Monolithic install
11023            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11024            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11025        } else {
11026            // Cluster install
11027            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11028            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11029                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11030                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11031                has64BitLibs = (new File(rootDir, isa)).exists();
11032            } else {
11033                has64BitLibs = false;
11034            }
11035            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11036                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11037                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11038                has32BitLibs = (new File(rootDir, isa)).exists();
11039            } else {
11040                has32BitLibs = false;
11041            }
11042        }
11043
11044        if (has64BitLibs && !has32BitLibs) {
11045            // The package has 64 bit libs, but not 32 bit libs. Its primary
11046            // ABI should be 64 bit. We can safely assume here that the bundled
11047            // native libraries correspond to the most preferred ABI in the list.
11048
11049            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11050            pkg.applicationInfo.secondaryCpuAbi = null;
11051        } else if (has32BitLibs && !has64BitLibs) {
11052            // The package has 32 bit libs but not 64 bit libs. Its primary
11053            // ABI should be 32 bit.
11054
11055            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11056            pkg.applicationInfo.secondaryCpuAbi = null;
11057        } else if (has32BitLibs && has64BitLibs) {
11058            // The application has both 64 and 32 bit bundled libraries. We check
11059            // here that the app declares multiArch support, and warn if it doesn't.
11060            //
11061            // We will be lenient here and record both ABIs. The primary will be the
11062            // ABI that's higher on the list, i.e, a device that's configured to prefer
11063            // 64 bit apps will see a 64 bit primary ABI,
11064
11065            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11066                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11067            }
11068
11069            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11070                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11071                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11072            } else {
11073                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11074                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11075            }
11076        } else {
11077            pkg.applicationInfo.primaryCpuAbi = null;
11078            pkg.applicationInfo.secondaryCpuAbi = null;
11079        }
11080    }
11081
11082    private void killApplication(String pkgName, int appId, String reason) {
11083        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11084    }
11085
11086    private void killApplication(String pkgName, int appId, int userId, String reason) {
11087        // Request the ActivityManager to kill the process(only for existing packages)
11088        // so that we do not end up in a confused state while the user is still using the older
11089        // version of the application while the new one gets installed.
11090        final long token = Binder.clearCallingIdentity();
11091        try {
11092            IActivityManager am = ActivityManager.getService();
11093            if (am != null) {
11094                try {
11095                    am.killApplication(pkgName, appId, userId, reason);
11096                } catch (RemoteException e) {
11097                }
11098            }
11099        } finally {
11100            Binder.restoreCallingIdentity(token);
11101        }
11102    }
11103
11104    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11105        // Remove the parent package setting
11106        PackageSetting ps = (PackageSetting) pkg.mExtras;
11107        if (ps != null) {
11108            removePackageLI(ps, chatty);
11109        }
11110        // Remove the child package setting
11111        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11112        for (int i = 0; i < childCount; i++) {
11113            PackageParser.Package childPkg = pkg.childPackages.get(i);
11114            ps = (PackageSetting) childPkg.mExtras;
11115            if (ps != null) {
11116                removePackageLI(ps, chatty);
11117            }
11118        }
11119    }
11120
11121    void removePackageLI(PackageSetting ps, boolean chatty) {
11122        if (DEBUG_INSTALL) {
11123            if (chatty)
11124                Log.d(TAG, "Removing package " + ps.name);
11125        }
11126
11127        // writer
11128        synchronized (mPackages) {
11129            mPackages.remove(ps.name);
11130            final PackageParser.Package pkg = ps.pkg;
11131            if (pkg != null) {
11132                cleanPackageDataStructuresLILPw(pkg, chatty);
11133            }
11134        }
11135    }
11136
11137    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11138        if (DEBUG_INSTALL) {
11139            if (chatty)
11140                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11141        }
11142
11143        // writer
11144        synchronized (mPackages) {
11145            // Remove the parent package
11146            mPackages.remove(pkg.applicationInfo.packageName);
11147            cleanPackageDataStructuresLILPw(pkg, chatty);
11148
11149            // Remove the child packages
11150            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11151            for (int i = 0; i < childCount; i++) {
11152                PackageParser.Package childPkg = pkg.childPackages.get(i);
11153                mPackages.remove(childPkg.applicationInfo.packageName);
11154                cleanPackageDataStructuresLILPw(childPkg, chatty);
11155            }
11156        }
11157    }
11158
11159    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11160        int N = pkg.providers.size();
11161        StringBuilder r = null;
11162        int i;
11163        for (i=0; i<N; i++) {
11164            PackageParser.Provider p = pkg.providers.get(i);
11165            mProviders.removeProvider(p);
11166            if (p.info.authority == null) {
11167
11168                /* There was another ContentProvider with this authority when
11169                 * this app was installed so this authority is null,
11170                 * Ignore it as we don't have to unregister the provider.
11171                 */
11172                continue;
11173            }
11174            String names[] = p.info.authority.split(";");
11175            for (int j = 0; j < names.length; j++) {
11176                if (mProvidersByAuthority.get(names[j]) == p) {
11177                    mProvidersByAuthority.remove(names[j]);
11178                    if (DEBUG_REMOVE) {
11179                        if (chatty)
11180                            Log.d(TAG, "Unregistered content provider: " + names[j]
11181                                    + ", className = " + p.info.name + ", isSyncable = "
11182                                    + p.info.isSyncable);
11183                    }
11184                }
11185            }
11186            if (DEBUG_REMOVE && chatty) {
11187                if (r == null) {
11188                    r = new StringBuilder(256);
11189                } else {
11190                    r.append(' ');
11191                }
11192                r.append(p.info.name);
11193            }
11194        }
11195        if (r != null) {
11196            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11197        }
11198
11199        N = pkg.services.size();
11200        r = null;
11201        for (i=0; i<N; i++) {
11202            PackageParser.Service s = pkg.services.get(i);
11203            mServices.removeService(s);
11204            if (chatty) {
11205                if (r == null) {
11206                    r = new StringBuilder(256);
11207                } else {
11208                    r.append(' ');
11209                }
11210                r.append(s.info.name);
11211            }
11212        }
11213        if (r != null) {
11214            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11215        }
11216
11217        N = pkg.receivers.size();
11218        r = null;
11219        for (i=0; i<N; i++) {
11220            PackageParser.Activity a = pkg.receivers.get(i);
11221            mReceivers.removeActivity(a, "receiver");
11222            if (DEBUG_REMOVE && chatty) {
11223                if (r == null) {
11224                    r = new StringBuilder(256);
11225                } else {
11226                    r.append(' ');
11227                }
11228                r.append(a.info.name);
11229            }
11230        }
11231        if (r != null) {
11232            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11233        }
11234
11235        N = pkg.activities.size();
11236        r = null;
11237        for (i=0; i<N; i++) {
11238            PackageParser.Activity a = pkg.activities.get(i);
11239            mActivities.removeActivity(a, "activity");
11240            if (DEBUG_REMOVE && chatty) {
11241                if (r == null) {
11242                    r = new StringBuilder(256);
11243                } else {
11244                    r.append(' ');
11245                }
11246                r.append(a.info.name);
11247            }
11248        }
11249        if (r != null) {
11250            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11251        }
11252
11253        N = pkg.permissions.size();
11254        r = null;
11255        for (i=0; i<N; i++) {
11256            PackageParser.Permission p = pkg.permissions.get(i);
11257            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11258            if (bp == null) {
11259                bp = mSettings.mPermissionTrees.get(p.info.name);
11260            }
11261            if (bp != null && bp.perm == p) {
11262                bp.perm = null;
11263                if (DEBUG_REMOVE && chatty) {
11264                    if (r == null) {
11265                        r = new StringBuilder(256);
11266                    } else {
11267                        r.append(' ');
11268                    }
11269                    r.append(p.info.name);
11270                }
11271            }
11272            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11273                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11274                if (appOpPkgs != null) {
11275                    appOpPkgs.remove(pkg.packageName);
11276                }
11277            }
11278        }
11279        if (r != null) {
11280            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11281        }
11282
11283        N = pkg.requestedPermissions.size();
11284        r = null;
11285        for (i=0; i<N; i++) {
11286            String perm = pkg.requestedPermissions.get(i);
11287            BasePermission bp = mSettings.mPermissions.get(perm);
11288            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11289                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11290                if (appOpPkgs != null) {
11291                    appOpPkgs.remove(pkg.packageName);
11292                    if (appOpPkgs.isEmpty()) {
11293                        mAppOpPermissionPackages.remove(perm);
11294                    }
11295                }
11296            }
11297        }
11298        if (r != null) {
11299            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11300        }
11301
11302        N = pkg.instrumentation.size();
11303        r = null;
11304        for (i=0; i<N; i++) {
11305            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11306            mInstrumentation.remove(a.getComponentName());
11307            if (DEBUG_REMOVE && chatty) {
11308                if (r == null) {
11309                    r = new StringBuilder(256);
11310                } else {
11311                    r.append(' ');
11312                }
11313                r.append(a.info.name);
11314            }
11315        }
11316        if (r != null) {
11317            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11318        }
11319
11320        r = null;
11321        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11322            // Only system apps can hold shared libraries.
11323            if (pkg.libraryNames != null) {
11324                for (i = 0; i < pkg.libraryNames.size(); i++) {
11325                    String name = pkg.libraryNames.get(i);
11326                    if (removeSharedLibraryLPw(name, 0)) {
11327                        if (DEBUG_REMOVE && chatty) {
11328                            if (r == null) {
11329                                r = new StringBuilder(256);
11330                            } else {
11331                                r.append(' ');
11332                            }
11333                            r.append(name);
11334                        }
11335                    }
11336                }
11337            }
11338        }
11339
11340        r = null;
11341
11342        // Any package can hold static shared libraries.
11343        if (pkg.staticSharedLibName != null) {
11344            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11345                if (DEBUG_REMOVE && chatty) {
11346                    if (r == null) {
11347                        r = new StringBuilder(256);
11348                    } else {
11349                        r.append(' ');
11350                    }
11351                    r.append(pkg.staticSharedLibName);
11352                }
11353            }
11354        }
11355
11356        if (r != null) {
11357            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11358        }
11359    }
11360
11361    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11362        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11363            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11364                return true;
11365            }
11366        }
11367        return false;
11368    }
11369
11370    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11371    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11372    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11373
11374    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11375        // Update the parent permissions
11376        updatePermissionsLPw(pkg.packageName, pkg, flags);
11377        // Update the child permissions
11378        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11379        for (int i = 0; i < childCount; i++) {
11380            PackageParser.Package childPkg = pkg.childPackages.get(i);
11381            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11382        }
11383    }
11384
11385    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11386            int flags) {
11387        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11388        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11389    }
11390
11391    private void updatePermissionsLPw(String changingPkg,
11392            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11393        // Make sure there are no dangling permission trees.
11394        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11395        while (it.hasNext()) {
11396            final BasePermission bp = it.next();
11397            if (bp.packageSetting == null) {
11398                // We may not yet have parsed the package, so just see if
11399                // we still know about its settings.
11400                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11401            }
11402            if (bp.packageSetting == null) {
11403                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11404                        + " from package " + bp.sourcePackage);
11405                it.remove();
11406            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11407                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11408                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11409                            + " from package " + bp.sourcePackage);
11410                    flags |= UPDATE_PERMISSIONS_ALL;
11411                    it.remove();
11412                }
11413            }
11414        }
11415
11416        // Make sure all dynamic permissions have been assigned to a package,
11417        // and make sure there are no dangling permissions.
11418        it = mSettings.mPermissions.values().iterator();
11419        while (it.hasNext()) {
11420            final BasePermission bp = it.next();
11421            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11422                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11423                        + bp.name + " pkg=" + bp.sourcePackage
11424                        + " info=" + bp.pendingInfo);
11425                if (bp.packageSetting == null && bp.pendingInfo != null) {
11426                    final BasePermission tree = findPermissionTreeLP(bp.name);
11427                    if (tree != null && tree.perm != null) {
11428                        bp.packageSetting = tree.packageSetting;
11429                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11430                                new PermissionInfo(bp.pendingInfo));
11431                        bp.perm.info.packageName = tree.perm.info.packageName;
11432                        bp.perm.info.name = bp.name;
11433                        bp.uid = tree.uid;
11434                    }
11435                }
11436            }
11437            if (bp.packageSetting == null) {
11438                // We may not yet have parsed the package, so just see if
11439                // we still know about its settings.
11440                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11441            }
11442            if (bp.packageSetting == null) {
11443                Slog.w(TAG, "Removing dangling permission: " + bp.name
11444                        + " from package " + bp.sourcePackage);
11445                it.remove();
11446            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11447                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11448                    Slog.i(TAG, "Removing old permission: " + bp.name
11449                            + " from package " + bp.sourcePackage);
11450                    flags |= UPDATE_PERMISSIONS_ALL;
11451                    it.remove();
11452                }
11453            }
11454        }
11455
11456        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11457        // Now update the permissions for all packages, in particular
11458        // replace the granted permissions of the system packages.
11459        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11460            for (PackageParser.Package pkg : mPackages.values()) {
11461                if (pkg != pkgInfo) {
11462                    // Only replace for packages on requested volume
11463                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11464                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11465                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11466                    grantPermissionsLPw(pkg, replace, changingPkg);
11467                }
11468            }
11469        }
11470
11471        if (pkgInfo != null) {
11472            // Only replace for packages on requested volume
11473            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11474            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11475                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11476            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11477        }
11478        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11479    }
11480
11481    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11482            String packageOfInterest) {
11483        // IMPORTANT: There are two types of permissions: install and runtime.
11484        // Install time permissions are granted when the app is installed to
11485        // all device users and users added in the future. Runtime permissions
11486        // are granted at runtime explicitly to specific users. Normal and signature
11487        // protected permissions are install time permissions. Dangerous permissions
11488        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11489        // otherwise they are runtime permissions. This function does not manage
11490        // runtime permissions except for the case an app targeting Lollipop MR1
11491        // being upgraded to target a newer SDK, in which case dangerous permissions
11492        // are transformed from install time to runtime ones.
11493
11494        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11495        if (ps == null) {
11496            return;
11497        }
11498
11499        PermissionsState permissionsState = ps.getPermissionsState();
11500        PermissionsState origPermissions = permissionsState;
11501
11502        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11503
11504        boolean runtimePermissionsRevoked = false;
11505        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11506
11507        boolean changedInstallPermission = false;
11508
11509        if (replace) {
11510            ps.installPermissionsFixed = false;
11511            if (!ps.isSharedUser()) {
11512                origPermissions = new PermissionsState(permissionsState);
11513                permissionsState.reset();
11514            } else {
11515                // We need to know only about runtime permission changes since the
11516                // calling code always writes the install permissions state but
11517                // the runtime ones are written only if changed. The only cases of
11518                // changed runtime permissions here are promotion of an install to
11519                // runtime and revocation of a runtime from a shared user.
11520                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11521                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11522                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11523                    runtimePermissionsRevoked = true;
11524                }
11525            }
11526        }
11527
11528        permissionsState.setGlobalGids(mGlobalGids);
11529
11530        final int N = pkg.requestedPermissions.size();
11531        for (int i=0; i<N; i++) {
11532            final String name = pkg.requestedPermissions.get(i);
11533            final BasePermission bp = mSettings.mPermissions.get(name);
11534            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11535                    >= Build.VERSION_CODES.M;
11536
11537            if (DEBUG_INSTALL) {
11538                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11539            }
11540
11541            if (bp == null || bp.packageSetting == null) {
11542                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11543                    Slog.w(TAG, "Unknown permission " + name
11544                            + " in package " + pkg.packageName);
11545                }
11546                continue;
11547            }
11548
11549
11550            // Limit ephemeral apps to ephemeral allowed permissions.
11551            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11552                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11553                        + pkg.packageName);
11554                continue;
11555            }
11556
11557            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
11558                Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
11559                        + pkg.packageName);
11560                continue;
11561            }
11562
11563            final String perm = bp.name;
11564            boolean allowedSig = false;
11565            int grant = GRANT_DENIED;
11566
11567            // Keep track of app op permissions.
11568            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11569                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11570                if (pkgs == null) {
11571                    pkgs = new ArraySet<>();
11572                    mAppOpPermissionPackages.put(bp.name, pkgs);
11573                }
11574                pkgs.add(pkg.packageName);
11575            }
11576
11577            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11578            switch (level) {
11579                case PermissionInfo.PROTECTION_NORMAL: {
11580                    // For all apps normal permissions are install time ones.
11581                    grant = GRANT_INSTALL;
11582                } break;
11583
11584                case PermissionInfo.PROTECTION_DANGEROUS: {
11585                    // If a permission review is required for legacy apps we represent
11586                    // their permissions as always granted runtime ones since we need
11587                    // to keep the review required permission flag per user while an
11588                    // install permission's state is shared across all users.
11589                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11590                        // For legacy apps dangerous permissions are install time ones.
11591                        grant = GRANT_INSTALL;
11592                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11593                        // For legacy apps that became modern, install becomes runtime.
11594                        grant = GRANT_UPGRADE;
11595                    } else if (mPromoteSystemApps
11596                            && isSystemApp(ps)
11597                            && mExistingSystemPackages.contains(ps.name)) {
11598                        // For legacy system apps, install becomes runtime.
11599                        // We cannot check hasInstallPermission() for system apps since those
11600                        // permissions were granted implicitly and not persisted pre-M.
11601                        grant = GRANT_UPGRADE;
11602                    } else {
11603                        // For modern apps keep runtime permissions unchanged.
11604                        grant = GRANT_RUNTIME;
11605                    }
11606                } break;
11607
11608                case PermissionInfo.PROTECTION_SIGNATURE: {
11609                    // For all apps signature permissions are install time ones.
11610                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11611                    if (allowedSig) {
11612                        grant = GRANT_INSTALL;
11613                    }
11614                } break;
11615            }
11616
11617            if (DEBUG_INSTALL) {
11618                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11619            }
11620
11621            if (grant != GRANT_DENIED) {
11622                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11623                    // If this is an existing, non-system package, then
11624                    // we can't add any new permissions to it.
11625                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11626                        // Except...  if this is a permission that was added
11627                        // to the platform (note: need to only do this when
11628                        // updating the platform).
11629                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11630                            grant = GRANT_DENIED;
11631                        }
11632                    }
11633                }
11634
11635                switch (grant) {
11636                    case GRANT_INSTALL: {
11637                        // Revoke this as runtime permission to handle the case of
11638                        // a runtime permission being downgraded to an install one.
11639                        // Also in permission review mode we keep dangerous permissions
11640                        // for legacy apps
11641                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11642                            if (origPermissions.getRuntimePermissionState(
11643                                    bp.name, userId) != null) {
11644                                // Revoke the runtime permission and clear the flags.
11645                                origPermissions.revokeRuntimePermission(bp, userId);
11646                                origPermissions.updatePermissionFlags(bp, userId,
11647                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11648                                // If we revoked a permission permission, we have to write.
11649                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11650                                        changedRuntimePermissionUserIds, userId);
11651                            }
11652                        }
11653                        // Grant an install permission.
11654                        if (permissionsState.grantInstallPermission(bp) !=
11655                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11656                            changedInstallPermission = true;
11657                        }
11658                    } break;
11659
11660                    case GRANT_RUNTIME: {
11661                        // Grant previously granted runtime permissions.
11662                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11663                            PermissionState permissionState = origPermissions
11664                                    .getRuntimePermissionState(bp.name, userId);
11665                            int flags = permissionState != null
11666                                    ? permissionState.getFlags() : 0;
11667                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11668                                // Don't propagate the permission in a permission review mode if
11669                                // the former was revoked, i.e. marked to not propagate on upgrade.
11670                                // Note that in a permission review mode install permissions are
11671                                // represented as constantly granted runtime ones since we need to
11672                                // keep a per user state associated with the permission. Also the
11673                                // revoke on upgrade flag is no longer applicable and is reset.
11674                                final boolean revokeOnUpgrade = (flags & PackageManager
11675                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11676                                if (revokeOnUpgrade) {
11677                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11678                                    // Since we changed the flags, we have to write.
11679                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11680                                            changedRuntimePermissionUserIds, userId);
11681                                }
11682                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11683                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11684                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11685                                        // If we cannot put the permission as it was,
11686                                        // we have to write.
11687                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11688                                                changedRuntimePermissionUserIds, userId);
11689                                    }
11690                                }
11691
11692                                // If the app supports runtime permissions no need for a review.
11693                                if (mPermissionReviewRequired
11694                                        && appSupportsRuntimePermissions
11695                                        && (flags & PackageManager
11696                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11697                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11698                                    // Since we changed the flags, we have to write.
11699                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11700                                            changedRuntimePermissionUserIds, userId);
11701                                }
11702                            } else if (mPermissionReviewRequired
11703                                    && !appSupportsRuntimePermissions) {
11704                                // For legacy apps that need a permission review, every new
11705                                // runtime permission is granted but it is pending a review.
11706                                // We also need to review only platform defined runtime
11707                                // permissions as these are the only ones the platform knows
11708                                // how to disable the API to simulate revocation as legacy
11709                                // apps don't expect to run with revoked permissions.
11710                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11711                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11712                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11713                                        // We changed the flags, hence have to write.
11714                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11715                                                changedRuntimePermissionUserIds, userId);
11716                                    }
11717                                }
11718                                if (permissionsState.grantRuntimePermission(bp, userId)
11719                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11720                                    // We changed the permission, hence have to write.
11721                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11722                                            changedRuntimePermissionUserIds, userId);
11723                                }
11724                            }
11725                            // Propagate the permission flags.
11726                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11727                        }
11728                    } break;
11729
11730                    case GRANT_UPGRADE: {
11731                        // Grant runtime permissions for a previously held install permission.
11732                        PermissionState permissionState = origPermissions
11733                                .getInstallPermissionState(bp.name);
11734                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11735
11736                        if (origPermissions.revokeInstallPermission(bp)
11737                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11738                            // We will be transferring the permission flags, so clear them.
11739                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11740                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11741                            changedInstallPermission = true;
11742                        }
11743
11744                        // If the permission is not to be promoted to runtime we ignore it and
11745                        // also its other flags as they are not applicable to install permissions.
11746                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11747                            for (int userId : currentUserIds) {
11748                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11749                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11750                                    // Transfer the permission flags.
11751                                    permissionsState.updatePermissionFlags(bp, userId,
11752                                            flags, flags);
11753                                    // If we granted the permission, we have to write.
11754                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11755                                            changedRuntimePermissionUserIds, userId);
11756                                }
11757                            }
11758                        }
11759                    } break;
11760
11761                    default: {
11762                        if (packageOfInterest == null
11763                                || packageOfInterest.equals(pkg.packageName)) {
11764                            Slog.w(TAG, "Not granting permission " + perm
11765                                    + " to package " + pkg.packageName
11766                                    + " because it was previously installed without");
11767                        }
11768                    } break;
11769                }
11770            } else {
11771                if (permissionsState.revokeInstallPermission(bp) !=
11772                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11773                    // Also drop the permission flags.
11774                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11775                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11776                    changedInstallPermission = true;
11777                    Slog.i(TAG, "Un-granting permission " + perm
11778                            + " from package " + pkg.packageName
11779                            + " (protectionLevel=" + bp.protectionLevel
11780                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11781                            + ")");
11782                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11783                    // Don't print warning for app op permissions, since it is fine for them
11784                    // not to be granted, there is a UI for the user to decide.
11785                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11786                        Slog.w(TAG, "Not granting permission " + perm
11787                                + " to package " + pkg.packageName
11788                                + " (protectionLevel=" + bp.protectionLevel
11789                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11790                                + ")");
11791                    }
11792                }
11793            }
11794        }
11795
11796        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11797                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11798            // This is the first that we have heard about this package, so the
11799            // permissions we have now selected are fixed until explicitly
11800            // changed.
11801            ps.installPermissionsFixed = true;
11802        }
11803
11804        // Persist the runtime permissions state for users with changes. If permissions
11805        // were revoked because no app in the shared user declares them we have to
11806        // write synchronously to avoid losing runtime permissions state.
11807        for (int userId : changedRuntimePermissionUserIds) {
11808            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11809        }
11810    }
11811
11812    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11813        boolean allowed = false;
11814        final int NP = PackageParser.NEW_PERMISSIONS.length;
11815        for (int ip=0; ip<NP; ip++) {
11816            final PackageParser.NewPermissionInfo npi
11817                    = PackageParser.NEW_PERMISSIONS[ip];
11818            if (npi.name.equals(perm)
11819                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11820                allowed = true;
11821                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11822                        + pkg.packageName);
11823                break;
11824            }
11825        }
11826        return allowed;
11827    }
11828
11829    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11830            BasePermission bp, PermissionsState origPermissions) {
11831        boolean privilegedPermission = (bp.protectionLevel
11832                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11833        boolean privappPermissionsDisable =
11834                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11835        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11836        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11837        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11838                && !platformPackage && platformPermission) {
11839            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11840                    .getPrivAppPermissions(pkg.packageName);
11841            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11842            if (!whitelisted) {
11843                Slog.w(TAG, "Privileged permission " + perm + " for package "
11844                        + pkg.packageName + " - not in privapp-permissions whitelist");
11845                // Only report violations for apps on system image
11846                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11847                    if (mPrivappPermissionsViolations == null) {
11848                        mPrivappPermissionsViolations = new ArraySet<>();
11849                    }
11850                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11851                }
11852                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11853                    return false;
11854                }
11855            }
11856        }
11857        boolean allowed = (compareSignatures(
11858                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11859                        == PackageManager.SIGNATURE_MATCH)
11860                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11861                        == PackageManager.SIGNATURE_MATCH);
11862        if (!allowed && privilegedPermission) {
11863            if (isSystemApp(pkg)) {
11864                // For updated system applications, a system permission
11865                // is granted only if it had been defined by the original application.
11866                if (pkg.isUpdatedSystemApp()) {
11867                    final PackageSetting sysPs = mSettings
11868                            .getDisabledSystemPkgLPr(pkg.packageName);
11869                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11870                        // If the original was granted this permission, we take
11871                        // that grant decision as read and propagate it to the
11872                        // update.
11873                        if (sysPs.isPrivileged()) {
11874                            allowed = true;
11875                        }
11876                    } else {
11877                        // The system apk may have been updated with an older
11878                        // version of the one on the data partition, but which
11879                        // granted a new system permission that it didn't have
11880                        // before.  In this case we do want to allow the app to
11881                        // now get the new permission if the ancestral apk is
11882                        // privileged to get it.
11883                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11884                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11885                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11886                                    allowed = true;
11887                                    break;
11888                                }
11889                            }
11890                        }
11891                        // Also if a privileged parent package on the system image or any of
11892                        // its children requested a privileged permission, the updated child
11893                        // packages can also get the permission.
11894                        if (pkg.parentPackage != null) {
11895                            final PackageSetting disabledSysParentPs = mSettings
11896                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11897                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11898                                    && disabledSysParentPs.isPrivileged()) {
11899                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11900                                    allowed = true;
11901                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11902                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11903                                    for (int i = 0; i < count; i++) {
11904                                        PackageParser.Package disabledSysChildPkg =
11905                                                disabledSysParentPs.pkg.childPackages.get(i);
11906                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11907                                                perm)) {
11908                                            allowed = true;
11909                                            break;
11910                                        }
11911                                    }
11912                                }
11913                            }
11914                        }
11915                    }
11916                } else {
11917                    allowed = isPrivilegedApp(pkg);
11918                }
11919            }
11920        }
11921        if (!allowed) {
11922            if (!allowed && (bp.protectionLevel
11923                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11924                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11925                // If this was a previously normal/dangerous permission that got moved
11926                // to a system permission as part of the runtime permission redesign, then
11927                // we still want to blindly grant it to old apps.
11928                allowed = true;
11929            }
11930            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11931                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11932                // If this permission is to be granted to the system installer and
11933                // this app is an installer, then it gets the permission.
11934                allowed = true;
11935            }
11936            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11937                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11938                // If this permission is to be granted to the system verifier and
11939                // this app is a verifier, then it gets the permission.
11940                allowed = true;
11941            }
11942            if (!allowed && (bp.protectionLevel
11943                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11944                    && isSystemApp(pkg)) {
11945                // Any pre-installed system app is allowed to get this permission.
11946                allowed = true;
11947            }
11948            if (!allowed && (bp.protectionLevel
11949                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11950                // For development permissions, a development permission
11951                // is granted only if it was already granted.
11952                allowed = origPermissions.hasInstallPermission(perm);
11953            }
11954            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11955                    && pkg.packageName.equals(mSetupWizardPackage)) {
11956                // If this permission is to be granted to the system setup wizard and
11957                // this app is a setup wizard, then it gets the permission.
11958                allowed = true;
11959            }
11960        }
11961        return allowed;
11962    }
11963
11964    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11965        final int permCount = pkg.requestedPermissions.size();
11966        for (int j = 0; j < permCount; j++) {
11967            String requestedPermission = pkg.requestedPermissions.get(j);
11968            if (permission.equals(requestedPermission)) {
11969                return true;
11970            }
11971        }
11972        return false;
11973    }
11974
11975    final class ActivityIntentResolver
11976            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11977        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11978                boolean defaultOnly, int userId) {
11979            if (!sUserManager.exists(userId)) return null;
11980            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11981            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11982        }
11983
11984        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11985                int userId) {
11986            if (!sUserManager.exists(userId)) return null;
11987            mFlags = flags;
11988            return super.queryIntent(intent, resolvedType,
11989                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11990                    userId);
11991        }
11992
11993        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11994                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11995            if (!sUserManager.exists(userId)) return null;
11996            if (packageActivities == null) {
11997                return null;
11998            }
11999            mFlags = flags;
12000            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12001            final int N = packageActivities.size();
12002            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12003                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12004
12005            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12006            for (int i = 0; i < N; ++i) {
12007                intentFilters = packageActivities.get(i).intents;
12008                if (intentFilters != null && intentFilters.size() > 0) {
12009                    PackageParser.ActivityIntentInfo[] array =
12010                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12011                    intentFilters.toArray(array);
12012                    listCut.add(array);
12013                }
12014            }
12015            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12016        }
12017
12018        /**
12019         * Finds a privileged activity that matches the specified activity names.
12020         */
12021        private PackageParser.Activity findMatchingActivity(
12022                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12023            for (PackageParser.Activity sysActivity : activityList) {
12024                if (sysActivity.info.name.equals(activityInfo.name)) {
12025                    return sysActivity;
12026                }
12027                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12028                    return sysActivity;
12029                }
12030                if (sysActivity.info.targetActivity != null) {
12031                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12032                        return sysActivity;
12033                    }
12034                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12035                        return sysActivity;
12036                    }
12037                }
12038            }
12039            return null;
12040        }
12041
12042        public class IterGenerator<E> {
12043            public Iterator<E> generate(ActivityIntentInfo info) {
12044                return null;
12045            }
12046        }
12047
12048        public class ActionIterGenerator extends IterGenerator<String> {
12049            @Override
12050            public Iterator<String> generate(ActivityIntentInfo info) {
12051                return info.actionsIterator();
12052            }
12053        }
12054
12055        public class CategoriesIterGenerator extends IterGenerator<String> {
12056            @Override
12057            public Iterator<String> generate(ActivityIntentInfo info) {
12058                return info.categoriesIterator();
12059            }
12060        }
12061
12062        public class SchemesIterGenerator extends IterGenerator<String> {
12063            @Override
12064            public Iterator<String> generate(ActivityIntentInfo info) {
12065                return info.schemesIterator();
12066            }
12067        }
12068
12069        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12070            @Override
12071            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12072                return info.authoritiesIterator();
12073            }
12074        }
12075
12076        /**
12077         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12078         * MODIFIED. Do not pass in a list that should not be changed.
12079         */
12080        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12081                IterGenerator<T> generator, Iterator<T> searchIterator) {
12082            // loop through the set of actions; every one must be found in the intent filter
12083            while (searchIterator.hasNext()) {
12084                // we must have at least one filter in the list to consider a match
12085                if (intentList.size() == 0) {
12086                    break;
12087                }
12088
12089                final T searchAction = searchIterator.next();
12090
12091                // loop through the set of intent filters
12092                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12093                while (intentIter.hasNext()) {
12094                    final ActivityIntentInfo intentInfo = intentIter.next();
12095                    boolean selectionFound = false;
12096
12097                    // loop through the intent filter's selection criteria; at least one
12098                    // of them must match the searched criteria
12099                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12100                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12101                        final T intentSelection = intentSelectionIter.next();
12102                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12103                            selectionFound = true;
12104                            break;
12105                        }
12106                    }
12107
12108                    // the selection criteria wasn't found in this filter's set; this filter
12109                    // is not a potential match
12110                    if (!selectionFound) {
12111                        intentIter.remove();
12112                    }
12113                }
12114            }
12115        }
12116
12117        private boolean isProtectedAction(ActivityIntentInfo filter) {
12118            final Iterator<String> actionsIter = filter.actionsIterator();
12119            while (actionsIter != null && actionsIter.hasNext()) {
12120                final String filterAction = actionsIter.next();
12121                if (PROTECTED_ACTIONS.contains(filterAction)) {
12122                    return true;
12123                }
12124            }
12125            return false;
12126        }
12127
12128        /**
12129         * Adjusts the priority of the given intent filter according to policy.
12130         * <p>
12131         * <ul>
12132         * <li>The priority for non privileged applications is capped to '0'</li>
12133         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12134         * <li>The priority for unbundled updates to privileged applications is capped to the
12135         *      priority defined on the system partition</li>
12136         * </ul>
12137         * <p>
12138         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12139         * allowed to obtain any priority on any action.
12140         */
12141        private void adjustPriority(
12142                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12143            // nothing to do; priority is fine as-is
12144            if (intent.getPriority() <= 0) {
12145                return;
12146            }
12147
12148            final ActivityInfo activityInfo = intent.activity.info;
12149            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12150
12151            final boolean privilegedApp =
12152                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12153            if (!privilegedApp) {
12154                // non-privileged applications can never define a priority >0
12155                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12156                        + " package: " + applicationInfo.packageName
12157                        + " activity: " + intent.activity.className
12158                        + " origPrio: " + intent.getPriority());
12159                intent.setPriority(0);
12160                return;
12161            }
12162
12163            if (systemActivities == null) {
12164                // the system package is not disabled; we're parsing the system partition
12165                if (isProtectedAction(intent)) {
12166                    if (mDeferProtectedFilters) {
12167                        // We can't deal with these just yet. No component should ever obtain a
12168                        // >0 priority for a protected actions, with ONE exception -- the setup
12169                        // wizard. The setup wizard, however, cannot be known until we're able to
12170                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12171                        // until all intent filters have been processed. Chicken, meet egg.
12172                        // Let the filter temporarily have a high priority and rectify the
12173                        // priorities after all system packages have been scanned.
12174                        mProtectedFilters.add(intent);
12175                        if (DEBUG_FILTERS) {
12176                            Slog.i(TAG, "Protected action; save for later;"
12177                                    + " package: " + applicationInfo.packageName
12178                                    + " activity: " + intent.activity.className
12179                                    + " origPrio: " + intent.getPriority());
12180                        }
12181                        return;
12182                    } else {
12183                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12184                            Slog.i(TAG, "No setup wizard;"
12185                                + " All protected intents capped to priority 0");
12186                        }
12187                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12188                            if (DEBUG_FILTERS) {
12189                                Slog.i(TAG, "Found setup wizard;"
12190                                    + " allow priority " + intent.getPriority() + ";"
12191                                    + " package: " + intent.activity.info.packageName
12192                                    + " activity: " + intent.activity.className
12193                                    + " priority: " + intent.getPriority());
12194                            }
12195                            // setup wizard gets whatever it wants
12196                            return;
12197                        }
12198                        Slog.w(TAG, "Protected action; cap priority to 0;"
12199                                + " package: " + intent.activity.info.packageName
12200                                + " activity: " + intent.activity.className
12201                                + " origPrio: " + intent.getPriority());
12202                        intent.setPriority(0);
12203                        return;
12204                    }
12205                }
12206                // privileged apps on the system image get whatever priority they request
12207                return;
12208            }
12209
12210            // privileged app unbundled update ... try to find the same activity
12211            final PackageParser.Activity foundActivity =
12212                    findMatchingActivity(systemActivities, activityInfo);
12213            if (foundActivity == null) {
12214                // this is a new activity; it cannot obtain >0 priority
12215                if (DEBUG_FILTERS) {
12216                    Slog.i(TAG, "New activity; cap priority to 0;"
12217                            + " package: " + applicationInfo.packageName
12218                            + " activity: " + intent.activity.className
12219                            + " origPrio: " + intent.getPriority());
12220                }
12221                intent.setPriority(0);
12222                return;
12223            }
12224
12225            // found activity, now check for filter equivalence
12226
12227            // a shallow copy is enough; we modify the list, not its contents
12228            final List<ActivityIntentInfo> intentListCopy =
12229                    new ArrayList<>(foundActivity.intents);
12230            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12231
12232            // find matching action subsets
12233            final Iterator<String> actionsIterator = intent.actionsIterator();
12234            if (actionsIterator != null) {
12235                getIntentListSubset(
12236                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12237                if (intentListCopy.size() == 0) {
12238                    // no more intents to match; we're not equivalent
12239                    if (DEBUG_FILTERS) {
12240                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12241                                + " package: " + applicationInfo.packageName
12242                                + " activity: " + intent.activity.className
12243                                + " origPrio: " + intent.getPriority());
12244                    }
12245                    intent.setPriority(0);
12246                    return;
12247                }
12248            }
12249
12250            // find matching category subsets
12251            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12252            if (categoriesIterator != null) {
12253                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12254                        categoriesIterator);
12255                if (intentListCopy.size() == 0) {
12256                    // no more intents to match; we're not equivalent
12257                    if (DEBUG_FILTERS) {
12258                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12259                                + " package: " + applicationInfo.packageName
12260                                + " activity: " + intent.activity.className
12261                                + " origPrio: " + intent.getPriority());
12262                    }
12263                    intent.setPriority(0);
12264                    return;
12265                }
12266            }
12267
12268            // find matching schemes subsets
12269            final Iterator<String> schemesIterator = intent.schemesIterator();
12270            if (schemesIterator != null) {
12271                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12272                        schemesIterator);
12273                if (intentListCopy.size() == 0) {
12274                    // no more intents to match; we're not equivalent
12275                    if (DEBUG_FILTERS) {
12276                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12277                                + " package: " + applicationInfo.packageName
12278                                + " activity: " + intent.activity.className
12279                                + " origPrio: " + intent.getPriority());
12280                    }
12281                    intent.setPriority(0);
12282                    return;
12283                }
12284            }
12285
12286            // find matching authorities subsets
12287            final Iterator<IntentFilter.AuthorityEntry>
12288                    authoritiesIterator = intent.authoritiesIterator();
12289            if (authoritiesIterator != null) {
12290                getIntentListSubset(intentListCopy,
12291                        new AuthoritiesIterGenerator(),
12292                        authoritiesIterator);
12293                if (intentListCopy.size() == 0) {
12294                    // no more intents to match; we're not equivalent
12295                    if (DEBUG_FILTERS) {
12296                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12297                                + " package: " + applicationInfo.packageName
12298                                + " activity: " + intent.activity.className
12299                                + " origPrio: " + intent.getPriority());
12300                    }
12301                    intent.setPriority(0);
12302                    return;
12303                }
12304            }
12305
12306            // we found matching filter(s); app gets the max priority of all intents
12307            int cappedPriority = 0;
12308            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12309                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12310            }
12311            if (intent.getPriority() > cappedPriority) {
12312                if (DEBUG_FILTERS) {
12313                    Slog.i(TAG, "Found matching filter(s);"
12314                            + " cap priority to " + cappedPriority + ";"
12315                            + " package: " + applicationInfo.packageName
12316                            + " activity: " + intent.activity.className
12317                            + " origPrio: " + intent.getPriority());
12318                }
12319                intent.setPriority(cappedPriority);
12320                return;
12321            }
12322            // all this for nothing; the requested priority was <= what was on the system
12323        }
12324
12325        public final void addActivity(PackageParser.Activity a, String type) {
12326            mActivities.put(a.getComponentName(), a);
12327            if (DEBUG_SHOW_INFO)
12328                Log.v(
12329                TAG, "  " + type + " " +
12330                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12331            if (DEBUG_SHOW_INFO)
12332                Log.v(TAG, "    Class=" + a.info.name);
12333            final int NI = a.intents.size();
12334            for (int j=0; j<NI; j++) {
12335                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12336                if ("activity".equals(type)) {
12337                    final PackageSetting ps =
12338                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12339                    final List<PackageParser.Activity> systemActivities =
12340                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12341                    adjustPriority(systemActivities, intent);
12342                }
12343                if (DEBUG_SHOW_INFO) {
12344                    Log.v(TAG, "    IntentFilter:");
12345                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12346                }
12347                if (!intent.debugCheck()) {
12348                    Log.w(TAG, "==> For Activity " + a.info.name);
12349                }
12350                addFilter(intent);
12351            }
12352        }
12353
12354        public final void removeActivity(PackageParser.Activity a, String type) {
12355            mActivities.remove(a.getComponentName());
12356            if (DEBUG_SHOW_INFO) {
12357                Log.v(TAG, "  " + type + " "
12358                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12359                                : a.info.name) + ":");
12360                Log.v(TAG, "    Class=" + a.info.name);
12361            }
12362            final int NI = a.intents.size();
12363            for (int j=0; j<NI; j++) {
12364                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12365                if (DEBUG_SHOW_INFO) {
12366                    Log.v(TAG, "    IntentFilter:");
12367                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12368                }
12369                removeFilter(intent);
12370            }
12371        }
12372
12373        @Override
12374        protected boolean allowFilterResult(
12375                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12376            ActivityInfo filterAi = filter.activity.info;
12377            for (int i=dest.size()-1; i>=0; i--) {
12378                ActivityInfo destAi = dest.get(i).activityInfo;
12379                if (destAi.name == filterAi.name
12380                        && destAi.packageName == filterAi.packageName) {
12381                    return false;
12382                }
12383            }
12384            return true;
12385        }
12386
12387        @Override
12388        protected ActivityIntentInfo[] newArray(int size) {
12389            return new ActivityIntentInfo[size];
12390        }
12391
12392        @Override
12393        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12394            if (!sUserManager.exists(userId)) return true;
12395            PackageParser.Package p = filter.activity.owner;
12396            if (p != null) {
12397                PackageSetting ps = (PackageSetting)p.mExtras;
12398                if (ps != null) {
12399                    // System apps are never considered stopped for purposes of
12400                    // filtering, because there may be no way for the user to
12401                    // actually re-launch them.
12402                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12403                            && ps.getStopped(userId);
12404                }
12405            }
12406            return false;
12407        }
12408
12409        @Override
12410        protected boolean isPackageForFilter(String packageName,
12411                PackageParser.ActivityIntentInfo info) {
12412            return packageName.equals(info.activity.owner.packageName);
12413        }
12414
12415        @Override
12416        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12417                int match, int userId) {
12418            if (!sUserManager.exists(userId)) return null;
12419            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12420                return null;
12421            }
12422            final PackageParser.Activity activity = info.activity;
12423            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12424            if (ps == null) {
12425                return null;
12426            }
12427            final PackageUserState userState = ps.readUserState(userId);
12428            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
12429            if (ai == null) {
12430                return null;
12431            }
12432            final boolean matchVisibleToInstantApp =
12433                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12434            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12435            // throw out filters that aren't visible to ephemeral apps
12436            if (matchVisibleToInstantApp
12437                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12438                return null;
12439            }
12440            // throw out ephemeral filters if we're not explicitly requesting them
12441            if (!isInstantApp && userState.instantApp) {
12442                return null;
12443            }
12444            // throw out instant app filters if updates are available; will trigger
12445            // instant app resolution
12446            if (userState.instantApp && ps.isUpdateAvailable()) {
12447                return null;
12448            }
12449            final ResolveInfo res = new ResolveInfo();
12450            res.activityInfo = ai;
12451            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12452                res.filter = info;
12453            }
12454            if (info != null) {
12455                res.handleAllWebDataURI = info.handleAllWebDataURI();
12456            }
12457            res.priority = info.getPriority();
12458            res.preferredOrder = activity.owner.mPreferredOrder;
12459            //System.out.println("Result: " + res.activityInfo.className +
12460            //                   " = " + res.priority);
12461            res.match = match;
12462            res.isDefault = info.hasDefault;
12463            res.labelRes = info.labelRes;
12464            res.nonLocalizedLabel = info.nonLocalizedLabel;
12465            if (userNeedsBadging(userId)) {
12466                res.noResourceId = true;
12467            } else {
12468                res.icon = info.icon;
12469            }
12470            res.iconResourceId = info.icon;
12471            res.system = res.activityInfo.applicationInfo.isSystemApp();
12472            res.instantAppAvailable = userState.instantApp;
12473            return res;
12474        }
12475
12476        @Override
12477        protected void sortResults(List<ResolveInfo> results) {
12478            Collections.sort(results, mResolvePrioritySorter);
12479        }
12480
12481        @Override
12482        protected void dumpFilter(PrintWriter out, String prefix,
12483                PackageParser.ActivityIntentInfo filter) {
12484            out.print(prefix); out.print(
12485                    Integer.toHexString(System.identityHashCode(filter.activity)));
12486                    out.print(' ');
12487                    filter.activity.printComponentShortName(out);
12488                    out.print(" filter ");
12489                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12490        }
12491
12492        @Override
12493        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12494            return filter.activity;
12495        }
12496
12497        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12498            PackageParser.Activity activity = (PackageParser.Activity)label;
12499            out.print(prefix); out.print(
12500                    Integer.toHexString(System.identityHashCode(activity)));
12501                    out.print(' ');
12502                    activity.printComponentShortName(out);
12503            if (count > 1) {
12504                out.print(" ("); out.print(count); out.print(" filters)");
12505            }
12506            out.println();
12507        }
12508
12509        // Keys are String (activity class name), values are Activity.
12510        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12511                = new ArrayMap<ComponentName, PackageParser.Activity>();
12512        private int mFlags;
12513    }
12514
12515    private final class ServiceIntentResolver
12516            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12517        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12518                boolean defaultOnly, int userId) {
12519            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12520            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12521        }
12522
12523        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12524                int userId) {
12525            if (!sUserManager.exists(userId)) return null;
12526            mFlags = flags;
12527            return super.queryIntent(intent, resolvedType,
12528                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12529                    userId);
12530        }
12531
12532        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12533                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12534            if (!sUserManager.exists(userId)) return null;
12535            if (packageServices == null) {
12536                return null;
12537            }
12538            mFlags = flags;
12539            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12540            final int N = packageServices.size();
12541            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12542                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12543
12544            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12545            for (int i = 0; i < N; ++i) {
12546                intentFilters = packageServices.get(i).intents;
12547                if (intentFilters != null && intentFilters.size() > 0) {
12548                    PackageParser.ServiceIntentInfo[] array =
12549                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12550                    intentFilters.toArray(array);
12551                    listCut.add(array);
12552                }
12553            }
12554            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12555        }
12556
12557        public final void addService(PackageParser.Service s) {
12558            mServices.put(s.getComponentName(), s);
12559            if (DEBUG_SHOW_INFO) {
12560                Log.v(TAG, "  "
12561                        + (s.info.nonLocalizedLabel != null
12562                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12563                Log.v(TAG, "    Class=" + s.info.name);
12564            }
12565            final int NI = s.intents.size();
12566            int j;
12567            for (j=0; j<NI; j++) {
12568                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12569                if (DEBUG_SHOW_INFO) {
12570                    Log.v(TAG, "    IntentFilter:");
12571                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12572                }
12573                if (!intent.debugCheck()) {
12574                    Log.w(TAG, "==> For Service " + s.info.name);
12575                }
12576                addFilter(intent);
12577            }
12578        }
12579
12580        public final void removeService(PackageParser.Service s) {
12581            mServices.remove(s.getComponentName());
12582            if (DEBUG_SHOW_INFO) {
12583                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12584                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12585                Log.v(TAG, "    Class=" + s.info.name);
12586            }
12587            final int NI = s.intents.size();
12588            int j;
12589            for (j=0; j<NI; j++) {
12590                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12591                if (DEBUG_SHOW_INFO) {
12592                    Log.v(TAG, "    IntentFilter:");
12593                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12594                }
12595                removeFilter(intent);
12596            }
12597        }
12598
12599        @Override
12600        protected boolean allowFilterResult(
12601                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12602            ServiceInfo filterSi = filter.service.info;
12603            for (int i=dest.size()-1; i>=0; i--) {
12604                ServiceInfo destAi = dest.get(i).serviceInfo;
12605                if (destAi.name == filterSi.name
12606                        && destAi.packageName == filterSi.packageName) {
12607                    return false;
12608                }
12609            }
12610            return true;
12611        }
12612
12613        @Override
12614        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12615            return new PackageParser.ServiceIntentInfo[size];
12616        }
12617
12618        @Override
12619        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12620            if (!sUserManager.exists(userId)) return true;
12621            PackageParser.Package p = filter.service.owner;
12622            if (p != null) {
12623                PackageSetting ps = (PackageSetting)p.mExtras;
12624                if (ps != null) {
12625                    // System apps are never considered stopped for purposes of
12626                    // filtering, because there may be no way for the user to
12627                    // actually re-launch them.
12628                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12629                            && ps.getStopped(userId);
12630                }
12631            }
12632            return false;
12633        }
12634
12635        @Override
12636        protected boolean isPackageForFilter(String packageName,
12637                PackageParser.ServiceIntentInfo info) {
12638            return packageName.equals(info.service.owner.packageName);
12639        }
12640
12641        @Override
12642        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12643                int match, int userId) {
12644            if (!sUserManager.exists(userId)) return null;
12645            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12646            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12647                return null;
12648            }
12649            final PackageParser.Service service = info.service;
12650            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12651            if (ps == null) {
12652                return null;
12653            }
12654            final PackageUserState userState = ps.readUserState(userId);
12655            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12656                    userState, userId);
12657            if (si == null) {
12658                return null;
12659            }
12660            final boolean matchVisibleToInstantApp =
12661                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12662            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12663            // throw out filters that aren't visible to ephemeral apps
12664            if (matchVisibleToInstantApp
12665                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12666                return null;
12667            }
12668            // throw out ephemeral filters if we're not explicitly requesting them
12669            if (!isInstantApp && userState.instantApp) {
12670                return null;
12671            }
12672            // throw out instant app filters if updates are available; will trigger
12673            // instant app resolution
12674            if (userState.instantApp && ps.isUpdateAvailable()) {
12675                return null;
12676            }
12677            final ResolveInfo res = new ResolveInfo();
12678            res.serviceInfo = si;
12679            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12680                res.filter = filter;
12681            }
12682            res.priority = info.getPriority();
12683            res.preferredOrder = service.owner.mPreferredOrder;
12684            res.match = match;
12685            res.isDefault = info.hasDefault;
12686            res.labelRes = info.labelRes;
12687            res.nonLocalizedLabel = info.nonLocalizedLabel;
12688            res.icon = info.icon;
12689            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12690            return res;
12691        }
12692
12693        @Override
12694        protected void sortResults(List<ResolveInfo> results) {
12695            Collections.sort(results, mResolvePrioritySorter);
12696        }
12697
12698        @Override
12699        protected void dumpFilter(PrintWriter out, String prefix,
12700                PackageParser.ServiceIntentInfo filter) {
12701            out.print(prefix); out.print(
12702                    Integer.toHexString(System.identityHashCode(filter.service)));
12703                    out.print(' ');
12704                    filter.service.printComponentShortName(out);
12705                    out.print(" filter ");
12706                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12707        }
12708
12709        @Override
12710        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12711            return filter.service;
12712        }
12713
12714        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12715            PackageParser.Service service = (PackageParser.Service)label;
12716            out.print(prefix); out.print(
12717                    Integer.toHexString(System.identityHashCode(service)));
12718                    out.print(' ');
12719                    service.printComponentShortName(out);
12720            if (count > 1) {
12721                out.print(" ("); out.print(count); out.print(" filters)");
12722            }
12723            out.println();
12724        }
12725
12726//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12727//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12728//            final List<ResolveInfo> retList = Lists.newArrayList();
12729//            while (i.hasNext()) {
12730//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12731//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12732//                    retList.add(resolveInfo);
12733//                }
12734//            }
12735//            return retList;
12736//        }
12737
12738        // Keys are String (activity class name), values are Activity.
12739        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12740                = new ArrayMap<ComponentName, PackageParser.Service>();
12741        private int mFlags;
12742    }
12743
12744    private final class ProviderIntentResolver
12745            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12746        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12747                boolean defaultOnly, int userId) {
12748            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12749            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12750        }
12751
12752        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12753                int userId) {
12754            if (!sUserManager.exists(userId))
12755                return null;
12756            mFlags = flags;
12757            return super.queryIntent(intent, resolvedType,
12758                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12759                    userId);
12760        }
12761
12762        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12763                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12764            if (!sUserManager.exists(userId))
12765                return null;
12766            if (packageProviders == null) {
12767                return null;
12768            }
12769            mFlags = flags;
12770            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12771            final int N = packageProviders.size();
12772            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12773                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12774
12775            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12776            for (int i = 0; i < N; ++i) {
12777                intentFilters = packageProviders.get(i).intents;
12778                if (intentFilters != null && intentFilters.size() > 0) {
12779                    PackageParser.ProviderIntentInfo[] array =
12780                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12781                    intentFilters.toArray(array);
12782                    listCut.add(array);
12783                }
12784            }
12785            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12786        }
12787
12788        public final void addProvider(PackageParser.Provider p) {
12789            if (mProviders.containsKey(p.getComponentName())) {
12790                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12791                return;
12792            }
12793
12794            mProviders.put(p.getComponentName(), p);
12795            if (DEBUG_SHOW_INFO) {
12796                Log.v(TAG, "  "
12797                        + (p.info.nonLocalizedLabel != null
12798                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12799                Log.v(TAG, "    Class=" + p.info.name);
12800            }
12801            final int NI = p.intents.size();
12802            int j;
12803            for (j = 0; j < NI; j++) {
12804                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12805                if (DEBUG_SHOW_INFO) {
12806                    Log.v(TAG, "    IntentFilter:");
12807                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12808                }
12809                if (!intent.debugCheck()) {
12810                    Log.w(TAG, "==> For Provider " + p.info.name);
12811                }
12812                addFilter(intent);
12813            }
12814        }
12815
12816        public final void removeProvider(PackageParser.Provider p) {
12817            mProviders.remove(p.getComponentName());
12818            if (DEBUG_SHOW_INFO) {
12819                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12820                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12821                Log.v(TAG, "    Class=" + p.info.name);
12822            }
12823            final int NI = p.intents.size();
12824            int j;
12825            for (j = 0; j < NI; j++) {
12826                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12827                if (DEBUG_SHOW_INFO) {
12828                    Log.v(TAG, "    IntentFilter:");
12829                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12830                }
12831                removeFilter(intent);
12832            }
12833        }
12834
12835        @Override
12836        protected boolean allowFilterResult(
12837                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12838            ProviderInfo filterPi = filter.provider.info;
12839            for (int i = dest.size() - 1; i >= 0; i--) {
12840                ProviderInfo destPi = dest.get(i).providerInfo;
12841                if (destPi.name == filterPi.name
12842                        && destPi.packageName == filterPi.packageName) {
12843                    return false;
12844                }
12845            }
12846            return true;
12847        }
12848
12849        @Override
12850        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12851            return new PackageParser.ProviderIntentInfo[size];
12852        }
12853
12854        @Override
12855        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12856            if (!sUserManager.exists(userId))
12857                return true;
12858            PackageParser.Package p = filter.provider.owner;
12859            if (p != null) {
12860                PackageSetting ps = (PackageSetting) p.mExtras;
12861                if (ps != null) {
12862                    // System apps are never considered stopped for purposes of
12863                    // filtering, because there may be no way for the user to
12864                    // actually re-launch them.
12865                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12866                            && ps.getStopped(userId);
12867                }
12868            }
12869            return false;
12870        }
12871
12872        @Override
12873        protected boolean isPackageForFilter(String packageName,
12874                PackageParser.ProviderIntentInfo info) {
12875            return packageName.equals(info.provider.owner.packageName);
12876        }
12877
12878        @Override
12879        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12880                int match, int userId) {
12881            if (!sUserManager.exists(userId))
12882                return null;
12883            final PackageParser.ProviderIntentInfo info = filter;
12884            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12885                return null;
12886            }
12887            final PackageParser.Provider provider = info.provider;
12888            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12889            if (ps == null) {
12890                return null;
12891            }
12892            final PackageUserState userState = ps.readUserState(userId);
12893            final boolean matchVisibleToInstantApp =
12894                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12895            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12896            // throw out filters that aren't visible to instant applications
12897            if (matchVisibleToInstantApp
12898                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12899                return null;
12900            }
12901            // throw out instant application filters if we're not explicitly requesting them
12902            if (!isInstantApp && userState.instantApp) {
12903                return null;
12904            }
12905            // throw out instant application filters if updates are available; will trigger
12906            // instant application resolution
12907            if (userState.instantApp && ps.isUpdateAvailable()) {
12908                return null;
12909            }
12910            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12911                    userState, userId);
12912            if (pi == null) {
12913                return null;
12914            }
12915            final ResolveInfo res = new ResolveInfo();
12916            res.providerInfo = pi;
12917            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12918                res.filter = filter;
12919            }
12920            res.priority = info.getPriority();
12921            res.preferredOrder = provider.owner.mPreferredOrder;
12922            res.match = match;
12923            res.isDefault = info.hasDefault;
12924            res.labelRes = info.labelRes;
12925            res.nonLocalizedLabel = info.nonLocalizedLabel;
12926            res.icon = info.icon;
12927            res.system = res.providerInfo.applicationInfo.isSystemApp();
12928            return res;
12929        }
12930
12931        @Override
12932        protected void sortResults(List<ResolveInfo> results) {
12933            Collections.sort(results, mResolvePrioritySorter);
12934        }
12935
12936        @Override
12937        protected void dumpFilter(PrintWriter out, String prefix,
12938                PackageParser.ProviderIntentInfo filter) {
12939            out.print(prefix);
12940            out.print(
12941                    Integer.toHexString(System.identityHashCode(filter.provider)));
12942            out.print(' ');
12943            filter.provider.printComponentShortName(out);
12944            out.print(" filter ");
12945            out.println(Integer.toHexString(System.identityHashCode(filter)));
12946        }
12947
12948        @Override
12949        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12950            return filter.provider;
12951        }
12952
12953        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12954            PackageParser.Provider provider = (PackageParser.Provider)label;
12955            out.print(prefix); out.print(
12956                    Integer.toHexString(System.identityHashCode(provider)));
12957                    out.print(' ');
12958                    provider.printComponentShortName(out);
12959            if (count > 1) {
12960                out.print(" ("); out.print(count); out.print(" filters)");
12961            }
12962            out.println();
12963        }
12964
12965        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12966                = new ArrayMap<ComponentName, PackageParser.Provider>();
12967        private int mFlags;
12968    }
12969
12970    static final class EphemeralIntentResolver
12971            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12972        /**
12973         * The result that has the highest defined order. Ordering applies on a
12974         * per-package basis. Mapping is from package name to Pair of order and
12975         * EphemeralResolveInfo.
12976         * <p>
12977         * NOTE: This is implemented as a field variable for convenience and efficiency.
12978         * By having a field variable, we're able to track filter ordering as soon as
12979         * a non-zero order is defined. Otherwise, multiple loops across the result set
12980         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12981         * this needs to be contained entirely within {@link #filterResults}.
12982         */
12983        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12984
12985        @Override
12986        protected AuxiliaryResolveInfo[] newArray(int size) {
12987            return new AuxiliaryResolveInfo[size];
12988        }
12989
12990        @Override
12991        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12992            return true;
12993        }
12994
12995        @Override
12996        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12997                int userId) {
12998            if (!sUserManager.exists(userId)) {
12999                return null;
13000            }
13001            final String packageName = responseObj.resolveInfo.getPackageName();
13002            final Integer order = responseObj.getOrder();
13003            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13004                    mOrderResult.get(packageName);
13005            // ordering is enabled and this item's order isn't high enough
13006            if (lastOrderResult != null && lastOrderResult.first >= order) {
13007                return null;
13008            }
13009            final InstantAppResolveInfo res = responseObj.resolveInfo;
13010            if (order > 0) {
13011                // non-zero order, enable ordering
13012                mOrderResult.put(packageName, new Pair<>(order, res));
13013            }
13014            return responseObj;
13015        }
13016
13017        @Override
13018        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13019            // only do work if ordering is enabled [most of the time it won't be]
13020            if (mOrderResult.size() == 0) {
13021                return;
13022            }
13023            int resultSize = results.size();
13024            for (int i = 0; i < resultSize; i++) {
13025                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13026                final String packageName = info.getPackageName();
13027                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13028                if (savedInfo == null) {
13029                    // package doesn't having ordering
13030                    continue;
13031                }
13032                if (savedInfo.second == info) {
13033                    // circled back to the highest ordered item; remove from order list
13034                    mOrderResult.remove(savedInfo);
13035                    if (mOrderResult.size() == 0) {
13036                        // no more ordered items
13037                        break;
13038                    }
13039                    continue;
13040                }
13041                // item has a worse order, remove it from the result list
13042                results.remove(i);
13043                resultSize--;
13044                i--;
13045            }
13046        }
13047    }
13048
13049    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13050            new Comparator<ResolveInfo>() {
13051        public int compare(ResolveInfo r1, ResolveInfo r2) {
13052            int v1 = r1.priority;
13053            int v2 = r2.priority;
13054            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13055            if (v1 != v2) {
13056                return (v1 > v2) ? -1 : 1;
13057            }
13058            v1 = r1.preferredOrder;
13059            v2 = r2.preferredOrder;
13060            if (v1 != v2) {
13061                return (v1 > v2) ? -1 : 1;
13062            }
13063            if (r1.isDefault != r2.isDefault) {
13064                return r1.isDefault ? -1 : 1;
13065            }
13066            v1 = r1.match;
13067            v2 = r2.match;
13068            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13069            if (v1 != v2) {
13070                return (v1 > v2) ? -1 : 1;
13071            }
13072            if (r1.system != r2.system) {
13073                return r1.system ? -1 : 1;
13074            }
13075            if (r1.activityInfo != null) {
13076                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13077            }
13078            if (r1.serviceInfo != null) {
13079                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13080            }
13081            if (r1.providerInfo != null) {
13082                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13083            }
13084            return 0;
13085        }
13086    };
13087
13088    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13089            new Comparator<ProviderInfo>() {
13090        public int compare(ProviderInfo p1, ProviderInfo p2) {
13091            final int v1 = p1.initOrder;
13092            final int v2 = p2.initOrder;
13093            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13094        }
13095    };
13096
13097    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13098            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13099            final int[] userIds) {
13100        mHandler.post(new Runnable() {
13101            @Override
13102            public void run() {
13103                try {
13104                    final IActivityManager am = ActivityManager.getService();
13105                    if (am == null) return;
13106                    final int[] resolvedUserIds;
13107                    if (userIds == null) {
13108                        resolvedUserIds = am.getRunningUserIds();
13109                    } else {
13110                        resolvedUserIds = userIds;
13111                    }
13112                    for (int id : resolvedUserIds) {
13113                        final Intent intent = new Intent(action,
13114                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13115                        if (extras != null) {
13116                            intent.putExtras(extras);
13117                        }
13118                        if (targetPkg != null) {
13119                            intent.setPackage(targetPkg);
13120                        }
13121                        // Modify the UID when posting to other users
13122                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13123                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13124                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13125                            intent.putExtra(Intent.EXTRA_UID, uid);
13126                        }
13127                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13128                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13129                        if (DEBUG_BROADCASTS) {
13130                            RuntimeException here = new RuntimeException("here");
13131                            here.fillInStackTrace();
13132                            Slog.d(TAG, "Sending to user " + id + ": "
13133                                    + intent.toShortString(false, true, false, false)
13134                                    + " " + intent.getExtras(), here);
13135                        }
13136                        am.broadcastIntent(null, intent, null, finishedReceiver,
13137                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13138                                null, finishedReceiver != null, false, id);
13139                    }
13140                } catch (RemoteException ex) {
13141                }
13142            }
13143        });
13144    }
13145
13146    /**
13147     * Check if the external storage media is available. This is true if there
13148     * is a mounted external storage medium or if the external storage is
13149     * emulated.
13150     */
13151    private boolean isExternalMediaAvailable() {
13152        return mMediaMounted || Environment.isExternalStorageEmulated();
13153    }
13154
13155    @Override
13156    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13157        // writer
13158        synchronized (mPackages) {
13159            if (!isExternalMediaAvailable()) {
13160                // If the external storage is no longer mounted at this point,
13161                // the caller may not have been able to delete all of this
13162                // packages files and can not delete any more.  Bail.
13163                return null;
13164            }
13165            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13166            if (lastPackage != null) {
13167                pkgs.remove(lastPackage);
13168            }
13169            if (pkgs.size() > 0) {
13170                return pkgs.get(0);
13171            }
13172        }
13173        return null;
13174    }
13175
13176    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13177        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13178                userId, andCode ? 1 : 0, packageName);
13179        if (mSystemReady) {
13180            msg.sendToTarget();
13181        } else {
13182            if (mPostSystemReadyMessages == null) {
13183                mPostSystemReadyMessages = new ArrayList<>();
13184            }
13185            mPostSystemReadyMessages.add(msg);
13186        }
13187    }
13188
13189    void startCleaningPackages() {
13190        // reader
13191        if (!isExternalMediaAvailable()) {
13192            return;
13193        }
13194        synchronized (mPackages) {
13195            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13196                return;
13197            }
13198        }
13199        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13200        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13201        IActivityManager am = ActivityManager.getService();
13202        if (am != null) {
13203            int dcsUid = -1;
13204            synchronized (mPackages) {
13205                if (!mDefaultContainerWhitelisted) {
13206                    mDefaultContainerWhitelisted = true;
13207                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13208                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13209                }
13210            }
13211            try {
13212                if (dcsUid > 0) {
13213                    am.backgroundWhitelistUid(dcsUid);
13214                }
13215                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13216                        UserHandle.USER_SYSTEM);
13217            } catch (RemoteException e) {
13218            }
13219        }
13220    }
13221
13222    @Override
13223    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13224            int installFlags, String installerPackageName, int userId) {
13225        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13226
13227        final int callingUid = Binder.getCallingUid();
13228        enforceCrossUserPermission(callingUid, userId,
13229                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13230
13231        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13232            try {
13233                if (observer != null) {
13234                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13235                }
13236            } catch (RemoteException re) {
13237            }
13238            return;
13239        }
13240
13241        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13242            installFlags |= PackageManager.INSTALL_FROM_ADB;
13243
13244        } else {
13245            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13246            // about installerPackageName.
13247
13248            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13249            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13250        }
13251
13252        UserHandle user;
13253        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13254            user = UserHandle.ALL;
13255        } else {
13256            user = new UserHandle(userId);
13257        }
13258
13259        // Only system components can circumvent runtime permissions when installing.
13260        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13261                && mContext.checkCallingOrSelfPermission(Manifest.permission
13262                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13263            throw new SecurityException("You need the "
13264                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13265                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13266        }
13267
13268        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13269                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13270            throw new IllegalArgumentException(
13271                    "New installs into ASEC containers no longer supported");
13272        }
13273
13274        final File originFile = new File(originPath);
13275        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13276
13277        final Message msg = mHandler.obtainMessage(INIT_COPY);
13278        final VerificationInfo verificationInfo = new VerificationInfo(
13279                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13280        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13281                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13282                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13283                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13284        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13285        msg.obj = params;
13286
13287        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13288                System.identityHashCode(msg.obj));
13289        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13290                System.identityHashCode(msg.obj));
13291
13292        mHandler.sendMessage(msg);
13293    }
13294
13295
13296    /**
13297     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13298     * it is acting on behalf on an enterprise or the user).
13299     *
13300     * Note that the ordering of the conditionals in this method is important. The checks we perform
13301     * are as follows, in this order:
13302     *
13303     * 1) If the install is being performed by a system app, we can trust the app to have set the
13304     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13305     *    what it is.
13306     * 2) If the install is being performed by a device or profile owner app, the install reason
13307     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13308     *    set the install reason correctly. If the app targets an older SDK version where install
13309     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13310     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13311     * 3) In all other cases, the install is being performed by a regular app that is neither part
13312     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13313     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13314     *    set to enterprise policy and if so, change it to unknown instead.
13315     */
13316    private int fixUpInstallReason(String installerPackageName, int installerUid,
13317            int installReason) {
13318        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13319                == PERMISSION_GRANTED) {
13320            // If the install is being performed by a system app, we trust that app to have set the
13321            // install reason correctly.
13322            return installReason;
13323        }
13324
13325        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13326            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13327        if (dpm != null) {
13328            ComponentName owner = null;
13329            try {
13330                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13331                if (owner == null) {
13332                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13333                }
13334            } catch (RemoteException e) {
13335            }
13336            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13337                // If the install is being performed by a device or profile owner, the install
13338                // reason should be enterprise policy.
13339                return PackageManager.INSTALL_REASON_POLICY;
13340            }
13341        }
13342
13343        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13344            // If the install is being performed by a regular app (i.e. neither system app nor
13345            // device or profile owner), we have no reason to believe that the app is acting on
13346            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13347            // change it to unknown instead.
13348            return PackageManager.INSTALL_REASON_UNKNOWN;
13349        }
13350
13351        // If the install is being performed by a regular app and the install reason was set to any
13352        // value but enterprise policy, leave the install reason unchanged.
13353        return installReason;
13354    }
13355
13356    void installStage(String packageName, File stagedDir, String stagedCid,
13357            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13358            String installerPackageName, int installerUid, UserHandle user,
13359            Certificate[][] certificates) {
13360        if (DEBUG_EPHEMERAL) {
13361            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13362                Slog.d(TAG, "Ephemeral install of " + packageName);
13363            }
13364        }
13365        final VerificationInfo verificationInfo = new VerificationInfo(
13366                sessionParams.originatingUri, sessionParams.referrerUri,
13367                sessionParams.originatingUid, installerUid);
13368
13369        final OriginInfo origin;
13370        if (stagedDir != null) {
13371            origin = OriginInfo.fromStagedFile(stagedDir);
13372        } else {
13373            origin = OriginInfo.fromStagedContainer(stagedCid);
13374        }
13375
13376        final Message msg = mHandler.obtainMessage(INIT_COPY);
13377        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13378                sessionParams.installReason);
13379        final InstallParams params = new InstallParams(origin, null, observer,
13380                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13381                verificationInfo, user, sessionParams.abiOverride,
13382                sessionParams.grantedRuntimePermissions, certificates, installReason);
13383        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13384        msg.obj = params;
13385
13386        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13387                System.identityHashCode(msg.obj));
13388        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13389                System.identityHashCode(msg.obj));
13390
13391        mHandler.sendMessage(msg);
13392    }
13393
13394    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13395            int userId) {
13396        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13397        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13398    }
13399
13400    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
13401        if (ArrayUtils.isEmpty(userIds)) {
13402            return;
13403        }
13404        Bundle extras = new Bundle(1);
13405        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13406        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13407
13408        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13409                packageName, extras, 0, null, null, userIds);
13410        if (isSystem) {
13411            mHandler.post(() -> {
13412                        for (int userId : userIds) {
13413                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13414                        }
13415                    }
13416            );
13417        }
13418    }
13419
13420    /**
13421     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13422     * automatically without needing an explicit launch.
13423     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13424     */
13425    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13426        // If user is not running, the app didn't miss any broadcast
13427        if (!mUserManagerInternal.isUserRunning(userId)) {
13428            return;
13429        }
13430        final IActivityManager am = ActivityManager.getService();
13431        try {
13432            // Deliver LOCKED_BOOT_COMPLETED first
13433            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13434                    .setPackage(packageName);
13435            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13436            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13437                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13438
13439            // Deliver BOOT_COMPLETED only if user is unlocked
13440            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13441                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13442                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13443                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13444            }
13445        } catch (RemoteException e) {
13446            throw e.rethrowFromSystemServer();
13447        }
13448    }
13449
13450    @Override
13451    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13452            int userId) {
13453        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13454        PackageSetting pkgSetting;
13455        final int uid = Binder.getCallingUid();
13456        enforceCrossUserPermission(uid, userId,
13457                true /* requireFullPermission */, true /* checkShell */,
13458                "setApplicationHiddenSetting for user " + userId);
13459
13460        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13461            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13462            return false;
13463        }
13464
13465        long callingId = Binder.clearCallingIdentity();
13466        try {
13467            boolean sendAdded = false;
13468            boolean sendRemoved = false;
13469            // writer
13470            synchronized (mPackages) {
13471                pkgSetting = mSettings.mPackages.get(packageName);
13472                if (pkgSetting == null) {
13473                    return false;
13474                }
13475                // Do not allow "android" is being disabled
13476                if ("android".equals(packageName)) {
13477                    Slog.w(TAG, "Cannot hide package: android");
13478                    return false;
13479                }
13480                // Cannot hide static shared libs as they are considered
13481                // a part of the using app (emulating static linking). Also
13482                // static libs are installed always on internal storage.
13483                PackageParser.Package pkg = mPackages.get(packageName);
13484                if (pkg != null && pkg.staticSharedLibName != null) {
13485                    Slog.w(TAG, "Cannot hide package: " + packageName
13486                            + " providing static shared library: "
13487                            + pkg.staticSharedLibName);
13488                    return false;
13489                }
13490                // Only allow protected packages to hide themselves.
13491                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13492                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13493                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13494                    return false;
13495                }
13496
13497                if (pkgSetting.getHidden(userId) != hidden) {
13498                    pkgSetting.setHidden(hidden, userId);
13499                    mSettings.writePackageRestrictionsLPr(userId);
13500                    if (hidden) {
13501                        sendRemoved = true;
13502                    } else {
13503                        sendAdded = true;
13504                    }
13505                }
13506            }
13507            if (sendAdded) {
13508                sendPackageAddedForUser(packageName, pkgSetting, userId);
13509                return true;
13510            }
13511            if (sendRemoved) {
13512                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13513                        "hiding pkg");
13514                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13515                return true;
13516            }
13517        } finally {
13518            Binder.restoreCallingIdentity(callingId);
13519        }
13520        return false;
13521    }
13522
13523    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13524            int userId) {
13525        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13526        info.removedPackage = packageName;
13527        info.installerPackageName = pkgSetting.installerPackageName;
13528        info.removedUsers = new int[] {userId};
13529        info.broadcastUsers = new int[] {userId};
13530        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13531        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13532    }
13533
13534    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13535        if (pkgList.length > 0) {
13536            Bundle extras = new Bundle(1);
13537            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13538
13539            sendPackageBroadcast(
13540                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13541                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13542                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13543                    new int[] {userId});
13544        }
13545    }
13546
13547    /**
13548     * Returns true if application is not found or there was an error. Otherwise it returns
13549     * the hidden state of the package for the given user.
13550     */
13551    @Override
13552    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13553        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13554        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13555                true /* requireFullPermission */, false /* checkShell */,
13556                "getApplicationHidden for user " + userId);
13557        PackageSetting pkgSetting;
13558        long callingId = Binder.clearCallingIdentity();
13559        try {
13560            // writer
13561            synchronized (mPackages) {
13562                pkgSetting = mSettings.mPackages.get(packageName);
13563                if (pkgSetting == null) {
13564                    return true;
13565                }
13566                return pkgSetting.getHidden(userId);
13567            }
13568        } finally {
13569            Binder.restoreCallingIdentity(callingId);
13570        }
13571    }
13572
13573    /**
13574     * @hide
13575     */
13576    @Override
13577    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13578            int installReason) {
13579        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13580                null);
13581        PackageSetting pkgSetting;
13582        final int uid = Binder.getCallingUid();
13583        enforceCrossUserPermission(uid, userId,
13584                true /* requireFullPermission */, true /* checkShell */,
13585                "installExistingPackage for user " + userId);
13586        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13587            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13588        }
13589
13590        long callingId = Binder.clearCallingIdentity();
13591        try {
13592            boolean installed = false;
13593            final boolean instantApp =
13594                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13595            final boolean fullApp =
13596                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13597
13598            // writer
13599            synchronized (mPackages) {
13600                pkgSetting = mSettings.mPackages.get(packageName);
13601                if (pkgSetting == null) {
13602                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13603                }
13604                if (!pkgSetting.getInstalled(userId)) {
13605                    pkgSetting.setInstalled(true, userId);
13606                    pkgSetting.setHidden(false, userId);
13607                    pkgSetting.setInstallReason(installReason, userId);
13608                    mSettings.writePackageRestrictionsLPr(userId);
13609                    mSettings.writeKernelMappingLPr(pkgSetting);
13610                    installed = true;
13611                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13612                    // upgrade app from instant to full; we don't allow app downgrade
13613                    installed = true;
13614                }
13615                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13616            }
13617
13618            if (installed) {
13619                if (pkgSetting.pkg != null) {
13620                    synchronized (mInstallLock) {
13621                        // We don't need to freeze for a brand new install
13622                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13623                    }
13624                }
13625                sendPackageAddedForUser(packageName, pkgSetting, userId);
13626                synchronized (mPackages) {
13627                    updateSequenceNumberLP(packageName, new int[]{ userId });
13628                }
13629            }
13630        } finally {
13631            Binder.restoreCallingIdentity(callingId);
13632        }
13633
13634        return PackageManager.INSTALL_SUCCEEDED;
13635    }
13636
13637    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13638            boolean instantApp, boolean fullApp) {
13639        // no state specified; do nothing
13640        if (!instantApp && !fullApp) {
13641            return;
13642        }
13643        if (userId != UserHandle.USER_ALL) {
13644            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13645                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13646            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13647                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13648            }
13649        } else {
13650            for (int currentUserId : sUserManager.getUserIds()) {
13651                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13652                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13653                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13654                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13655                }
13656            }
13657        }
13658    }
13659
13660    boolean isUserRestricted(int userId, String restrictionKey) {
13661        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13662        if (restrictions.getBoolean(restrictionKey, false)) {
13663            Log.w(TAG, "User is restricted: " + restrictionKey);
13664            return true;
13665        }
13666        return false;
13667    }
13668
13669    @Override
13670    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13671            int userId) {
13672        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13673        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13674                true /* requireFullPermission */, true /* checkShell */,
13675                "setPackagesSuspended for user " + userId);
13676
13677        if (ArrayUtils.isEmpty(packageNames)) {
13678            return packageNames;
13679        }
13680
13681        // List of package names for whom the suspended state has changed.
13682        List<String> changedPackages = new ArrayList<>(packageNames.length);
13683        // List of package names for whom the suspended state is not set as requested in this
13684        // method.
13685        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13686        long callingId = Binder.clearCallingIdentity();
13687        try {
13688            for (int i = 0; i < packageNames.length; i++) {
13689                String packageName = packageNames[i];
13690                boolean changed = false;
13691                final int appId;
13692                synchronized (mPackages) {
13693                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13694                    if (pkgSetting == null) {
13695                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13696                                + "\". Skipping suspending/un-suspending.");
13697                        unactionedPackages.add(packageName);
13698                        continue;
13699                    }
13700                    appId = pkgSetting.appId;
13701                    if (pkgSetting.getSuspended(userId) != suspended) {
13702                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13703                            unactionedPackages.add(packageName);
13704                            continue;
13705                        }
13706                        pkgSetting.setSuspended(suspended, userId);
13707                        mSettings.writePackageRestrictionsLPr(userId);
13708                        changed = true;
13709                        changedPackages.add(packageName);
13710                    }
13711                }
13712
13713                if (changed && suspended) {
13714                    killApplication(packageName, UserHandle.getUid(userId, appId),
13715                            "suspending package");
13716                }
13717            }
13718        } finally {
13719            Binder.restoreCallingIdentity(callingId);
13720        }
13721
13722        if (!changedPackages.isEmpty()) {
13723            sendPackagesSuspendedForUser(changedPackages.toArray(
13724                    new String[changedPackages.size()]), userId, suspended);
13725        }
13726
13727        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13728    }
13729
13730    @Override
13731    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13732        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13733                true /* requireFullPermission */, false /* checkShell */,
13734                "isPackageSuspendedForUser for user " + userId);
13735        synchronized (mPackages) {
13736            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13737            if (pkgSetting == null) {
13738                throw new IllegalArgumentException("Unknown target package: " + packageName);
13739            }
13740            return pkgSetting.getSuspended(userId);
13741        }
13742    }
13743
13744    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13745        if (isPackageDeviceAdmin(packageName, userId)) {
13746            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13747                    + "\": has an active device admin");
13748            return false;
13749        }
13750
13751        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13752        if (packageName.equals(activeLauncherPackageName)) {
13753            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13754                    + "\": contains the active launcher");
13755            return false;
13756        }
13757
13758        if (packageName.equals(mRequiredInstallerPackage)) {
13759            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13760                    + "\": required for package installation");
13761            return false;
13762        }
13763
13764        if (packageName.equals(mRequiredUninstallerPackage)) {
13765            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13766                    + "\": required for package uninstallation");
13767            return false;
13768        }
13769
13770        if (packageName.equals(mRequiredVerifierPackage)) {
13771            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13772                    + "\": required for package verification");
13773            return false;
13774        }
13775
13776        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13777            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13778                    + "\": is the default dialer");
13779            return false;
13780        }
13781
13782        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13783            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13784                    + "\": protected package");
13785            return false;
13786        }
13787
13788        // Cannot suspend static shared libs as they are considered
13789        // a part of the using app (emulating static linking). Also
13790        // static libs are installed always on internal storage.
13791        PackageParser.Package pkg = mPackages.get(packageName);
13792        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13793            Slog.w(TAG, "Cannot suspend package: " + packageName
13794                    + " providing static shared library: "
13795                    + pkg.staticSharedLibName);
13796            return false;
13797        }
13798
13799        return true;
13800    }
13801
13802    private String getActiveLauncherPackageName(int userId) {
13803        Intent intent = new Intent(Intent.ACTION_MAIN);
13804        intent.addCategory(Intent.CATEGORY_HOME);
13805        ResolveInfo resolveInfo = resolveIntent(
13806                intent,
13807                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13808                PackageManager.MATCH_DEFAULT_ONLY,
13809                userId);
13810
13811        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13812    }
13813
13814    private String getDefaultDialerPackageName(int userId) {
13815        synchronized (mPackages) {
13816            return mSettings.getDefaultDialerPackageNameLPw(userId);
13817        }
13818    }
13819
13820    @Override
13821    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13822        mContext.enforceCallingOrSelfPermission(
13823                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13824                "Only package verification agents can verify applications");
13825
13826        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13827        final PackageVerificationResponse response = new PackageVerificationResponse(
13828                verificationCode, Binder.getCallingUid());
13829        msg.arg1 = id;
13830        msg.obj = response;
13831        mHandler.sendMessage(msg);
13832    }
13833
13834    @Override
13835    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13836            long millisecondsToDelay) {
13837        mContext.enforceCallingOrSelfPermission(
13838                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13839                "Only package verification agents can extend verification timeouts");
13840
13841        final PackageVerificationState state = mPendingVerification.get(id);
13842        final PackageVerificationResponse response = new PackageVerificationResponse(
13843                verificationCodeAtTimeout, Binder.getCallingUid());
13844
13845        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13846            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13847        }
13848        if (millisecondsToDelay < 0) {
13849            millisecondsToDelay = 0;
13850        }
13851        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13852                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13853            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13854        }
13855
13856        if ((state != null) && !state.timeoutExtended()) {
13857            state.extendTimeout();
13858
13859            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13860            msg.arg1 = id;
13861            msg.obj = response;
13862            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13863        }
13864    }
13865
13866    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13867            int verificationCode, UserHandle user) {
13868        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13869        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13870        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13871        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13872        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13873
13874        mContext.sendBroadcastAsUser(intent, user,
13875                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13876    }
13877
13878    private ComponentName matchComponentForVerifier(String packageName,
13879            List<ResolveInfo> receivers) {
13880        ActivityInfo targetReceiver = null;
13881
13882        final int NR = receivers.size();
13883        for (int i = 0; i < NR; i++) {
13884            final ResolveInfo info = receivers.get(i);
13885            if (info.activityInfo == null) {
13886                continue;
13887            }
13888
13889            if (packageName.equals(info.activityInfo.packageName)) {
13890                targetReceiver = info.activityInfo;
13891                break;
13892            }
13893        }
13894
13895        if (targetReceiver == null) {
13896            return null;
13897        }
13898
13899        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13900    }
13901
13902    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13903            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13904        if (pkgInfo.verifiers.length == 0) {
13905            return null;
13906        }
13907
13908        final int N = pkgInfo.verifiers.length;
13909        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13910        for (int i = 0; i < N; i++) {
13911            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13912
13913            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13914                    receivers);
13915            if (comp == null) {
13916                continue;
13917            }
13918
13919            final int verifierUid = getUidForVerifier(verifierInfo);
13920            if (verifierUid == -1) {
13921                continue;
13922            }
13923
13924            if (DEBUG_VERIFY) {
13925                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13926                        + " with the correct signature");
13927            }
13928            sufficientVerifiers.add(comp);
13929            verificationState.addSufficientVerifier(verifierUid);
13930        }
13931
13932        return sufficientVerifiers;
13933    }
13934
13935    private int getUidForVerifier(VerifierInfo verifierInfo) {
13936        synchronized (mPackages) {
13937            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13938            if (pkg == null) {
13939                return -1;
13940            } else if (pkg.mSignatures.length != 1) {
13941                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13942                        + " has more than one signature; ignoring");
13943                return -1;
13944            }
13945
13946            /*
13947             * If the public key of the package's signature does not match
13948             * our expected public key, then this is a different package and
13949             * we should skip.
13950             */
13951
13952            final byte[] expectedPublicKey;
13953            try {
13954                final Signature verifierSig = pkg.mSignatures[0];
13955                final PublicKey publicKey = verifierSig.getPublicKey();
13956                expectedPublicKey = publicKey.getEncoded();
13957            } catch (CertificateException e) {
13958                return -1;
13959            }
13960
13961            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13962
13963            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13964                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13965                        + " does not have the expected public key; ignoring");
13966                return -1;
13967            }
13968
13969            return pkg.applicationInfo.uid;
13970        }
13971    }
13972
13973    @Override
13974    public void finishPackageInstall(int token, boolean didLaunch) {
13975        enforceSystemOrRoot("Only the system is allowed to finish installs");
13976
13977        if (DEBUG_INSTALL) {
13978            Slog.v(TAG, "BM finishing package install for " + token);
13979        }
13980        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13981
13982        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13983        mHandler.sendMessage(msg);
13984    }
13985
13986    /**
13987     * Get the verification agent timeout.  Used for both the APK verifier and the
13988     * intent filter verifier.
13989     *
13990     * @return verification timeout in milliseconds
13991     */
13992    private long getVerificationTimeout() {
13993        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13994                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13995                DEFAULT_VERIFICATION_TIMEOUT);
13996    }
13997
13998    /**
13999     * Get the default verification agent response code.
14000     *
14001     * @return default verification response code
14002     */
14003    private int getDefaultVerificationResponse() {
14004        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14005                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14006                DEFAULT_VERIFICATION_RESPONSE);
14007    }
14008
14009    /**
14010     * Check whether or not package verification has been enabled.
14011     *
14012     * @return true if verification should be performed
14013     */
14014    private boolean isVerificationEnabled(int userId, int installFlags) {
14015        if (!DEFAULT_VERIFY_ENABLE) {
14016            return false;
14017        }
14018
14019        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14020
14021        // Check if installing from ADB
14022        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14023            // Do not run verification in a test harness environment
14024            if (ActivityManager.isRunningInTestHarness()) {
14025                return false;
14026            }
14027            if (ensureVerifyAppsEnabled) {
14028                return true;
14029            }
14030            // Check if the developer does not want package verification for ADB installs
14031            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14032                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14033                return false;
14034            }
14035        }
14036
14037        if (ensureVerifyAppsEnabled) {
14038            return true;
14039        }
14040
14041        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14042                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14043    }
14044
14045    @Override
14046    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14047            throws RemoteException {
14048        mContext.enforceCallingOrSelfPermission(
14049                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14050                "Only intentfilter verification agents can verify applications");
14051
14052        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14053        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14054                Binder.getCallingUid(), verificationCode, failedDomains);
14055        msg.arg1 = id;
14056        msg.obj = response;
14057        mHandler.sendMessage(msg);
14058    }
14059
14060    @Override
14061    public int getIntentVerificationStatus(String packageName, int userId) {
14062        synchronized (mPackages) {
14063            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14064        }
14065    }
14066
14067    @Override
14068    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14069        mContext.enforceCallingOrSelfPermission(
14070                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14071
14072        boolean result = false;
14073        synchronized (mPackages) {
14074            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14075        }
14076        if (result) {
14077            scheduleWritePackageRestrictionsLocked(userId);
14078        }
14079        return result;
14080    }
14081
14082    @Override
14083    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14084            String packageName) {
14085        synchronized (mPackages) {
14086            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14087        }
14088    }
14089
14090    @Override
14091    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14092        if (TextUtils.isEmpty(packageName)) {
14093            return ParceledListSlice.emptyList();
14094        }
14095        synchronized (mPackages) {
14096            PackageParser.Package pkg = mPackages.get(packageName);
14097            if (pkg == null || pkg.activities == null) {
14098                return ParceledListSlice.emptyList();
14099            }
14100            final int count = pkg.activities.size();
14101            ArrayList<IntentFilter> result = new ArrayList<>();
14102            for (int n=0; n<count; n++) {
14103                PackageParser.Activity activity = pkg.activities.get(n);
14104                if (activity.intents != null && activity.intents.size() > 0) {
14105                    result.addAll(activity.intents);
14106                }
14107            }
14108            return new ParceledListSlice<>(result);
14109        }
14110    }
14111
14112    @Override
14113    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14114        mContext.enforceCallingOrSelfPermission(
14115                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14116
14117        synchronized (mPackages) {
14118            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14119            if (packageName != null) {
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 PackageSetting ps;
16057        final String pkgName = pkg.packageName;
16058        final int[] allUsers;
16059        final int[] installedUsers;
16060
16061        synchronized(mPackages) {
16062            oldPackage = mPackages.get(pkgName);
16063            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16064
16065            // don't allow upgrade to target a release SDK from a pre-release SDK
16066            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16067                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16068            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16069                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16070            if (oldTargetsPreRelease
16071                    && !newTargetsPreRelease
16072                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16073                Slog.w(TAG, "Can't install package targeting released sdk");
16074                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16075                return;
16076            }
16077
16078            ps = mSettings.mPackages.get(pkgName);
16079
16080            // verify signatures are valid
16081            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16082                if (!checkUpgradeKeySetLP(ps, pkg)) {
16083                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16084                            "New package not signed by keys specified by upgrade-keysets: "
16085                                    + pkgName);
16086                    return;
16087                }
16088            } else {
16089                // default to original signature matching
16090                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16091                        != PackageManager.SIGNATURE_MATCH) {
16092                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16093                            "New package has a different signature: " + pkgName);
16094                    return;
16095                }
16096            }
16097
16098            // don't allow a system upgrade unless the upgrade hash matches
16099            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16100                byte[] digestBytes = null;
16101                try {
16102                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16103                    updateDigest(digest, new File(pkg.baseCodePath));
16104                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16105                        for (String path : pkg.splitCodePaths) {
16106                            updateDigest(digest, new File(path));
16107                        }
16108                    }
16109                    digestBytes = digest.digest();
16110                } catch (NoSuchAlgorithmException | IOException e) {
16111                    res.setError(INSTALL_FAILED_INVALID_APK,
16112                            "Could not compute hash: " + pkgName);
16113                    return;
16114                }
16115                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16116                    res.setError(INSTALL_FAILED_INVALID_APK,
16117                            "New package fails restrict-update check: " + pkgName);
16118                    return;
16119                }
16120                // retain upgrade restriction
16121                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16122            }
16123
16124            // Check for shared user id changes
16125            String invalidPackageName =
16126                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16127            if (invalidPackageName != null) {
16128                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16129                        "Package " + invalidPackageName + " tried to change user "
16130                                + oldPackage.mSharedUserId);
16131                return;
16132            }
16133
16134            // In case of rollback, remember per-user/profile install state
16135            allUsers = sUserManager.getUserIds();
16136            installedUsers = ps.queryInstalledUsers(allUsers, true);
16137
16138            // don't allow an upgrade from full to ephemeral
16139            if (isInstantApp) {
16140                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16141                    for (int currentUser : allUsers) {
16142                        if (!ps.getInstantApp(currentUser)) {
16143                            // can't downgrade from full to instant
16144                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16145                                    + " for user: " + currentUser);
16146                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16147                            return;
16148                        }
16149                    }
16150                } else if (!ps.getInstantApp(user.getIdentifier())) {
16151                    // can't downgrade from full to instant
16152                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16153                            + " for user: " + user.getIdentifier());
16154                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16155                    return;
16156                }
16157            }
16158        }
16159
16160        // Update what is removed
16161        res.removedInfo = new PackageRemovedInfo(this);
16162        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16163        res.removedInfo.removedPackage = oldPackage.packageName;
16164        res.removedInfo.installerPackageName = ps.installerPackageName;
16165        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16166        res.removedInfo.isUpdate = true;
16167        res.removedInfo.origUsers = installedUsers;
16168        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16169        for (int i = 0; i < installedUsers.length; i++) {
16170            final int userId = installedUsers[i];
16171            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16172        }
16173
16174        final int childCount = (oldPackage.childPackages != null)
16175                ? oldPackage.childPackages.size() : 0;
16176        for (int i = 0; i < childCount; i++) {
16177            boolean childPackageUpdated = false;
16178            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16179            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16180            if (res.addedChildPackages != null) {
16181                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16182                if (childRes != null) {
16183                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16184                    childRes.removedInfo.removedPackage = childPkg.packageName;
16185                    if (childPs != null) {
16186                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16187                    }
16188                    childRes.removedInfo.isUpdate = true;
16189                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16190                    childPackageUpdated = true;
16191                }
16192            }
16193            if (!childPackageUpdated) {
16194                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16195                childRemovedRes.removedPackage = childPkg.packageName;
16196                if (childPs != null) {
16197                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16198                }
16199                childRemovedRes.isUpdate = false;
16200                childRemovedRes.dataRemoved = true;
16201                synchronized (mPackages) {
16202                    if (childPs != null) {
16203                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16204                    }
16205                }
16206                if (res.removedInfo.removedChildPackages == null) {
16207                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16208                }
16209                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16210            }
16211        }
16212
16213        boolean sysPkg = (isSystemApp(oldPackage));
16214        if (sysPkg) {
16215            // Set the system/privileged flags as needed
16216            final boolean privileged =
16217                    (oldPackage.applicationInfo.privateFlags
16218                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16219            final int systemPolicyFlags = policyFlags
16220                    | PackageParser.PARSE_IS_SYSTEM
16221                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16222
16223            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16224                    user, allUsers, installerPackageName, res, installReason);
16225        } else {
16226            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16227                    user, allUsers, installerPackageName, res, installReason);
16228        }
16229    }
16230
16231    public List<String> getPreviousCodePaths(String packageName) {
16232        final PackageSetting ps = mSettings.mPackages.get(packageName);
16233        final List<String> result = new ArrayList<String>();
16234        if (ps != null && ps.oldCodePaths != null) {
16235            result.addAll(ps.oldCodePaths);
16236        }
16237        return result;
16238    }
16239
16240    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16241            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16242            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16243            int installReason) {
16244        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16245                + deletedPackage);
16246
16247        String pkgName = deletedPackage.packageName;
16248        boolean deletedPkg = true;
16249        boolean addedPkg = false;
16250        boolean updatedSettings = false;
16251        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16252        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16253                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16254
16255        final long origUpdateTime = (pkg.mExtras != null)
16256                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16257
16258        // First delete the existing package while retaining the data directory
16259        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16260                res.removedInfo, true, pkg)) {
16261            // If the existing package wasn't successfully deleted
16262            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16263            deletedPkg = false;
16264        } else {
16265            // Successfully deleted the old package; proceed with replace.
16266
16267            // If deleted package lived in a container, give users a chance to
16268            // relinquish resources before killing.
16269            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16270                if (DEBUG_INSTALL) {
16271                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16272                }
16273                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16274                final ArrayList<String> pkgList = new ArrayList<String>(1);
16275                pkgList.add(deletedPackage.applicationInfo.packageName);
16276                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16277            }
16278
16279            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16280                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16281            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16282
16283            try {
16284                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16285                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16286                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16287                        installReason);
16288
16289                // Update the in-memory copy of the previous code paths.
16290                PackageSetting ps = mSettings.mPackages.get(pkgName);
16291                if (!killApp) {
16292                    if (ps.oldCodePaths == null) {
16293                        ps.oldCodePaths = new ArraySet<>();
16294                    }
16295                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16296                    if (deletedPackage.splitCodePaths != null) {
16297                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16298                    }
16299                } else {
16300                    ps.oldCodePaths = null;
16301                }
16302                if (ps.childPackageNames != null) {
16303                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16304                        final String childPkgName = ps.childPackageNames.get(i);
16305                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16306                        childPs.oldCodePaths = ps.oldCodePaths;
16307                    }
16308                }
16309                // set instant app status, but, only if it's explicitly specified
16310                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16311                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16312                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16313                prepareAppDataAfterInstallLIF(newPackage);
16314                addedPkg = true;
16315                mDexManager.notifyPackageUpdated(newPackage.packageName,
16316                        newPackage.baseCodePath, newPackage.splitCodePaths);
16317            } catch (PackageManagerException e) {
16318                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16319            }
16320        }
16321
16322        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16323            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16324
16325            // Revert all internal state mutations and added folders for the failed install
16326            if (addedPkg) {
16327                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16328                        res.removedInfo, true, null);
16329            }
16330
16331            // Restore the old package
16332            if (deletedPkg) {
16333                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16334                File restoreFile = new File(deletedPackage.codePath);
16335                // Parse old package
16336                boolean oldExternal = isExternal(deletedPackage);
16337                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16338                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16339                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16340                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16341                try {
16342                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16343                            null);
16344                } catch (PackageManagerException e) {
16345                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16346                            + e.getMessage());
16347                    return;
16348                }
16349
16350                synchronized (mPackages) {
16351                    // Ensure the installer package name up to date
16352                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16353
16354                    // Update permissions for restored package
16355                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16356
16357                    mSettings.writeLPr();
16358                }
16359
16360                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16361            }
16362        } else {
16363            synchronized (mPackages) {
16364                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16365                if (ps != null) {
16366                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16367                    if (res.removedInfo.removedChildPackages != null) {
16368                        final int childCount = res.removedInfo.removedChildPackages.size();
16369                        // Iterate in reverse as we may modify the collection
16370                        for (int i = childCount - 1; i >= 0; i--) {
16371                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16372                            if (res.addedChildPackages.containsKey(childPackageName)) {
16373                                res.removedInfo.removedChildPackages.removeAt(i);
16374                            } else {
16375                                PackageRemovedInfo childInfo = res.removedInfo
16376                                        .removedChildPackages.valueAt(i);
16377                                childInfo.removedForAllUsers = mPackages.get(
16378                                        childInfo.removedPackage) == null;
16379                            }
16380                        }
16381                    }
16382                }
16383            }
16384        }
16385    }
16386
16387    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16388            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16389            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16390            int installReason) {
16391        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16392                + ", old=" + deletedPackage);
16393
16394        final boolean disabledSystem;
16395
16396        // Remove existing system package
16397        removePackageLI(deletedPackage, true);
16398
16399        synchronized (mPackages) {
16400            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16401        }
16402        if (!disabledSystem) {
16403            // We didn't need to disable the .apk as a current system package,
16404            // which means we are replacing another update that is already
16405            // installed.  We need to make sure to delete the older one's .apk.
16406            res.removedInfo.args = createInstallArgsForExisting(0,
16407                    deletedPackage.applicationInfo.getCodePath(),
16408                    deletedPackage.applicationInfo.getResourcePath(),
16409                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16410        } else {
16411            res.removedInfo.args = null;
16412        }
16413
16414        // Successfully disabled the old package. Now proceed with re-installation
16415        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16416                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16417        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16418
16419        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16420        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16421                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16422
16423        PackageParser.Package newPackage = null;
16424        try {
16425            // Add the package to the internal data structures
16426            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16427
16428            // Set the update and install times
16429            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16430            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16431                    System.currentTimeMillis());
16432
16433            // Update the package dynamic state if succeeded
16434            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16435                // Now that the install succeeded make sure we remove data
16436                // directories for any child package the update removed.
16437                final int deletedChildCount = (deletedPackage.childPackages != null)
16438                        ? deletedPackage.childPackages.size() : 0;
16439                final int newChildCount = (newPackage.childPackages != null)
16440                        ? newPackage.childPackages.size() : 0;
16441                for (int i = 0; i < deletedChildCount; i++) {
16442                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16443                    boolean childPackageDeleted = true;
16444                    for (int j = 0; j < newChildCount; j++) {
16445                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16446                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16447                            childPackageDeleted = false;
16448                            break;
16449                        }
16450                    }
16451                    if (childPackageDeleted) {
16452                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16453                                deletedChildPkg.packageName);
16454                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16455                            PackageRemovedInfo removedChildRes = res.removedInfo
16456                                    .removedChildPackages.get(deletedChildPkg.packageName);
16457                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16458                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16459                        }
16460                    }
16461                }
16462
16463                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16464                        installReason);
16465                prepareAppDataAfterInstallLIF(newPackage);
16466
16467                mDexManager.notifyPackageUpdated(newPackage.packageName,
16468                            newPackage.baseCodePath, newPackage.splitCodePaths);
16469            }
16470        } catch (PackageManagerException e) {
16471            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16472            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16473        }
16474
16475        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16476            // Re installation failed. Restore old information
16477            // Remove new pkg information
16478            if (newPackage != null) {
16479                removeInstalledPackageLI(newPackage, true);
16480            }
16481            // Add back the old system package
16482            try {
16483                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16484            } catch (PackageManagerException e) {
16485                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16486            }
16487
16488            synchronized (mPackages) {
16489                if (disabledSystem) {
16490                    enableSystemPackageLPw(deletedPackage);
16491                }
16492
16493                // Ensure the installer package name up to date
16494                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16495
16496                // Update permissions for restored package
16497                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16498
16499                mSettings.writeLPr();
16500            }
16501
16502            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16503                    + " after failed upgrade");
16504        }
16505    }
16506
16507    /**
16508     * Checks whether the parent or any of the child packages have a change shared
16509     * user. For a package to be a valid update the shred users of the parent and
16510     * the children should match. We may later support changing child shared users.
16511     * @param oldPkg The updated package.
16512     * @param newPkg The update package.
16513     * @return The shared user that change between the versions.
16514     */
16515    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16516            PackageParser.Package newPkg) {
16517        // Check parent shared user
16518        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16519            return newPkg.packageName;
16520        }
16521        // Check child shared users
16522        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16523        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16524        for (int i = 0; i < newChildCount; i++) {
16525            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16526            // If this child was present, did it have the same shared user?
16527            for (int j = 0; j < oldChildCount; j++) {
16528                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16529                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16530                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16531                    return newChildPkg.packageName;
16532                }
16533            }
16534        }
16535        return null;
16536    }
16537
16538    private void removeNativeBinariesLI(PackageSetting ps) {
16539        // Remove the lib path for the parent package
16540        if (ps != null) {
16541            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16542            // Remove the lib path for the child packages
16543            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16544            for (int i = 0; i < childCount; i++) {
16545                PackageSetting childPs = null;
16546                synchronized (mPackages) {
16547                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16548                }
16549                if (childPs != null) {
16550                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16551                            .legacyNativeLibraryPathString);
16552                }
16553            }
16554        }
16555    }
16556
16557    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16558        // Enable the parent package
16559        mSettings.enableSystemPackageLPw(pkg.packageName);
16560        // Enable the child packages
16561        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16562        for (int i = 0; i < childCount; i++) {
16563            PackageParser.Package childPkg = pkg.childPackages.get(i);
16564            mSettings.enableSystemPackageLPw(childPkg.packageName);
16565        }
16566    }
16567
16568    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16569            PackageParser.Package newPkg) {
16570        // Disable the parent package (parent always replaced)
16571        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16572        // Disable the child packages
16573        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16574        for (int i = 0; i < childCount; i++) {
16575            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16576            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16577            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16578        }
16579        return disabled;
16580    }
16581
16582    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16583            String installerPackageName) {
16584        // Enable the parent package
16585        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16586        // Enable the child packages
16587        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16588        for (int i = 0; i < childCount; i++) {
16589            PackageParser.Package childPkg = pkg.childPackages.get(i);
16590            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16591        }
16592    }
16593
16594    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16595        // Collect all used permissions in the UID
16596        ArraySet<String> usedPermissions = new ArraySet<>();
16597        final int packageCount = su.packages.size();
16598        for (int i = 0; i < packageCount; i++) {
16599            PackageSetting ps = su.packages.valueAt(i);
16600            if (ps.pkg == null) {
16601                continue;
16602            }
16603            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16604            for (int j = 0; j < requestedPermCount; j++) {
16605                String permission = ps.pkg.requestedPermissions.get(j);
16606                BasePermission bp = mSettings.mPermissions.get(permission);
16607                if (bp != null) {
16608                    usedPermissions.add(permission);
16609                }
16610            }
16611        }
16612
16613        PermissionsState permissionsState = su.getPermissionsState();
16614        // Prune install permissions
16615        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16616        final int installPermCount = installPermStates.size();
16617        for (int i = installPermCount - 1; i >= 0;  i--) {
16618            PermissionState permissionState = installPermStates.get(i);
16619            if (!usedPermissions.contains(permissionState.getName())) {
16620                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16621                if (bp != null) {
16622                    permissionsState.revokeInstallPermission(bp);
16623                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16624                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16625                }
16626            }
16627        }
16628
16629        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16630
16631        // Prune runtime permissions
16632        for (int userId : allUserIds) {
16633            List<PermissionState> runtimePermStates = permissionsState
16634                    .getRuntimePermissionStates(userId);
16635            final int runtimePermCount = runtimePermStates.size();
16636            for (int i = runtimePermCount - 1; i >= 0; i--) {
16637                PermissionState permissionState = runtimePermStates.get(i);
16638                if (!usedPermissions.contains(permissionState.getName())) {
16639                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16640                    if (bp != null) {
16641                        permissionsState.revokeRuntimePermission(bp, userId);
16642                        permissionsState.updatePermissionFlags(bp, userId,
16643                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16644                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16645                                runtimePermissionChangedUserIds, userId);
16646                    }
16647                }
16648            }
16649        }
16650
16651        return runtimePermissionChangedUserIds;
16652    }
16653
16654    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16655            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16656        // Update the parent package setting
16657        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16658                res, user, installReason);
16659        // Update the child packages setting
16660        final int childCount = (newPackage.childPackages != null)
16661                ? newPackage.childPackages.size() : 0;
16662        for (int i = 0; i < childCount; i++) {
16663            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16664            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16665            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16666                    childRes.origUsers, childRes, user, installReason);
16667        }
16668    }
16669
16670    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16671            String installerPackageName, int[] allUsers, int[] installedForUsers,
16672            PackageInstalledInfo res, UserHandle user, int installReason) {
16673        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16674
16675        String pkgName = newPackage.packageName;
16676        synchronized (mPackages) {
16677            //write settings. the installStatus will be incomplete at this stage.
16678            //note that the new package setting would have already been
16679            //added to mPackages. It hasn't been persisted yet.
16680            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16681            // TODO: Remove this write? It's also written at the end of this method
16682            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16683            mSettings.writeLPr();
16684            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16685        }
16686
16687        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16688        synchronized (mPackages) {
16689            updatePermissionsLPw(newPackage.packageName, newPackage,
16690                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16691                            ? UPDATE_PERMISSIONS_ALL : 0));
16692            // For system-bundled packages, we assume that installing an upgraded version
16693            // of the package implies that the user actually wants to run that new code,
16694            // so we enable the package.
16695            PackageSetting ps = mSettings.mPackages.get(pkgName);
16696            final int userId = user.getIdentifier();
16697            if (ps != null) {
16698                if (isSystemApp(newPackage)) {
16699                    if (DEBUG_INSTALL) {
16700                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16701                    }
16702                    // Enable system package for requested users
16703                    if (res.origUsers != null) {
16704                        for (int origUserId : res.origUsers) {
16705                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16706                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16707                                        origUserId, installerPackageName);
16708                            }
16709                        }
16710                    }
16711                    // Also convey the prior install/uninstall state
16712                    if (allUsers != null && installedForUsers != null) {
16713                        for (int currentUserId : allUsers) {
16714                            final boolean installed = ArrayUtils.contains(
16715                                    installedForUsers, currentUserId);
16716                            if (DEBUG_INSTALL) {
16717                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16718                            }
16719                            ps.setInstalled(installed, currentUserId);
16720                        }
16721                        // these install state changes will be persisted in the
16722                        // upcoming call to mSettings.writeLPr().
16723                    }
16724                }
16725                // It's implied that when a user requests installation, they want the app to be
16726                // installed and enabled.
16727                if (userId != UserHandle.USER_ALL) {
16728                    ps.setInstalled(true, userId);
16729                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16730                }
16731
16732                // When replacing an existing package, preserve the original install reason for all
16733                // users that had the package installed before.
16734                final Set<Integer> previousUserIds = new ArraySet<>();
16735                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16736                    final int installReasonCount = res.removedInfo.installReasons.size();
16737                    for (int i = 0; i < installReasonCount; i++) {
16738                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16739                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16740                        ps.setInstallReason(previousInstallReason, previousUserId);
16741                        previousUserIds.add(previousUserId);
16742                    }
16743                }
16744
16745                // Set install reason for users that are having the package newly installed.
16746                if (userId == UserHandle.USER_ALL) {
16747                    for (int currentUserId : sUserManager.getUserIds()) {
16748                        if (!previousUserIds.contains(currentUserId)) {
16749                            ps.setInstallReason(installReason, currentUserId);
16750                        }
16751                    }
16752                } else if (!previousUserIds.contains(userId)) {
16753                    ps.setInstallReason(installReason, userId);
16754                }
16755                mSettings.writeKernelMappingLPr(ps);
16756            }
16757            res.name = pkgName;
16758            res.uid = newPackage.applicationInfo.uid;
16759            res.pkg = newPackage;
16760            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16761            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16762            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16763            //to update install status
16764            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16765            mSettings.writeLPr();
16766            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16767        }
16768
16769        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16770    }
16771
16772    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16773        try {
16774            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16775            installPackageLI(args, res);
16776        } finally {
16777            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16778        }
16779    }
16780
16781    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16782        final int installFlags = args.installFlags;
16783        final String installerPackageName = args.installerPackageName;
16784        final String volumeUuid = args.volumeUuid;
16785        final File tmpPackageFile = new File(args.getCodePath());
16786        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16787        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16788                || (args.volumeUuid != null));
16789        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16790        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16791        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16792        boolean replace = false;
16793        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16794        if (args.move != null) {
16795            // moving a complete application; perform an initial scan on the new install location
16796            scanFlags |= SCAN_INITIAL;
16797        }
16798        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16799            scanFlags |= SCAN_DONT_KILL_APP;
16800        }
16801        if (instantApp) {
16802            scanFlags |= SCAN_AS_INSTANT_APP;
16803        }
16804        if (fullApp) {
16805            scanFlags |= SCAN_AS_FULL_APP;
16806        }
16807
16808        // Result object to be returned
16809        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16810
16811        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16812
16813        // Sanity check
16814        if (instantApp && (forwardLocked || onExternal)) {
16815            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16816                    + " external=" + onExternal);
16817            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16818            return;
16819        }
16820
16821        // Retrieve PackageSettings and parse package
16822        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16823                | PackageParser.PARSE_ENFORCE_CODE
16824                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16825                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16826                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16827                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16828        PackageParser pp = new PackageParser();
16829        pp.setSeparateProcesses(mSeparateProcesses);
16830        pp.setDisplayMetrics(mMetrics);
16831        pp.setCallback(mPackageParserCallback);
16832
16833        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16834        final PackageParser.Package pkg;
16835        try {
16836            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16837        } catch (PackageParserException e) {
16838            res.setError("Failed parse during installPackageLI", e);
16839            return;
16840        } finally {
16841            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16842        }
16843
16844        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16845        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16846            Slog.w(TAG, "Instant app package " + pkg.packageName
16847                    + " does not target O, this will be a fatal error.");
16848            // STOPSHIP: Make this a fatal error
16849            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16850        }
16851        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16852            Slog.w(TAG, "Instant app package " + pkg.packageName
16853                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16854            // STOPSHIP: Make this a fatal error
16855            pkg.applicationInfo.targetSandboxVersion = 2;
16856        }
16857
16858        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16859            // Static shared libraries have synthetic package names
16860            renameStaticSharedLibraryPackage(pkg);
16861
16862            // No static shared libs on external storage
16863            if (onExternal) {
16864                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16865                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16866                        "Packages declaring static-shared libs cannot be updated");
16867                return;
16868            }
16869        }
16870
16871        // If we are installing a clustered package add results for the children
16872        if (pkg.childPackages != null) {
16873            synchronized (mPackages) {
16874                final int childCount = pkg.childPackages.size();
16875                for (int i = 0; i < childCount; i++) {
16876                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16877                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16878                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16879                    childRes.pkg = childPkg;
16880                    childRes.name = childPkg.packageName;
16881                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16882                    if (childPs != null) {
16883                        childRes.origUsers = childPs.queryInstalledUsers(
16884                                sUserManager.getUserIds(), true);
16885                    }
16886                    if ((mPackages.containsKey(childPkg.packageName))) {
16887                        childRes.removedInfo = new PackageRemovedInfo(this);
16888                        childRes.removedInfo.removedPackage = childPkg.packageName;
16889                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16890                    }
16891                    if (res.addedChildPackages == null) {
16892                        res.addedChildPackages = new ArrayMap<>();
16893                    }
16894                    res.addedChildPackages.put(childPkg.packageName, childRes);
16895                }
16896            }
16897        }
16898
16899        // If package doesn't declare API override, mark that we have an install
16900        // time CPU ABI override.
16901        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16902            pkg.cpuAbiOverride = args.abiOverride;
16903        }
16904
16905        String pkgName = res.name = pkg.packageName;
16906        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16907            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16908                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16909                return;
16910            }
16911        }
16912
16913        try {
16914            // either use what we've been given or parse directly from the APK
16915            if (args.certificates != null) {
16916                try {
16917                    PackageParser.populateCertificates(pkg, args.certificates);
16918                } catch (PackageParserException e) {
16919                    // there was something wrong with the certificates we were given;
16920                    // try to pull them from the APK
16921                    PackageParser.collectCertificates(pkg, parseFlags);
16922                }
16923            } else {
16924                PackageParser.collectCertificates(pkg, parseFlags);
16925            }
16926        } catch (PackageParserException e) {
16927            res.setError("Failed collect during installPackageLI", e);
16928            return;
16929        }
16930
16931        // Get rid of all references to package scan path via parser.
16932        pp = null;
16933        String oldCodePath = null;
16934        boolean systemApp = false;
16935        synchronized (mPackages) {
16936            // Check if installing already existing package
16937            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16938                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16939                if (pkg.mOriginalPackages != null
16940                        && pkg.mOriginalPackages.contains(oldName)
16941                        && mPackages.containsKey(oldName)) {
16942                    // This package is derived from an original package,
16943                    // and this device has been updating from that original
16944                    // name.  We must continue using the original name, so
16945                    // rename the new package here.
16946                    pkg.setPackageName(oldName);
16947                    pkgName = pkg.packageName;
16948                    replace = true;
16949                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16950                            + oldName + " pkgName=" + pkgName);
16951                } else if (mPackages.containsKey(pkgName)) {
16952                    // This package, under its official name, already exists
16953                    // on the device; we should replace it.
16954                    replace = true;
16955                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16956                }
16957
16958                // Child packages are installed through the parent package
16959                if (pkg.parentPackage != null) {
16960                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16961                            "Package " + pkg.packageName + " is child of package "
16962                                    + pkg.parentPackage.parentPackage + ". Child packages "
16963                                    + "can be updated only through the parent package.");
16964                    return;
16965                }
16966
16967                if (replace) {
16968                    // Prevent apps opting out from runtime permissions
16969                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16970                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16971                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16972                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16973                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16974                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16975                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16976                                        + " doesn't support runtime permissions but the old"
16977                                        + " target SDK " + oldTargetSdk + " does.");
16978                        return;
16979                    }
16980                    // Prevent apps from downgrading their targetSandbox.
16981                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16982                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16983                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16984                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16985                                "Package " + pkg.packageName + " new target sandbox "
16986                                + newTargetSandbox + " is incompatible with the previous value of"
16987                                + oldTargetSandbox + ".");
16988                        return;
16989                    }
16990
16991                    // Prevent installing of child packages
16992                    if (oldPackage.parentPackage != null) {
16993                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16994                                "Package " + pkg.packageName + " is child of package "
16995                                        + oldPackage.parentPackage + ". Child packages "
16996                                        + "can be updated only through the parent package.");
16997                        return;
16998                    }
16999                }
17000            }
17001
17002            PackageSetting ps = mSettings.mPackages.get(pkgName);
17003            if (ps != null) {
17004                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17005
17006                // Static shared libs have same package with different versions where
17007                // we internally use a synthetic package name to allow multiple versions
17008                // of the same package, therefore we need to compare signatures against
17009                // the package setting for the latest library version.
17010                PackageSetting signatureCheckPs = ps;
17011                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17012                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17013                    if (libraryEntry != null) {
17014                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17015                    }
17016                }
17017
17018                // Quick sanity check that we're signed correctly if updating;
17019                // we'll check this again later when scanning, but we want to
17020                // bail early here before tripping over redefined permissions.
17021                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17022                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17023                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17024                                + pkg.packageName + " upgrade keys do not match the "
17025                                + "previously installed version");
17026                        return;
17027                    }
17028                } else {
17029                    try {
17030                        verifySignaturesLP(signatureCheckPs, pkg);
17031                    } catch (PackageManagerException e) {
17032                        res.setError(e.error, e.getMessage());
17033                        return;
17034                    }
17035                }
17036
17037                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17038                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17039                    systemApp = (ps.pkg.applicationInfo.flags &
17040                            ApplicationInfo.FLAG_SYSTEM) != 0;
17041                }
17042                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17043            }
17044
17045            int N = pkg.permissions.size();
17046            for (int i = N-1; i >= 0; i--) {
17047                PackageParser.Permission perm = pkg.permissions.get(i);
17048                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17049
17050                // Don't allow anyone but the platform to define ephemeral permissions.
17051                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17052                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17053                    Slog.w(TAG, "Package " + pkg.packageName
17054                            + " attempting to delcare ephemeral permission "
17055                            + perm.info.name + "; Removing ephemeral.");
17056                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17057                }
17058                // Check whether the newly-scanned package wants to define an already-defined perm
17059                if (bp != null) {
17060                    // If the defining package is signed with our cert, it's okay.  This
17061                    // also includes the "updating the same package" case, of course.
17062                    // "updating same package" could also involve key-rotation.
17063                    final boolean sigsOk;
17064                    if (bp.sourcePackage.equals(pkg.packageName)
17065                            && (bp.packageSetting instanceof PackageSetting)
17066                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17067                                    scanFlags))) {
17068                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17069                    } else {
17070                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17071                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17072                    }
17073                    if (!sigsOk) {
17074                        // If the owning package is the system itself, we log but allow
17075                        // install to proceed; we fail the install on all other permission
17076                        // redefinitions.
17077                        if (!bp.sourcePackage.equals("android")) {
17078                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17079                                    + pkg.packageName + " attempting to redeclare permission "
17080                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17081                            res.origPermission = perm.info.name;
17082                            res.origPackage = bp.sourcePackage;
17083                            return;
17084                        } else {
17085                            Slog.w(TAG, "Package " + pkg.packageName
17086                                    + " attempting to redeclare system permission "
17087                                    + perm.info.name + "; ignoring new declaration");
17088                            pkg.permissions.remove(i);
17089                        }
17090                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17091                        // Prevent apps to change protection level to dangerous from any other
17092                        // type as this would allow a privilege escalation where an app adds a
17093                        // normal/signature permission in other app's group and later redefines
17094                        // it as dangerous leading to the group auto-grant.
17095                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17096                                == PermissionInfo.PROTECTION_DANGEROUS) {
17097                            if (bp != null && !bp.isRuntime()) {
17098                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17099                                        + "non-runtime permission " + perm.info.name
17100                                        + " to runtime; keeping old protection level");
17101                                perm.info.protectionLevel = bp.protectionLevel;
17102                            }
17103                        }
17104                    }
17105                }
17106            }
17107        }
17108
17109        if (systemApp) {
17110            if (onExternal) {
17111                // Abort update; system app can't be replaced with app on sdcard
17112                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17113                        "Cannot install updates to system apps on sdcard");
17114                return;
17115            } else if (instantApp) {
17116                // Abort update; system app can't be replaced with an instant app
17117                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17118                        "Cannot update a system app with an instant app");
17119                return;
17120            }
17121        }
17122
17123        if (args.move != null) {
17124            // We did an in-place move, so dex is ready to roll
17125            scanFlags |= SCAN_NO_DEX;
17126            scanFlags |= SCAN_MOVE;
17127
17128            synchronized (mPackages) {
17129                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17130                if (ps == null) {
17131                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17132                            "Missing settings for moved package " + pkgName);
17133                }
17134
17135                // We moved the entire application as-is, so bring over the
17136                // previously derived ABI information.
17137                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17138                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17139            }
17140
17141        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17142            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17143            scanFlags |= SCAN_NO_DEX;
17144
17145            try {
17146                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17147                    args.abiOverride : pkg.cpuAbiOverride);
17148                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17149                        true /*extractLibs*/, mAppLib32InstallDir);
17150            } catch (PackageManagerException pme) {
17151                Slog.e(TAG, "Error deriving application ABI", pme);
17152                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17153                return;
17154            }
17155
17156            // Shared libraries for the package need to be updated.
17157            synchronized (mPackages) {
17158                try {
17159                    updateSharedLibrariesLPr(pkg, null);
17160                } catch (PackageManagerException e) {
17161                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17162                }
17163            }
17164
17165            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17166            // Do not run PackageDexOptimizer through the local performDexOpt
17167            // method because `pkg` may not be in `mPackages` yet.
17168            //
17169            // Also, don't fail application installs if the dexopt step fails.
17170            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17171                    null /* instructionSets */, false /* checkProfiles */,
17172                    getCompilerFilterForReason(REASON_INSTALL),
17173                    getOrCreateCompilerPackageStats(pkg),
17174                    mDexManager.isUsedByOtherApps(pkg.packageName));
17175            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17176
17177            // Notify BackgroundDexOptService that the package has been changed.
17178            // If this is an update of a package which used to fail to compile,
17179            // BDOS will remove it from its blacklist.
17180            // TODO: Layering violation
17181            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17182        }
17183
17184        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17185            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17186            return;
17187        }
17188
17189        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17190
17191        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17192                "installPackageLI")) {
17193            if (replace) {
17194                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17195                    // Static libs have a synthetic package name containing the version
17196                    // and cannot be updated as an update would get a new package name,
17197                    // unless this is the exact same version code which is useful for
17198                    // development.
17199                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17200                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17201                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17202                                + "static-shared libs cannot be updated");
17203                        return;
17204                    }
17205                }
17206                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17207                        installerPackageName, res, args.installReason);
17208            } else {
17209                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17210                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17211            }
17212        }
17213
17214        synchronized (mPackages) {
17215            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17216            if (ps != null) {
17217                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17218                ps.setUpdateAvailable(false /*updateAvailable*/);
17219            }
17220
17221            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17222            for (int i = 0; i < childCount; i++) {
17223                PackageParser.Package childPkg = pkg.childPackages.get(i);
17224                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17225                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17226                if (childPs != null) {
17227                    childRes.newUsers = childPs.queryInstalledUsers(
17228                            sUserManager.getUserIds(), true);
17229                }
17230            }
17231
17232            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17233                updateSequenceNumberLP(pkgName, res.newUsers);
17234                updateInstantAppInstallerLocked(pkgName);
17235            }
17236        }
17237    }
17238
17239    private void startIntentFilterVerifications(int userId, boolean replacing,
17240            PackageParser.Package pkg) {
17241        if (mIntentFilterVerifierComponent == null) {
17242            Slog.w(TAG, "No IntentFilter verification will not be done as "
17243                    + "there is no IntentFilterVerifier available!");
17244            return;
17245        }
17246
17247        final int verifierUid = getPackageUid(
17248                mIntentFilterVerifierComponent.getPackageName(),
17249                MATCH_DEBUG_TRIAGED_MISSING,
17250                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17251
17252        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17253        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17254        mHandler.sendMessage(msg);
17255
17256        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17257        for (int i = 0; i < childCount; i++) {
17258            PackageParser.Package childPkg = pkg.childPackages.get(i);
17259            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17260            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17261            mHandler.sendMessage(msg);
17262        }
17263    }
17264
17265    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17266            PackageParser.Package pkg) {
17267        int size = pkg.activities.size();
17268        if (size == 0) {
17269            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17270                    "No activity, so no need to verify any IntentFilter!");
17271            return;
17272        }
17273
17274        final boolean hasDomainURLs = hasDomainURLs(pkg);
17275        if (!hasDomainURLs) {
17276            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17277                    "No domain URLs, so no need to verify any IntentFilter!");
17278            return;
17279        }
17280
17281        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17282                + " if any IntentFilter from the " + size
17283                + " Activities needs verification ...");
17284
17285        int count = 0;
17286        final String packageName = pkg.packageName;
17287
17288        synchronized (mPackages) {
17289            // If this is a new install and we see that we've already run verification for this
17290            // package, we have nothing to do: it means the state was restored from backup.
17291            if (!replacing) {
17292                IntentFilterVerificationInfo ivi =
17293                        mSettings.getIntentFilterVerificationLPr(packageName);
17294                if (ivi != null) {
17295                    if (DEBUG_DOMAIN_VERIFICATION) {
17296                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17297                                + ivi.getStatusString());
17298                    }
17299                    return;
17300                }
17301            }
17302
17303            // If any filters need to be verified, then all need to be.
17304            boolean needToVerify = false;
17305            for (PackageParser.Activity a : pkg.activities) {
17306                for (ActivityIntentInfo filter : a.intents) {
17307                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17308                        if (DEBUG_DOMAIN_VERIFICATION) {
17309                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17310                        }
17311                        needToVerify = true;
17312                        break;
17313                    }
17314                }
17315            }
17316
17317            if (needToVerify) {
17318                final int verificationId = mIntentFilterVerificationToken++;
17319                for (PackageParser.Activity a : pkg.activities) {
17320                    for (ActivityIntentInfo filter : a.intents) {
17321                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17322                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17323                                    "Verification needed for IntentFilter:" + filter.toString());
17324                            mIntentFilterVerifier.addOneIntentFilterVerification(
17325                                    verifierUid, userId, verificationId, filter, packageName);
17326                            count++;
17327                        }
17328                    }
17329                }
17330            }
17331        }
17332
17333        if (count > 0) {
17334            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17335                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17336                    +  " for userId:" + userId);
17337            mIntentFilterVerifier.startVerifications(userId);
17338        } else {
17339            if (DEBUG_DOMAIN_VERIFICATION) {
17340                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17341            }
17342        }
17343    }
17344
17345    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17346        final ComponentName cn  = filter.activity.getComponentName();
17347        final String packageName = cn.getPackageName();
17348
17349        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17350                packageName);
17351        if (ivi == null) {
17352            return true;
17353        }
17354        int status = ivi.getStatus();
17355        switch (status) {
17356            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17357            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17358                return true;
17359
17360            default:
17361                // Nothing to do
17362                return false;
17363        }
17364    }
17365
17366    private static boolean isMultiArch(ApplicationInfo info) {
17367        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17368    }
17369
17370    private static boolean isExternal(PackageParser.Package pkg) {
17371        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17372    }
17373
17374    private static boolean isExternal(PackageSetting ps) {
17375        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17376    }
17377
17378    private static boolean isSystemApp(PackageParser.Package pkg) {
17379        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17380    }
17381
17382    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17383        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17384    }
17385
17386    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17387        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17388    }
17389
17390    private static boolean isSystemApp(PackageSetting ps) {
17391        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17392    }
17393
17394    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17395        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17396    }
17397
17398    private int packageFlagsToInstallFlags(PackageSetting ps) {
17399        int installFlags = 0;
17400        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17401            // This existing package was an external ASEC install when we have
17402            // the external flag without a UUID
17403            installFlags |= PackageManager.INSTALL_EXTERNAL;
17404        }
17405        if (ps.isForwardLocked()) {
17406            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17407        }
17408        return installFlags;
17409    }
17410
17411    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17412        if (isExternal(pkg)) {
17413            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17414                return StorageManager.UUID_PRIMARY_PHYSICAL;
17415            } else {
17416                return pkg.volumeUuid;
17417            }
17418        } else {
17419            return StorageManager.UUID_PRIVATE_INTERNAL;
17420        }
17421    }
17422
17423    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17424        if (isExternal(pkg)) {
17425            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17426                return mSettings.getExternalVersion();
17427            } else {
17428                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17429            }
17430        } else {
17431            return mSettings.getInternalVersion();
17432        }
17433    }
17434
17435    private void deleteTempPackageFiles() {
17436        final FilenameFilter filter = new FilenameFilter() {
17437            public boolean accept(File dir, String name) {
17438                return name.startsWith("vmdl") && name.endsWith(".tmp");
17439            }
17440        };
17441        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17442            file.delete();
17443        }
17444    }
17445
17446    @Override
17447    public void deletePackageAsUser(String packageName, int versionCode,
17448            IPackageDeleteObserver observer, int userId, int flags) {
17449        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17450                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17451    }
17452
17453    @Override
17454    public void deletePackageVersioned(VersionedPackage versionedPackage,
17455            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17456        mContext.enforceCallingOrSelfPermission(
17457                android.Manifest.permission.DELETE_PACKAGES, null);
17458        Preconditions.checkNotNull(versionedPackage);
17459        Preconditions.checkNotNull(observer);
17460        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17461                PackageManager.VERSION_CODE_HIGHEST,
17462                Integer.MAX_VALUE, "versionCode must be >= -1");
17463
17464        final String packageName = versionedPackage.getPackageName();
17465        // TODO: We will change version code to long, so in the new API it is long
17466        final int versionCode = (int) versionedPackage.getVersionCode();
17467        final String internalPackageName;
17468        synchronized (mPackages) {
17469            // Normalize package name to handle renamed packages and static libs
17470            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17471                    // TODO: We will change version code to long, so in the new API it is long
17472                    (int) versionedPackage.getVersionCode());
17473        }
17474
17475        final int uid = Binder.getCallingUid();
17476        if (!isOrphaned(internalPackageName)
17477                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17478            try {
17479                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17480                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17481                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17482                observer.onUserActionRequired(intent);
17483            } catch (RemoteException re) {
17484            }
17485            return;
17486        }
17487        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17488        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17489        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17490            mContext.enforceCallingOrSelfPermission(
17491                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17492                    "deletePackage for user " + userId);
17493        }
17494
17495        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17496            try {
17497                observer.onPackageDeleted(packageName,
17498                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17499            } catch (RemoteException re) {
17500            }
17501            return;
17502        }
17503
17504        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17505            try {
17506                observer.onPackageDeleted(packageName,
17507                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17508            } catch (RemoteException re) {
17509            }
17510            return;
17511        }
17512
17513        if (DEBUG_REMOVE) {
17514            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17515                    + " deleteAllUsers: " + deleteAllUsers + " version="
17516                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17517                    ? "VERSION_CODE_HIGHEST" : versionCode));
17518        }
17519        // Queue up an async operation since the package deletion may take a little while.
17520        mHandler.post(new Runnable() {
17521            public void run() {
17522                mHandler.removeCallbacks(this);
17523                int returnCode;
17524                if (!deleteAllUsers) {
17525                    returnCode = deletePackageX(internalPackageName, versionCode,
17526                            userId, deleteFlags);
17527                } else {
17528                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17529                            internalPackageName, users);
17530                    // If nobody is blocking uninstall, proceed with delete for all users
17531                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17532                        returnCode = deletePackageX(internalPackageName, versionCode,
17533                                userId, deleteFlags);
17534                    } else {
17535                        // Otherwise uninstall individually for users with blockUninstalls=false
17536                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17537                        for (int userId : users) {
17538                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17539                                returnCode = deletePackageX(internalPackageName, versionCode,
17540                                        userId, userFlags);
17541                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17542                                    Slog.w(TAG, "Package delete failed for user " + userId
17543                                            + ", returnCode " + returnCode);
17544                                }
17545                            }
17546                        }
17547                        // The app has only been marked uninstalled for certain users.
17548                        // We still need to report that delete was blocked
17549                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17550                    }
17551                }
17552                try {
17553                    observer.onPackageDeleted(packageName, returnCode, null);
17554                } catch (RemoteException e) {
17555                    Log.i(TAG, "Observer no longer exists.");
17556                } //end catch
17557            } //end run
17558        });
17559    }
17560
17561    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17562        if (pkg.staticSharedLibName != null) {
17563            return pkg.manifestPackageName;
17564        }
17565        return pkg.packageName;
17566    }
17567
17568    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17569        // Handle renamed packages
17570        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17571        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17572
17573        // Is this a static library?
17574        SparseArray<SharedLibraryEntry> versionedLib =
17575                mStaticLibsByDeclaringPackage.get(packageName);
17576        if (versionedLib == null || versionedLib.size() <= 0) {
17577            return packageName;
17578        }
17579
17580        // Figure out which lib versions the caller can see
17581        SparseIntArray versionsCallerCanSee = null;
17582        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17583        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17584                && callingAppId != Process.ROOT_UID) {
17585            versionsCallerCanSee = new SparseIntArray();
17586            String libName = versionedLib.valueAt(0).info.getName();
17587            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17588            if (uidPackages != null) {
17589                for (String uidPackage : uidPackages) {
17590                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17591                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17592                    if (libIdx >= 0) {
17593                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17594                        versionsCallerCanSee.append(libVersion, libVersion);
17595                    }
17596                }
17597            }
17598        }
17599
17600        // Caller can see nothing - done
17601        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17602            return packageName;
17603        }
17604
17605        // Find the version the caller can see and the app version code
17606        SharedLibraryEntry highestVersion = null;
17607        final int versionCount = versionedLib.size();
17608        for (int i = 0; i < versionCount; i++) {
17609            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17610            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17611                    // TODO: Remove cast for lib version once internally we support longs.
17612                    (int) libEntry.info.getVersion()) < 0) {
17613                continue;
17614            }
17615            // TODO: We will change version code to long, so in the new API it is long
17616            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17617            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17618                if (libVersionCode == versionCode) {
17619                    return libEntry.apk;
17620                }
17621            } else if (highestVersion == null) {
17622                highestVersion = libEntry;
17623            } else if (libVersionCode  > highestVersion.info
17624                    .getDeclaringPackage().getVersionCode()) {
17625                highestVersion = libEntry;
17626            }
17627        }
17628
17629        if (highestVersion != null) {
17630            return highestVersion.apk;
17631        }
17632
17633        return packageName;
17634    }
17635
17636    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17637        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17638              || callingUid == Process.SYSTEM_UID) {
17639            return true;
17640        }
17641        final int callingUserId = UserHandle.getUserId(callingUid);
17642        // If the caller installed the pkgName, then allow it to silently uninstall.
17643        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17644            return true;
17645        }
17646
17647        // Allow package verifier to silently uninstall.
17648        if (mRequiredVerifierPackage != null &&
17649                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17650            return true;
17651        }
17652
17653        // Allow package uninstaller to silently uninstall.
17654        if (mRequiredUninstallerPackage != null &&
17655                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17656            return true;
17657        }
17658
17659        // Allow storage manager to silently uninstall.
17660        if (mStorageManagerPackage != null &&
17661                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17662            return true;
17663        }
17664        return false;
17665    }
17666
17667    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17668        int[] result = EMPTY_INT_ARRAY;
17669        for (int userId : userIds) {
17670            if (getBlockUninstallForUser(packageName, userId)) {
17671                result = ArrayUtils.appendInt(result, userId);
17672            }
17673        }
17674        return result;
17675    }
17676
17677    @Override
17678    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17679        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17680    }
17681
17682    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17683        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17684                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17685        try {
17686            if (dpm != null) {
17687                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17688                        /* callingUserOnly =*/ false);
17689                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17690                        : deviceOwnerComponentName.getPackageName();
17691                // Does the package contains the device owner?
17692                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17693                // this check is probably not needed, since DO should be registered as a device
17694                // admin on some user too. (Original bug for this: b/17657954)
17695                if (packageName.equals(deviceOwnerPackageName)) {
17696                    return true;
17697                }
17698                // Does it contain a device admin for any user?
17699                int[] users;
17700                if (userId == UserHandle.USER_ALL) {
17701                    users = sUserManager.getUserIds();
17702                } else {
17703                    users = new int[]{userId};
17704                }
17705                for (int i = 0; i < users.length; ++i) {
17706                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17707                        return true;
17708                    }
17709                }
17710            }
17711        } catch (RemoteException e) {
17712        }
17713        return false;
17714    }
17715
17716    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17717        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17718    }
17719
17720    /**
17721     *  This method is an internal method that could be get invoked either
17722     *  to delete an installed package or to clean up a failed installation.
17723     *  After deleting an installed package, a broadcast is sent to notify any
17724     *  listeners that the package has been removed. For cleaning up a failed
17725     *  installation, the broadcast is not necessary since the package's
17726     *  installation wouldn't have sent the initial broadcast either
17727     *  The key steps in deleting a package are
17728     *  deleting the package information in internal structures like mPackages,
17729     *  deleting the packages base directories through installd
17730     *  updating mSettings to reflect current status
17731     *  persisting settings for later use
17732     *  sending a broadcast if necessary
17733     */
17734    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17735        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17736        final boolean res;
17737
17738        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17739                ? UserHandle.USER_ALL : userId;
17740
17741        if (isPackageDeviceAdmin(packageName, removeUser)) {
17742            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17743            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17744        }
17745
17746        PackageSetting uninstalledPs = null;
17747        PackageParser.Package pkg = null;
17748
17749        // for the uninstall-updates case and restricted profiles, remember the per-
17750        // user handle installed state
17751        int[] allUsers;
17752        synchronized (mPackages) {
17753            uninstalledPs = mSettings.mPackages.get(packageName);
17754            if (uninstalledPs == null) {
17755                Slog.w(TAG, "Not removing non-existent package " + packageName);
17756                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17757            }
17758
17759            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17760                    && uninstalledPs.versionCode != versionCode) {
17761                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17762                        + uninstalledPs.versionCode + " != " + versionCode);
17763                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17764            }
17765
17766            // Static shared libs can be declared by any package, so let us not
17767            // allow removing a package if it provides a lib others depend on.
17768            pkg = mPackages.get(packageName);
17769            if (pkg != null && pkg.staticSharedLibName != null) {
17770                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17771                        pkg.staticSharedLibVersion);
17772                if (libEntry != null) {
17773                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17774                            libEntry.info, 0, userId);
17775                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17776                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17777                                + " hosting lib " + libEntry.info.getName() + " version "
17778                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17779                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17780                    }
17781                }
17782            }
17783
17784            allUsers = sUserManager.getUserIds();
17785            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17786        }
17787
17788        final int freezeUser;
17789        if (isUpdatedSystemApp(uninstalledPs)
17790                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17791            // We're downgrading a system app, which will apply to all users, so
17792            // freeze them all during the downgrade
17793            freezeUser = UserHandle.USER_ALL;
17794        } else {
17795            freezeUser = removeUser;
17796        }
17797
17798        synchronized (mInstallLock) {
17799            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17800            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17801                    deleteFlags, "deletePackageX")) {
17802                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17803                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17804            }
17805            synchronized (mPackages) {
17806                if (res) {
17807                    if (pkg != null) {
17808                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17809                    }
17810                    updateSequenceNumberLP(packageName, info.removedUsers);
17811                    updateInstantAppInstallerLocked(packageName);
17812                }
17813            }
17814        }
17815
17816        if (res) {
17817            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17818            info.sendPackageRemovedBroadcasts(killApp);
17819            info.sendSystemPackageUpdatedBroadcasts();
17820            info.sendSystemPackageAppearedBroadcasts();
17821        }
17822        // Force a gc here.
17823        Runtime.getRuntime().gc();
17824        // Delete the resources here after sending the broadcast to let
17825        // other processes clean up before deleting resources.
17826        if (info.args != null) {
17827            synchronized (mInstallLock) {
17828                info.args.doPostDeleteLI(true);
17829            }
17830        }
17831
17832        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17833    }
17834
17835    static class PackageRemovedInfo {
17836        final PackageSender packageSender;
17837        String removedPackage;
17838        String installerPackageName;
17839        int uid = -1;
17840        int removedAppId = -1;
17841        int[] origUsers;
17842        int[] removedUsers = null;
17843        int[] broadcastUsers = null;
17844        SparseArray<Integer> installReasons;
17845        boolean isRemovedPackageSystemUpdate = false;
17846        boolean isUpdate;
17847        boolean dataRemoved;
17848        boolean removedForAllUsers;
17849        boolean isStaticSharedLib;
17850        // Clean up resources deleted packages.
17851        InstallArgs args = null;
17852        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17853        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17854
17855        PackageRemovedInfo(PackageSender packageSender) {
17856            this.packageSender = packageSender;
17857        }
17858
17859        void sendPackageRemovedBroadcasts(boolean killApp) {
17860            sendPackageRemovedBroadcastInternal(killApp);
17861            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17862            for (int i = 0; i < childCount; i++) {
17863                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17864                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17865            }
17866        }
17867
17868        void sendSystemPackageUpdatedBroadcasts() {
17869            if (isRemovedPackageSystemUpdate) {
17870                sendSystemPackageUpdatedBroadcastsInternal();
17871                final int childCount = (removedChildPackages != null)
17872                        ? removedChildPackages.size() : 0;
17873                for (int i = 0; i < childCount; i++) {
17874                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17875                    if (childInfo.isRemovedPackageSystemUpdate) {
17876                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17877                    }
17878                }
17879            }
17880        }
17881
17882        void sendSystemPackageAppearedBroadcasts() {
17883            final int packageCount = (appearedChildPackages != null)
17884                    ? appearedChildPackages.size() : 0;
17885            for (int i = 0; i < packageCount; i++) {
17886                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17887                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17888                    true, UserHandle.getAppId(installedInfo.uid),
17889                    installedInfo.newUsers);
17890            }
17891        }
17892
17893        private void sendSystemPackageUpdatedBroadcastsInternal() {
17894            Bundle extras = new Bundle(2);
17895            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17896            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17897            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17898                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17899            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17900                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17901            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17902                null, null, 0, removedPackage, null, null);
17903            if (installerPackageName != null) {
17904                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17905                        removedPackage, extras, 0 /*flags*/,
17906                        installerPackageName, null, null);
17907                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17908                        removedPackage, extras, 0 /*flags*/,
17909                        installerPackageName, null, null);
17910            }
17911        }
17912
17913        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17914            // Don't send static shared library removal broadcasts as these
17915            // libs are visible only the the apps that depend on them an one
17916            // cannot remove the library if it has a dependency.
17917            if (isStaticSharedLib) {
17918                return;
17919            }
17920            Bundle extras = new Bundle(2);
17921            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17922            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17923            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17924            if (isUpdate || isRemovedPackageSystemUpdate) {
17925                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17926            }
17927            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17928            if (removedPackage != null) {
17929                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17930                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
17931                if (installerPackageName != null) {
17932                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17933                            removedPackage, extras, 0 /*flags*/,
17934                            installerPackageName, null, broadcastUsers);
17935                }
17936                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17937                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17938                        removedPackage, extras,
17939                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17940                        null, null, broadcastUsers);
17941                }
17942            }
17943            if (removedAppId >= 0) {
17944                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
17945                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
17946            }
17947        }
17948
17949        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17950            removedUsers = userIds;
17951            if (removedUsers == null) {
17952                broadcastUsers = null;
17953                return;
17954            }
17955
17956            broadcastUsers = EMPTY_INT_ARRAY;
17957            for (int i = userIds.length - 1; i >= 0; --i) {
17958                final int userId = userIds[i];
17959                if (deletedPackageSetting.getInstantApp(userId)) {
17960                    continue;
17961                }
17962                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17963            }
17964        }
17965    }
17966
17967    /*
17968     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17969     * flag is not set, the data directory is removed as well.
17970     * make sure this flag is set for partially installed apps. If not its meaningless to
17971     * delete a partially installed application.
17972     */
17973    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17974            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17975        String packageName = ps.name;
17976        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17977        // Retrieve object to delete permissions for shared user later on
17978        final PackageParser.Package deletedPkg;
17979        final PackageSetting deletedPs;
17980        // reader
17981        synchronized (mPackages) {
17982            deletedPkg = mPackages.get(packageName);
17983            deletedPs = mSettings.mPackages.get(packageName);
17984            if (outInfo != null) {
17985                outInfo.removedPackage = packageName;
17986                outInfo.installerPackageName = ps.installerPackageName;
17987                outInfo.isStaticSharedLib = deletedPkg != null
17988                        && deletedPkg.staticSharedLibName != null;
17989                outInfo.populateUsers(deletedPs == null ? null
17990                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17991            }
17992        }
17993
17994        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17995
17996        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17997            final PackageParser.Package resolvedPkg;
17998            if (deletedPkg != null) {
17999                resolvedPkg = deletedPkg;
18000            } else {
18001                // We don't have a parsed package when it lives on an ejected
18002                // adopted storage device, so fake something together
18003                resolvedPkg = new PackageParser.Package(ps.name);
18004                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18005            }
18006            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18007                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18008            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18009            if (outInfo != null) {
18010                outInfo.dataRemoved = true;
18011            }
18012            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18013        }
18014
18015        int removedAppId = -1;
18016
18017        // writer
18018        synchronized (mPackages) {
18019            boolean installedStateChanged = false;
18020            if (deletedPs != null) {
18021                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18022                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18023                    clearDefaultBrowserIfNeeded(packageName);
18024                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18025                    removedAppId = mSettings.removePackageLPw(packageName);
18026                    if (outInfo != null) {
18027                        outInfo.removedAppId = removedAppId;
18028                    }
18029                    updatePermissionsLPw(deletedPs.name, null, 0);
18030                    if (deletedPs.sharedUser != null) {
18031                        // Remove permissions associated with package. Since runtime
18032                        // permissions are per user we have to kill the removed package
18033                        // or packages running under the shared user of the removed
18034                        // package if revoking the permissions requested only by the removed
18035                        // package is successful and this causes a change in gids.
18036                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18037                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18038                                    userId);
18039                            if (userIdToKill == UserHandle.USER_ALL
18040                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18041                                // If gids changed for this user, kill all affected packages.
18042                                mHandler.post(new Runnable() {
18043                                    @Override
18044                                    public void run() {
18045                                        // This has to happen with no lock held.
18046                                        killApplication(deletedPs.name, deletedPs.appId,
18047                                                KILL_APP_REASON_GIDS_CHANGED);
18048                                    }
18049                                });
18050                                break;
18051                            }
18052                        }
18053                    }
18054                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18055                }
18056                // make sure to preserve per-user disabled state if this removal was just
18057                // a downgrade of a system app to the factory package
18058                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18059                    if (DEBUG_REMOVE) {
18060                        Slog.d(TAG, "Propagating install state across downgrade");
18061                    }
18062                    for (int userId : allUserHandles) {
18063                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18064                        if (DEBUG_REMOVE) {
18065                            Slog.d(TAG, "    user " + userId + " => " + installed);
18066                        }
18067                        if (installed != ps.getInstalled(userId)) {
18068                            installedStateChanged = true;
18069                        }
18070                        ps.setInstalled(installed, userId);
18071                    }
18072                }
18073            }
18074            // can downgrade to reader
18075            if (writeSettings) {
18076                // Save settings now
18077                mSettings.writeLPr();
18078            }
18079            if (installedStateChanged) {
18080                mSettings.writeKernelMappingLPr(ps);
18081            }
18082        }
18083        if (removedAppId != -1) {
18084            // A user ID was deleted here. Go through all users and remove it
18085            // from KeyStore.
18086            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18087        }
18088    }
18089
18090    static boolean locationIsPrivileged(File path) {
18091        try {
18092            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18093                    .getCanonicalPath();
18094            return path.getCanonicalPath().startsWith(privilegedAppDir);
18095        } catch (IOException e) {
18096            Slog.e(TAG, "Unable to access code path " + path);
18097        }
18098        return false;
18099    }
18100
18101    /*
18102     * Tries to delete system package.
18103     */
18104    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18105            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18106            boolean writeSettings) {
18107        if (deletedPs.parentPackageName != null) {
18108            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18109            return false;
18110        }
18111
18112        final boolean applyUserRestrictions
18113                = (allUserHandles != null) && (outInfo.origUsers != null);
18114        final PackageSetting disabledPs;
18115        // Confirm if the system package has been updated
18116        // An updated system app can be deleted. This will also have to restore
18117        // the system pkg from system partition
18118        // reader
18119        synchronized (mPackages) {
18120            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18121        }
18122
18123        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18124                + " disabledPs=" + disabledPs);
18125
18126        if (disabledPs == null) {
18127            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18128            return false;
18129        } else if (DEBUG_REMOVE) {
18130            Slog.d(TAG, "Deleting system pkg from data partition");
18131        }
18132
18133        if (DEBUG_REMOVE) {
18134            if (applyUserRestrictions) {
18135                Slog.d(TAG, "Remembering install states:");
18136                for (int userId : allUserHandles) {
18137                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18138                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18139                }
18140            }
18141        }
18142
18143        // Delete the updated package
18144        outInfo.isRemovedPackageSystemUpdate = true;
18145        if (outInfo.removedChildPackages != null) {
18146            final int childCount = (deletedPs.childPackageNames != null)
18147                    ? deletedPs.childPackageNames.size() : 0;
18148            for (int i = 0; i < childCount; i++) {
18149                String childPackageName = deletedPs.childPackageNames.get(i);
18150                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18151                        .contains(childPackageName)) {
18152                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18153                            childPackageName);
18154                    if (childInfo != null) {
18155                        childInfo.isRemovedPackageSystemUpdate = true;
18156                    }
18157                }
18158            }
18159        }
18160
18161        if (disabledPs.versionCode < deletedPs.versionCode) {
18162            // Delete data for downgrades
18163            flags &= ~PackageManager.DELETE_KEEP_DATA;
18164        } else {
18165            // Preserve data by setting flag
18166            flags |= PackageManager.DELETE_KEEP_DATA;
18167        }
18168
18169        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18170                outInfo, writeSettings, disabledPs.pkg);
18171        if (!ret) {
18172            return false;
18173        }
18174
18175        // writer
18176        synchronized (mPackages) {
18177            // Reinstate the old system package
18178            enableSystemPackageLPw(disabledPs.pkg);
18179            // Remove any native libraries from the upgraded package.
18180            removeNativeBinariesLI(deletedPs);
18181        }
18182
18183        // Install the system package
18184        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18185        int parseFlags = mDefParseFlags
18186                | PackageParser.PARSE_MUST_BE_APK
18187                | PackageParser.PARSE_IS_SYSTEM
18188                | PackageParser.PARSE_IS_SYSTEM_DIR;
18189        if (locationIsPrivileged(disabledPs.codePath)) {
18190            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18191        }
18192
18193        final PackageParser.Package newPkg;
18194        try {
18195            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18196                0 /* currentTime */, null);
18197        } catch (PackageManagerException e) {
18198            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18199                    + e.getMessage());
18200            return false;
18201        }
18202
18203        try {
18204            // update shared libraries for the newly re-installed system package
18205            updateSharedLibrariesLPr(newPkg, null);
18206        } catch (PackageManagerException e) {
18207            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18208        }
18209
18210        prepareAppDataAfterInstallLIF(newPkg);
18211
18212        // writer
18213        synchronized (mPackages) {
18214            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18215
18216            // Propagate the permissions state as we do not want to drop on the floor
18217            // runtime permissions. The update permissions method below will take
18218            // care of removing obsolete permissions and grant install permissions.
18219            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18220            updatePermissionsLPw(newPkg.packageName, newPkg,
18221                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18222
18223            if (applyUserRestrictions) {
18224                boolean installedStateChanged = false;
18225                if (DEBUG_REMOVE) {
18226                    Slog.d(TAG, "Propagating install state across reinstall");
18227                }
18228                for (int userId : allUserHandles) {
18229                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18230                    if (DEBUG_REMOVE) {
18231                        Slog.d(TAG, "    user " + userId + " => " + installed);
18232                    }
18233                    if (installed != ps.getInstalled(userId)) {
18234                        installedStateChanged = true;
18235                    }
18236                    ps.setInstalled(installed, userId);
18237
18238                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18239                }
18240                // Regardless of writeSettings we need to ensure that this restriction
18241                // state propagation is persisted
18242                mSettings.writeAllUsersPackageRestrictionsLPr();
18243                if (installedStateChanged) {
18244                    mSettings.writeKernelMappingLPr(ps);
18245                }
18246            }
18247            // can downgrade to reader here
18248            if (writeSettings) {
18249                mSettings.writeLPr();
18250            }
18251        }
18252        return true;
18253    }
18254
18255    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18256            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18257            PackageRemovedInfo outInfo, boolean writeSettings,
18258            PackageParser.Package replacingPackage) {
18259        synchronized (mPackages) {
18260            if (outInfo != null) {
18261                outInfo.uid = ps.appId;
18262            }
18263
18264            if (outInfo != null && outInfo.removedChildPackages != null) {
18265                final int childCount = (ps.childPackageNames != null)
18266                        ? ps.childPackageNames.size() : 0;
18267                for (int i = 0; i < childCount; i++) {
18268                    String childPackageName = ps.childPackageNames.get(i);
18269                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18270                    if (childPs == null) {
18271                        return false;
18272                    }
18273                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18274                            childPackageName);
18275                    if (childInfo != null) {
18276                        childInfo.uid = childPs.appId;
18277                    }
18278                }
18279            }
18280        }
18281
18282        // Delete package data from internal structures and also remove data if flag is set
18283        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18284
18285        // Delete the child packages data
18286        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18287        for (int i = 0; i < childCount; i++) {
18288            PackageSetting childPs;
18289            synchronized (mPackages) {
18290                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18291            }
18292            if (childPs != null) {
18293                PackageRemovedInfo childOutInfo = (outInfo != null
18294                        && outInfo.removedChildPackages != null)
18295                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18296                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18297                        && (replacingPackage != null
18298                        && !replacingPackage.hasChildPackage(childPs.name))
18299                        ? flags & ~DELETE_KEEP_DATA : flags;
18300                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18301                        deleteFlags, writeSettings);
18302            }
18303        }
18304
18305        // Delete application code and resources only for parent packages
18306        if (ps.parentPackageName == null) {
18307            if (deleteCodeAndResources && (outInfo != null)) {
18308                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18309                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18310                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18311            }
18312        }
18313
18314        return true;
18315    }
18316
18317    @Override
18318    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18319            int userId) {
18320        mContext.enforceCallingOrSelfPermission(
18321                android.Manifest.permission.DELETE_PACKAGES, null);
18322        synchronized (mPackages) {
18323            PackageSetting ps = mSettings.mPackages.get(packageName);
18324            if (ps == null) {
18325                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18326                return false;
18327            }
18328            // Cannot block uninstall of static shared libs as they are
18329            // considered a part of the using app (emulating static linking).
18330            // Also static libs are installed always on internal storage.
18331            PackageParser.Package pkg = mPackages.get(packageName);
18332            if (pkg != null && pkg.staticSharedLibName != null) {
18333                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18334                        + " providing static shared library: " + pkg.staticSharedLibName);
18335                return false;
18336            }
18337            if (!ps.getInstalled(userId)) {
18338                // Can't block uninstall for an app that is not installed or enabled.
18339                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18340                return false;
18341            }
18342            ps.setBlockUninstall(blockUninstall, userId);
18343            mSettings.writePackageRestrictionsLPr(userId);
18344        }
18345        return true;
18346    }
18347
18348    @Override
18349    public boolean getBlockUninstallForUser(String packageName, int userId) {
18350        synchronized (mPackages) {
18351            PackageSetting ps = mSettings.mPackages.get(packageName);
18352            if (ps == null) {
18353                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18354                return false;
18355            }
18356            return ps.getBlockUninstall(userId);
18357        }
18358    }
18359
18360    @Override
18361    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18362        int callingUid = Binder.getCallingUid();
18363        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18364            throw new SecurityException(
18365                    "setRequiredForSystemUser can only be run by the system or root");
18366        }
18367        synchronized (mPackages) {
18368            PackageSetting ps = mSettings.mPackages.get(packageName);
18369            if (ps == null) {
18370                Log.w(TAG, "Package doesn't exist: " + packageName);
18371                return false;
18372            }
18373            if (systemUserApp) {
18374                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18375            } else {
18376                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18377            }
18378            mSettings.writeLPr();
18379        }
18380        return true;
18381    }
18382
18383    /*
18384     * This method handles package deletion in general
18385     */
18386    private boolean deletePackageLIF(String packageName, UserHandle user,
18387            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18388            PackageRemovedInfo outInfo, boolean writeSettings,
18389            PackageParser.Package replacingPackage) {
18390        if (packageName == null) {
18391            Slog.w(TAG, "Attempt to delete null packageName.");
18392            return false;
18393        }
18394
18395        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18396
18397        PackageSetting ps;
18398        synchronized (mPackages) {
18399            ps = mSettings.mPackages.get(packageName);
18400            if (ps == null) {
18401                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18402                return false;
18403            }
18404
18405            if (ps.parentPackageName != null && (!isSystemApp(ps)
18406                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18407                if (DEBUG_REMOVE) {
18408                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18409                            + ((user == null) ? UserHandle.USER_ALL : user));
18410                }
18411                final int removedUserId = (user != null) ? user.getIdentifier()
18412                        : UserHandle.USER_ALL;
18413                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18414                    return false;
18415                }
18416                markPackageUninstalledForUserLPw(ps, user);
18417                scheduleWritePackageRestrictionsLocked(user);
18418                return true;
18419            }
18420        }
18421
18422        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18423                && user.getIdentifier() != UserHandle.USER_ALL)) {
18424            // The caller is asking that the package only be deleted for a single
18425            // user.  To do this, we just mark its uninstalled state and delete
18426            // its data. If this is a system app, we only allow this to happen if
18427            // they have set the special DELETE_SYSTEM_APP which requests different
18428            // semantics than normal for uninstalling system apps.
18429            markPackageUninstalledForUserLPw(ps, user);
18430
18431            if (!isSystemApp(ps)) {
18432                // Do not uninstall the APK if an app should be cached
18433                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18434                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18435                    // Other user still have this package installed, so all
18436                    // we need to do is clear this user's data and save that
18437                    // it is uninstalled.
18438                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18439                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18440                        return false;
18441                    }
18442                    scheduleWritePackageRestrictionsLocked(user);
18443                    return true;
18444                } else {
18445                    // We need to set it back to 'installed' so the uninstall
18446                    // broadcasts will be sent correctly.
18447                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18448                    ps.setInstalled(true, user.getIdentifier());
18449                    mSettings.writeKernelMappingLPr(ps);
18450                }
18451            } else {
18452                // This is a system app, so we assume that the
18453                // other users still have this package installed, so all
18454                // we need to do is clear this user's data and save that
18455                // it is uninstalled.
18456                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18457                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18458                    return false;
18459                }
18460                scheduleWritePackageRestrictionsLocked(user);
18461                return true;
18462            }
18463        }
18464
18465        // If we are deleting a composite package for all users, keep track
18466        // of result for each child.
18467        if (ps.childPackageNames != null && outInfo != null) {
18468            synchronized (mPackages) {
18469                final int childCount = ps.childPackageNames.size();
18470                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18471                for (int i = 0; i < childCount; i++) {
18472                    String childPackageName = ps.childPackageNames.get(i);
18473                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18474                    childInfo.removedPackage = childPackageName;
18475                    childInfo.installerPackageName = ps.installerPackageName;
18476                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18477                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18478                    if (childPs != null) {
18479                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18480                    }
18481                }
18482            }
18483        }
18484
18485        boolean ret = false;
18486        if (isSystemApp(ps)) {
18487            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18488            // When an updated system application is deleted we delete the existing resources
18489            // as well and fall back to existing code in system partition
18490            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18491        } else {
18492            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18493            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18494                    outInfo, writeSettings, replacingPackage);
18495        }
18496
18497        // Take a note whether we deleted the package for all users
18498        if (outInfo != null) {
18499            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18500            if (outInfo.removedChildPackages != null) {
18501                synchronized (mPackages) {
18502                    final int childCount = outInfo.removedChildPackages.size();
18503                    for (int i = 0; i < childCount; i++) {
18504                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18505                        if (childInfo != null) {
18506                            childInfo.removedForAllUsers = mPackages.get(
18507                                    childInfo.removedPackage) == null;
18508                        }
18509                    }
18510                }
18511            }
18512            // If we uninstalled an update to a system app there may be some
18513            // child packages that appeared as they are declared in the system
18514            // app but were not declared in the update.
18515            if (isSystemApp(ps)) {
18516                synchronized (mPackages) {
18517                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18518                    final int childCount = (updatedPs.childPackageNames != null)
18519                            ? updatedPs.childPackageNames.size() : 0;
18520                    for (int i = 0; i < childCount; i++) {
18521                        String childPackageName = updatedPs.childPackageNames.get(i);
18522                        if (outInfo.removedChildPackages == null
18523                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18524                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18525                            if (childPs == null) {
18526                                continue;
18527                            }
18528                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18529                            installRes.name = childPackageName;
18530                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18531                            installRes.pkg = mPackages.get(childPackageName);
18532                            installRes.uid = childPs.pkg.applicationInfo.uid;
18533                            if (outInfo.appearedChildPackages == null) {
18534                                outInfo.appearedChildPackages = new ArrayMap<>();
18535                            }
18536                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18537                        }
18538                    }
18539                }
18540            }
18541        }
18542
18543        return ret;
18544    }
18545
18546    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18547        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18548                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18549        for (int nextUserId : userIds) {
18550            if (DEBUG_REMOVE) {
18551                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18552            }
18553            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18554                    false /*installed*/,
18555                    true /*stopped*/,
18556                    true /*notLaunched*/,
18557                    false /*hidden*/,
18558                    false /*suspended*/,
18559                    false /*instantApp*/,
18560                    null /*lastDisableAppCaller*/,
18561                    null /*enabledComponents*/,
18562                    null /*disabledComponents*/,
18563                    false /*blockUninstall*/,
18564                    ps.readUserState(nextUserId).domainVerificationStatus,
18565                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18566        }
18567        mSettings.writeKernelMappingLPr(ps);
18568    }
18569
18570    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18571            PackageRemovedInfo outInfo) {
18572        final PackageParser.Package pkg;
18573        synchronized (mPackages) {
18574            pkg = mPackages.get(ps.name);
18575        }
18576
18577        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18578                : new int[] {userId};
18579        for (int nextUserId : userIds) {
18580            if (DEBUG_REMOVE) {
18581                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18582                        + nextUserId);
18583            }
18584
18585            destroyAppDataLIF(pkg, userId,
18586                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18587            destroyAppProfilesLIF(pkg, userId);
18588            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18589            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18590            schedulePackageCleaning(ps.name, nextUserId, false);
18591            synchronized (mPackages) {
18592                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18593                    scheduleWritePackageRestrictionsLocked(nextUserId);
18594                }
18595                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18596            }
18597        }
18598
18599        if (outInfo != null) {
18600            outInfo.removedPackage = ps.name;
18601            outInfo.installerPackageName = ps.installerPackageName;
18602            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18603            outInfo.removedAppId = ps.appId;
18604            outInfo.removedUsers = userIds;
18605            outInfo.broadcastUsers = userIds;
18606        }
18607
18608        return true;
18609    }
18610
18611    private final class ClearStorageConnection implements ServiceConnection {
18612        IMediaContainerService mContainerService;
18613
18614        @Override
18615        public void onServiceConnected(ComponentName name, IBinder service) {
18616            synchronized (this) {
18617                mContainerService = IMediaContainerService.Stub
18618                        .asInterface(Binder.allowBlocking(service));
18619                notifyAll();
18620            }
18621        }
18622
18623        @Override
18624        public void onServiceDisconnected(ComponentName name) {
18625        }
18626    }
18627
18628    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18629        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18630
18631        final boolean mounted;
18632        if (Environment.isExternalStorageEmulated()) {
18633            mounted = true;
18634        } else {
18635            final String status = Environment.getExternalStorageState();
18636
18637            mounted = status.equals(Environment.MEDIA_MOUNTED)
18638                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18639        }
18640
18641        if (!mounted) {
18642            return;
18643        }
18644
18645        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18646        int[] users;
18647        if (userId == UserHandle.USER_ALL) {
18648            users = sUserManager.getUserIds();
18649        } else {
18650            users = new int[] { userId };
18651        }
18652        final ClearStorageConnection conn = new ClearStorageConnection();
18653        if (mContext.bindServiceAsUser(
18654                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18655            try {
18656                for (int curUser : users) {
18657                    long timeout = SystemClock.uptimeMillis() + 5000;
18658                    synchronized (conn) {
18659                        long now;
18660                        while (conn.mContainerService == null &&
18661                                (now = SystemClock.uptimeMillis()) < timeout) {
18662                            try {
18663                                conn.wait(timeout - now);
18664                            } catch (InterruptedException e) {
18665                            }
18666                        }
18667                    }
18668                    if (conn.mContainerService == null) {
18669                        return;
18670                    }
18671
18672                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18673                    clearDirectory(conn.mContainerService,
18674                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18675                    if (allData) {
18676                        clearDirectory(conn.mContainerService,
18677                                userEnv.buildExternalStorageAppDataDirs(packageName));
18678                        clearDirectory(conn.mContainerService,
18679                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18680                    }
18681                }
18682            } finally {
18683                mContext.unbindService(conn);
18684            }
18685        }
18686    }
18687
18688    @Override
18689    public void clearApplicationProfileData(String packageName) {
18690        enforceSystemOrRoot("Only the system can clear all profile data");
18691
18692        final PackageParser.Package pkg;
18693        synchronized (mPackages) {
18694            pkg = mPackages.get(packageName);
18695        }
18696
18697        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18698            synchronized (mInstallLock) {
18699                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18700            }
18701        }
18702    }
18703
18704    @Override
18705    public void clearApplicationUserData(final String packageName,
18706            final IPackageDataObserver observer, final int userId) {
18707        mContext.enforceCallingOrSelfPermission(
18708                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18709
18710        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18711                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18712
18713        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18714            throw new SecurityException("Cannot clear data for a protected package: "
18715                    + packageName);
18716        }
18717        // Queue up an async operation since the package deletion may take a little while.
18718        mHandler.post(new Runnable() {
18719            public void run() {
18720                mHandler.removeCallbacks(this);
18721                final boolean succeeded;
18722                try (PackageFreezer freezer = freezePackage(packageName,
18723                        "clearApplicationUserData")) {
18724                    synchronized (mInstallLock) {
18725                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18726                    }
18727                    clearExternalStorageDataSync(packageName, userId, true);
18728                    synchronized (mPackages) {
18729                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18730                                packageName, userId);
18731                    }
18732                }
18733                if (succeeded) {
18734                    // invoke DeviceStorageMonitor's update method to clear any notifications
18735                    DeviceStorageMonitorInternal dsm = LocalServices
18736                            .getService(DeviceStorageMonitorInternal.class);
18737                    if (dsm != null) {
18738                        dsm.checkMemory();
18739                    }
18740                }
18741                if(observer != null) {
18742                    try {
18743                        observer.onRemoveCompleted(packageName, succeeded);
18744                    } catch (RemoteException e) {
18745                        Log.i(TAG, "Observer no longer exists.");
18746                    }
18747                } //end if observer
18748            } //end run
18749        });
18750    }
18751
18752    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18753        if (packageName == null) {
18754            Slog.w(TAG, "Attempt to delete null packageName.");
18755            return false;
18756        }
18757
18758        // Try finding details about the requested package
18759        PackageParser.Package pkg;
18760        synchronized (mPackages) {
18761            pkg = mPackages.get(packageName);
18762            if (pkg == null) {
18763                final PackageSetting ps = mSettings.mPackages.get(packageName);
18764                if (ps != null) {
18765                    pkg = ps.pkg;
18766                }
18767            }
18768
18769            if (pkg == null) {
18770                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18771                return false;
18772            }
18773
18774            PackageSetting ps = (PackageSetting) pkg.mExtras;
18775            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18776        }
18777
18778        clearAppDataLIF(pkg, userId,
18779                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18780
18781        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18782        removeKeystoreDataIfNeeded(userId, appId);
18783
18784        UserManagerInternal umInternal = getUserManagerInternal();
18785        final int flags;
18786        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18787            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18788        } else if (umInternal.isUserRunning(userId)) {
18789            flags = StorageManager.FLAG_STORAGE_DE;
18790        } else {
18791            flags = 0;
18792        }
18793        prepareAppDataContentsLIF(pkg, userId, flags);
18794
18795        return true;
18796    }
18797
18798    /**
18799     * Reverts user permission state changes (permissions and flags) in
18800     * all packages for a given user.
18801     *
18802     * @param userId The device user for which to do a reset.
18803     */
18804    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18805        final int packageCount = mPackages.size();
18806        for (int i = 0; i < packageCount; i++) {
18807            PackageParser.Package pkg = mPackages.valueAt(i);
18808            PackageSetting ps = (PackageSetting) pkg.mExtras;
18809            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18810        }
18811    }
18812
18813    private void resetNetworkPolicies(int userId) {
18814        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18815    }
18816
18817    /**
18818     * Reverts user permission state changes (permissions and flags).
18819     *
18820     * @param ps The package for which to reset.
18821     * @param userId The device user for which to do a reset.
18822     */
18823    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18824            final PackageSetting ps, final int userId) {
18825        if (ps.pkg == null) {
18826            return;
18827        }
18828
18829        // These are flags that can change base on user actions.
18830        final int userSettableMask = FLAG_PERMISSION_USER_SET
18831                | FLAG_PERMISSION_USER_FIXED
18832                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18833                | FLAG_PERMISSION_REVIEW_REQUIRED;
18834
18835        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18836                | FLAG_PERMISSION_POLICY_FIXED;
18837
18838        boolean writeInstallPermissions = false;
18839        boolean writeRuntimePermissions = false;
18840
18841        final int permissionCount = ps.pkg.requestedPermissions.size();
18842        for (int i = 0; i < permissionCount; i++) {
18843            String permission = ps.pkg.requestedPermissions.get(i);
18844
18845            BasePermission bp = mSettings.mPermissions.get(permission);
18846            if (bp == null) {
18847                continue;
18848            }
18849
18850            // If shared user we just reset the state to which only this app contributed.
18851            if (ps.sharedUser != null) {
18852                boolean used = false;
18853                final int packageCount = ps.sharedUser.packages.size();
18854                for (int j = 0; j < packageCount; j++) {
18855                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18856                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18857                            && pkg.pkg.requestedPermissions.contains(permission)) {
18858                        used = true;
18859                        break;
18860                    }
18861                }
18862                if (used) {
18863                    continue;
18864                }
18865            }
18866
18867            PermissionsState permissionsState = ps.getPermissionsState();
18868
18869            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18870
18871            // Always clear the user settable flags.
18872            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18873                    bp.name) != null;
18874            // If permission review is enabled and this is a legacy app, mark the
18875            // permission as requiring a review as this is the initial state.
18876            int flags = 0;
18877            if (mPermissionReviewRequired
18878                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18879                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18880            }
18881            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18882                if (hasInstallState) {
18883                    writeInstallPermissions = true;
18884                } else {
18885                    writeRuntimePermissions = true;
18886                }
18887            }
18888
18889            // Below is only runtime permission handling.
18890            if (!bp.isRuntime()) {
18891                continue;
18892            }
18893
18894            // Never clobber system or policy.
18895            if ((oldFlags & policyOrSystemFlags) != 0) {
18896                continue;
18897            }
18898
18899            // If this permission was granted by default, make sure it is.
18900            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18901                if (permissionsState.grantRuntimePermission(bp, userId)
18902                        != PERMISSION_OPERATION_FAILURE) {
18903                    writeRuntimePermissions = true;
18904                }
18905            // If permission review is enabled the permissions for a legacy apps
18906            // are represented as constantly granted runtime ones, so don't revoke.
18907            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18908                // Otherwise, reset the permission.
18909                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18910                switch (revokeResult) {
18911                    case PERMISSION_OPERATION_SUCCESS:
18912                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18913                        writeRuntimePermissions = true;
18914                        final int appId = ps.appId;
18915                        mHandler.post(new Runnable() {
18916                            @Override
18917                            public void run() {
18918                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18919                            }
18920                        });
18921                    } break;
18922                }
18923            }
18924        }
18925
18926        // Synchronously write as we are taking permissions away.
18927        if (writeRuntimePermissions) {
18928            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18929        }
18930
18931        // Synchronously write as we are taking permissions away.
18932        if (writeInstallPermissions) {
18933            mSettings.writeLPr();
18934        }
18935    }
18936
18937    /**
18938     * Remove entries from the keystore daemon. Will only remove it if the
18939     * {@code appId} is valid.
18940     */
18941    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18942        if (appId < 0) {
18943            return;
18944        }
18945
18946        final KeyStore keyStore = KeyStore.getInstance();
18947        if (keyStore != null) {
18948            if (userId == UserHandle.USER_ALL) {
18949                for (final int individual : sUserManager.getUserIds()) {
18950                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18951                }
18952            } else {
18953                keyStore.clearUid(UserHandle.getUid(userId, appId));
18954            }
18955        } else {
18956            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18957        }
18958    }
18959
18960    @Override
18961    public void deleteApplicationCacheFiles(final String packageName,
18962            final IPackageDataObserver observer) {
18963        final int userId = UserHandle.getCallingUserId();
18964        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18965    }
18966
18967    @Override
18968    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18969            final IPackageDataObserver observer) {
18970        mContext.enforceCallingOrSelfPermission(
18971                android.Manifest.permission.DELETE_CACHE_FILES, null);
18972        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18973                /* requireFullPermission= */ true, /* checkShell= */ false,
18974                "delete application cache files");
18975
18976        final PackageParser.Package pkg;
18977        synchronized (mPackages) {
18978            pkg = mPackages.get(packageName);
18979        }
18980
18981        // Queue up an async operation since the package deletion may take a little while.
18982        mHandler.post(new Runnable() {
18983            public void run() {
18984                synchronized (mInstallLock) {
18985                    final int flags = StorageManager.FLAG_STORAGE_DE
18986                            | StorageManager.FLAG_STORAGE_CE;
18987                    // We're only clearing cache files, so we don't care if the
18988                    // app is unfrozen and still able to run
18989                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18990                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18991                }
18992                clearExternalStorageDataSync(packageName, userId, false);
18993                if (observer != null) {
18994                    try {
18995                        observer.onRemoveCompleted(packageName, true);
18996                    } catch (RemoteException e) {
18997                        Log.i(TAG, "Observer no longer exists.");
18998                    }
18999                }
19000            }
19001        });
19002    }
19003
19004    @Override
19005    public void getPackageSizeInfo(final String packageName, int userHandle,
19006            final IPackageStatsObserver observer) {
19007        throw new UnsupportedOperationException(
19008                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19009    }
19010
19011    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19012        final PackageSetting ps;
19013        synchronized (mPackages) {
19014            ps = mSettings.mPackages.get(packageName);
19015            if (ps == null) {
19016                Slog.w(TAG, "Failed to find settings for " + packageName);
19017                return false;
19018            }
19019        }
19020
19021        final String[] packageNames = { packageName };
19022        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19023        final String[] codePaths = { ps.codePathString };
19024
19025        try {
19026            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19027                    ps.appId, ceDataInodes, codePaths, stats);
19028
19029            // For now, ignore code size of packages on system partition
19030            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19031                stats.codeSize = 0;
19032            }
19033
19034            // External clients expect these to be tracked separately
19035            stats.dataSize -= stats.cacheSize;
19036
19037        } catch (InstallerException e) {
19038            Slog.w(TAG, String.valueOf(e));
19039            return false;
19040        }
19041
19042        return true;
19043    }
19044
19045    private int getUidTargetSdkVersionLockedLPr(int uid) {
19046        Object obj = mSettings.getUserIdLPr(uid);
19047        if (obj instanceof SharedUserSetting) {
19048            final SharedUserSetting sus = (SharedUserSetting) obj;
19049            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19050            final Iterator<PackageSetting> it = sus.packages.iterator();
19051            while (it.hasNext()) {
19052                final PackageSetting ps = it.next();
19053                if (ps.pkg != null) {
19054                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19055                    if (v < vers) vers = v;
19056                }
19057            }
19058            return vers;
19059        } else if (obj instanceof PackageSetting) {
19060            final PackageSetting ps = (PackageSetting) obj;
19061            if (ps.pkg != null) {
19062                return ps.pkg.applicationInfo.targetSdkVersion;
19063            }
19064        }
19065        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19066    }
19067
19068    @Override
19069    public void addPreferredActivity(IntentFilter filter, int match,
19070            ComponentName[] set, ComponentName activity, int userId) {
19071        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19072                "Adding preferred");
19073    }
19074
19075    private void addPreferredActivityInternal(IntentFilter filter, int match,
19076            ComponentName[] set, ComponentName activity, boolean always, int userId,
19077            String opname) {
19078        // writer
19079        int callingUid = Binder.getCallingUid();
19080        enforceCrossUserPermission(callingUid, userId,
19081                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19082        if (filter.countActions() == 0) {
19083            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19084            return;
19085        }
19086        synchronized (mPackages) {
19087            if (mContext.checkCallingOrSelfPermission(
19088                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19089                    != PackageManager.PERMISSION_GRANTED) {
19090                if (getUidTargetSdkVersionLockedLPr(callingUid)
19091                        < Build.VERSION_CODES.FROYO) {
19092                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19093                            + callingUid);
19094                    return;
19095                }
19096                mContext.enforceCallingOrSelfPermission(
19097                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19098            }
19099
19100            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19101            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19102                    + userId + ":");
19103            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19104            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19105            scheduleWritePackageRestrictionsLocked(userId);
19106            postPreferredActivityChangedBroadcast(userId);
19107        }
19108    }
19109
19110    private void postPreferredActivityChangedBroadcast(int userId) {
19111        mHandler.post(() -> {
19112            final IActivityManager am = ActivityManager.getService();
19113            if (am == null) {
19114                return;
19115            }
19116
19117            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19118            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19119            try {
19120                am.broadcastIntent(null, intent, null, null,
19121                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19122                        null, false, false, userId);
19123            } catch (RemoteException e) {
19124            }
19125        });
19126    }
19127
19128    @Override
19129    public void replacePreferredActivity(IntentFilter filter, int match,
19130            ComponentName[] set, ComponentName activity, int userId) {
19131        if (filter.countActions() != 1) {
19132            throw new IllegalArgumentException(
19133                    "replacePreferredActivity expects filter to have only 1 action.");
19134        }
19135        if (filter.countDataAuthorities() != 0
19136                || filter.countDataPaths() != 0
19137                || filter.countDataSchemes() > 1
19138                || filter.countDataTypes() != 0) {
19139            throw new IllegalArgumentException(
19140                    "replacePreferredActivity expects filter to have no data authorities, " +
19141                    "paths, or types; and at most one scheme.");
19142        }
19143
19144        final int callingUid = Binder.getCallingUid();
19145        enforceCrossUserPermission(callingUid, userId,
19146                true /* requireFullPermission */, false /* checkShell */,
19147                "replace preferred activity");
19148        synchronized (mPackages) {
19149            if (mContext.checkCallingOrSelfPermission(
19150                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19151                    != PackageManager.PERMISSION_GRANTED) {
19152                if (getUidTargetSdkVersionLockedLPr(callingUid)
19153                        < Build.VERSION_CODES.FROYO) {
19154                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19155                            + Binder.getCallingUid());
19156                    return;
19157                }
19158                mContext.enforceCallingOrSelfPermission(
19159                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19160            }
19161
19162            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19163            if (pir != null) {
19164                // Get all of the existing entries that exactly match this filter.
19165                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19166                if (existing != null && existing.size() == 1) {
19167                    PreferredActivity cur = existing.get(0);
19168                    if (DEBUG_PREFERRED) {
19169                        Slog.i(TAG, "Checking replace of preferred:");
19170                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19171                        if (!cur.mPref.mAlways) {
19172                            Slog.i(TAG, "  -- CUR; not mAlways!");
19173                        } else {
19174                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19175                            Slog.i(TAG, "  -- CUR: mSet="
19176                                    + Arrays.toString(cur.mPref.mSetComponents));
19177                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19178                            Slog.i(TAG, "  -- NEW: mMatch="
19179                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19180                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19181                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19182                        }
19183                    }
19184                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19185                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19186                            && cur.mPref.sameSet(set)) {
19187                        // Setting the preferred activity to what it happens to be already
19188                        if (DEBUG_PREFERRED) {
19189                            Slog.i(TAG, "Replacing with same preferred activity "
19190                                    + cur.mPref.mShortComponent + " for user "
19191                                    + userId + ":");
19192                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19193                        }
19194                        return;
19195                    }
19196                }
19197
19198                if (existing != null) {
19199                    if (DEBUG_PREFERRED) {
19200                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19201                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19202                    }
19203                    for (int i = 0; i < existing.size(); i++) {
19204                        PreferredActivity pa = existing.get(i);
19205                        if (DEBUG_PREFERRED) {
19206                            Slog.i(TAG, "Removing existing preferred activity "
19207                                    + pa.mPref.mComponent + ":");
19208                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19209                        }
19210                        pir.removeFilter(pa);
19211                    }
19212                }
19213            }
19214            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19215                    "Replacing preferred");
19216        }
19217    }
19218
19219    @Override
19220    public void clearPackagePreferredActivities(String packageName) {
19221        final int uid = Binder.getCallingUid();
19222        // writer
19223        synchronized (mPackages) {
19224            PackageParser.Package pkg = mPackages.get(packageName);
19225            if (pkg == null || pkg.applicationInfo.uid != uid) {
19226                if (mContext.checkCallingOrSelfPermission(
19227                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19228                        != PackageManager.PERMISSION_GRANTED) {
19229                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
19230                            < Build.VERSION_CODES.FROYO) {
19231                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19232                                + Binder.getCallingUid());
19233                        return;
19234                    }
19235                    mContext.enforceCallingOrSelfPermission(
19236                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19237                }
19238            }
19239
19240            int user = UserHandle.getCallingUserId();
19241            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19242                scheduleWritePackageRestrictionsLocked(user);
19243            }
19244        }
19245    }
19246
19247    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19248    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19249        ArrayList<PreferredActivity> removed = null;
19250        boolean changed = false;
19251        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19252            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19253            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19254            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19255                continue;
19256            }
19257            Iterator<PreferredActivity> it = pir.filterIterator();
19258            while (it.hasNext()) {
19259                PreferredActivity pa = it.next();
19260                // Mark entry for removal only if it matches the package name
19261                // and the entry is of type "always".
19262                if (packageName == null ||
19263                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19264                                && pa.mPref.mAlways)) {
19265                    if (removed == null) {
19266                        removed = new ArrayList<PreferredActivity>();
19267                    }
19268                    removed.add(pa);
19269                }
19270            }
19271            if (removed != null) {
19272                for (int j=0; j<removed.size(); j++) {
19273                    PreferredActivity pa = removed.get(j);
19274                    pir.removeFilter(pa);
19275                }
19276                changed = true;
19277            }
19278        }
19279        if (changed) {
19280            postPreferredActivityChangedBroadcast(userId);
19281        }
19282        return changed;
19283    }
19284
19285    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19286    private void clearIntentFilterVerificationsLPw(int userId) {
19287        final int packageCount = mPackages.size();
19288        for (int i = 0; i < packageCount; i++) {
19289            PackageParser.Package pkg = mPackages.valueAt(i);
19290            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19291        }
19292    }
19293
19294    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19295    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19296        if (userId == UserHandle.USER_ALL) {
19297            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19298                    sUserManager.getUserIds())) {
19299                for (int oneUserId : sUserManager.getUserIds()) {
19300                    scheduleWritePackageRestrictionsLocked(oneUserId);
19301                }
19302            }
19303        } else {
19304            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19305                scheduleWritePackageRestrictionsLocked(userId);
19306            }
19307        }
19308    }
19309
19310    /** Clears state for all users, and touches intent filter verification policy */
19311    void clearDefaultBrowserIfNeeded(String packageName) {
19312        for (int oneUserId : sUserManager.getUserIds()) {
19313            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19314        }
19315    }
19316
19317    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19318        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19319        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19320            if (packageName.equals(defaultBrowserPackageName)) {
19321                setDefaultBrowserPackageName(null, userId);
19322            }
19323        }
19324    }
19325
19326    @Override
19327    public void resetApplicationPreferences(int userId) {
19328        mContext.enforceCallingOrSelfPermission(
19329                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19330        final long identity = Binder.clearCallingIdentity();
19331        // writer
19332        try {
19333            synchronized (mPackages) {
19334                clearPackagePreferredActivitiesLPw(null, userId);
19335                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19336                // TODO: We have to reset the default SMS and Phone. This requires
19337                // significant refactoring to keep all default apps in the package
19338                // manager (cleaner but more work) or have the services provide
19339                // callbacks to the package manager to request a default app reset.
19340                applyFactoryDefaultBrowserLPw(userId);
19341                clearIntentFilterVerificationsLPw(userId);
19342                primeDomainVerificationsLPw(userId);
19343                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19344                scheduleWritePackageRestrictionsLocked(userId);
19345            }
19346            resetNetworkPolicies(userId);
19347        } finally {
19348            Binder.restoreCallingIdentity(identity);
19349        }
19350    }
19351
19352    @Override
19353    public int getPreferredActivities(List<IntentFilter> outFilters,
19354            List<ComponentName> outActivities, String packageName) {
19355
19356        int num = 0;
19357        final int userId = UserHandle.getCallingUserId();
19358        // reader
19359        synchronized (mPackages) {
19360            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19361            if (pir != null) {
19362                final Iterator<PreferredActivity> it = pir.filterIterator();
19363                while (it.hasNext()) {
19364                    final PreferredActivity pa = it.next();
19365                    if (packageName == null
19366                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19367                                    && pa.mPref.mAlways)) {
19368                        if (outFilters != null) {
19369                            outFilters.add(new IntentFilter(pa));
19370                        }
19371                        if (outActivities != null) {
19372                            outActivities.add(pa.mPref.mComponent);
19373                        }
19374                    }
19375                }
19376            }
19377        }
19378
19379        return num;
19380    }
19381
19382    @Override
19383    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19384            int userId) {
19385        int callingUid = Binder.getCallingUid();
19386        if (callingUid != Process.SYSTEM_UID) {
19387            throw new SecurityException(
19388                    "addPersistentPreferredActivity can only be run by the system");
19389        }
19390        if (filter.countActions() == 0) {
19391            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19392            return;
19393        }
19394        synchronized (mPackages) {
19395            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19396                    ":");
19397            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19398            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19399                    new PersistentPreferredActivity(filter, activity));
19400            scheduleWritePackageRestrictionsLocked(userId);
19401            postPreferredActivityChangedBroadcast(userId);
19402        }
19403    }
19404
19405    @Override
19406    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19407        int callingUid = Binder.getCallingUid();
19408        if (callingUid != Process.SYSTEM_UID) {
19409            throw new SecurityException(
19410                    "clearPackagePersistentPreferredActivities can only be run by the system");
19411        }
19412        ArrayList<PersistentPreferredActivity> removed = null;
19413        boolean changed = false;
19414        synchronized (mPackages) {
19415            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19416                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19417                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19418                        .valueAt(i);
19419                if (userId != thisUserId) {
19420                    continue;
19421                }
19422                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19423                while (it.hasNext()) {
19424                    PersistentPreferredActivity ppa = it.next();
19425                    // Mark entry for removal only if it matches the package name.
19426                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19427                        if (removed == null) {
19428                            removed = new ArrayList<PersistentPreferredActivity>();
19429                        }
19430                        removed.add(ppa);
19431                    }
19432                }
19433                if (removed != null) {
19434                    for (int j=0; j<removed.size(); j++) {
19435                        PersistentPreferredActivity ppa = removed.get(j);
19436                        ppir.removeFilter(ppa);
19437                    }
19438                    changed = true;
19439                }
19440            }
19441
19442            if (changed) {
19443                scheduleWritePackageRestrictionsLocked(userId);
19444                postPreferredActivityChangedBroadcast(userId);
19445            }
19446        }
19447    }
19448
19449    /**
19450     * Common machinery for picking apart a restored XML blob and passing
19451     * it to a caller-supplied functor to be applied to the running system.
19452     */
19453    private void restoreFromXml(XmlPullParser parser, int userId,
19454            String expectedStartTag, BlobXmlRestorer functor)
19455            throws IOException, XmlPullParserException {
19456        int type;
19457        while ((type = parser.next()) != XmlPullParser.START_TAG
19458                && type != XmlPullParser.END_DOCUMENT) {
19459        }
19460        if (type != XmlPullParser.START_TAG) {
19461            // oops didn't find a start tag?!
19462            if (DEBUG_BACKUP) {
19463                Slog.e(TAG, "Didn't find start tag during restore");
19464            }
19465            return;
19466        }
19467Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19468        // this is supposed to be TAG_PREFERRED_BACKUP
19469        if (!expectedStartTag.equals(parser.getName())) {
19470            if (DEBUG_BACKUP) {
19471                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19472            }
19473            return;
19474        }
19475
19476        // skip interfering stuff, then we're aligned with the backing implementation
19477        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19478Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19479        functor.apply(parser, userId);
19480    }
19481
19482    private interface BlobXmlRestorer {
19483        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19484    }
19485
19486    /**
19487     * Non-Binder method, support for the backup/restore mechanism: write the
19488     * full set of preferred activities in its canonical XML format.  Returns the
19489     * XML output as a byte array, or null if there is none.
19490     */
19491    @Override
19492    public byte[] getPreferredActivityBackup(int userId) {
19493        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19494            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19495        }
19496
19497        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19498        try {
19499            final XmlSerializer serializer = new FastXmlSerializer();
19500            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19501            serializer.startDocument(null, true);
19502            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19503
19504            synchronized (mPackages) {
19505                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19506            }
19507
19508            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19509            serializer.endDocument();
19510            serializer.flush();
19511        } catch (Exception e) {
19512            if (DEBUG_BACKUP) {
19513                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19514            }
19515            return null;
19516        }
19517
19518        return dataStream.toByteArray();
19519    }
19520
19521    @Override
19522    public void restorePreferredActivities(byte[] backup, int userId) {
19523        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19524            throw new SecurityException("Only the system may call restorePreferredActivities()");
19525        }
19526
19527        try {
19528            final XmlPullParser parser = Xml.newPullParser();
19529            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19530            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19531                    new BlobXmlRestorer() {
19532                        @Override
19533                        public void apply(XmlPullParser parser, int userId)
19534                                throws XmlPullParserException, IOException {
19535                            synchronized (mPackages) {
19536                                mSettings.readPreferredActivitiesLPw(parser, userId);
19537                            }
19538                        }
19539                    } );
19540        } catch (Exception e) {
19541            if (DEBUG_BACKUP) {
19542                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19543            }
19544        }
19545    }
19546
19547    /**
19548     * Non-Binder method, support for the backup/restore mechanism: write the
19549     * default browser (etc) settings in its canonical XML format.  Returns the default
19550     * browser XML representation as a byte array, or null if there is none.
19551     */
19552    @Override
19553    public byte[] getDefaultAppsBackup(int userId) {
19554        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19555            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19556        }
19557
19558        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19559        try {
19560            final XmlSerializer serializer = new FastXmlSerializer();
19561            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19562            serializer.startDocument(null, true);
19563            serializer.startTag(null, TAG_DEFAULT_APPS);
19564
19565            synchronized (mPackages) {
19566                mSettings.writeDefaultAppsLPr(serializer, userId);
19567            }
19568
19569            serializer.endTag(null, TAG_DEFAULT_APPS);
19570            serializer.endDocument();
19571            serializer.flush();
19572        } catch (Exception e) {
19573            if (DEBUG_BACKUP) {
19574                Slog.e(TAG, "Unable to write default apps for backup", e);
19575            }
19576            return null;
19577        }
19578
19579        return dataStream.toByteArray();
19580    }
19581
19582    @Override
19583    public void restoreDefaultApps(byte[] backup, int userId) {
19584        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19585            throw new SecurityException("Only the system may call restoreDefaultApps()");
19586        }
19587
19588        try {
19589            final XmlPullParser parser = Xml.newPullParser();
19590            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19591            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19592                    new BlobXmlRestorer() {
19593                        @Override
19594                        public void apply(XmlPullParser parser, int userId)
19595                                throws XmlPullParserException, IOException {
19596                            synchronized (mPackages) {
19597                                mSettings.readDefaultAppsLPw(parser, userId);
19598                            }
19599                        }
19600                    } );
19601        } catch (Exception e) {
19602            if (DEBUG_BACKUP) {
19603                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19604            }
19605        }
19606    }
19607
19608    @Override
19609    public byte[] getIntentFilterVerificationBackup(int userId) {
19610        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19611            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19612        }
19613
19614        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19615        try {
19616            final XmlSerializer serializer = new FastXmlSerializer();
19617            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19618            serializer.startDocument(null, true);
19619            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19620
19621            synchronized (mPackages) {
19622                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19623            }
19624
19625            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19626            serializer.endDocument();
19627            serializer.flush();
19628        } catch (Exception e) {
19629            if (DEBUG_BACKUP) {
19630                Slog.e(TAG, "Unable to write default apps for backup", e);
19631            }
19632            return null;
19633        }
19634
19635        return dataStream.toByteArray();
19636    }
19637
19638    @Override
19639    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19640        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19641            throw new SecurityException("Only the system may call restorePreferredActivities()");
19642        }
19643
19644        try {
19645            final XmlPullParser parser = Xml.newPullParser();
19646            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19647            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19648                    new BlobXmlRestorer() {
19649                        @Override
19650                        public void apply(XmlPullParser parser, int userId)
19651                                throws XmlPullParserException, IOException {
19652                            synchronized (mPackages) {
19653                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19654                                mSettings.writeLPr();
19655                            }
19656                        }
19657                    } );
19658        } catch (Exception e) {
19659            if (DEBUG_BACKUP) {
19660                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19661            }
19662        }
19663    }
19664
19665    @Override
19666    public byte[] getPermissionGrantBackup(int userId) {
19667        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19668            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19669        }
19670
19671        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19672        try {
19673            final XmlSerializer serializer = new FastXmlSerializer();
19674            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19675            serializer.startDocument(null, true);
19676            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19677
19678            synchronized (mPackages) {
19679                serializeRuntimePermissionGrantsLPr(serializer, userId);
19680            }
19681
19682            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19683            serializer.endDocument();
19684            serializer.flush();
19685        } catch (Exception e) {
19686            if (DEBUG_BACKUP) {
19687                Slog.e(TAG, "Unable to write default apps for backup", e);
19688            }
19689            return null;
19690        }
19691
19692        return dataStream.toByteArray();
19693    }
19694
19695    @Override
19696    public void restorePermissionGrants(byte[] backup, int userId) {
19697        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19698            throw new SecurityException("Only the system may call restorePermissionGrants()");
19699        }
19700
19701        try {
19702            final XmlPullParser parser = Xml.newPullParser();
19703            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19704            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19705                    new BlobXmlRestorer() {
19706                        @Override
19707                        public void apply(XmlPullParser parser, int userId)
19708                                throws XmlPullParserException, IOException {
19709                            synchronized (mPackages) {
19710                                processRestoredPermissionGrantsLPr(parser, userId);
19711                            }
19712                        }
19713                    } );
19714        } catch (Exception e) {
19715            if (DEBUG_BACKUP) {
19716                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19717            }
19718        }
19719    }
19720
19721    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19722            throws IOException {
19723        serializer.startTag(null, TAG_ALL_GRANTS);
19724
19725        final int N = mSettings.mPackages.size();
19726        for (int i = 0; i < N; i++) {
19727            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19728            boolean pkgGrantsKnown = false;
19729
19730            PermissionsState packagePerms = ps.getPermissionsState();
19731
19732            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19733                final int grantFlags = state.getFlags();
19734                // only look at grants that are not system/policy fixed
19735                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19736                    final boolean isGranted = state.isGranted();
19737                    // And only back up the user-twiddled state bits
19738                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19739                        final String packageName = mSettings.mPackages.keyAt(i);
19740                        if (!pkgGrantsKnown) {
19741                            serializer.startTag(null, TAG_GRANT);
19742                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19743                            pkgGrantsKnown = true;
19744                        }
19745
19746                        final boolean userSet =
19747                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19748                        final boolean userFixed =
19749                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19750                        final boolean revoke =
19751                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19752
19753                        serializer.startTag(null, TAG_PERMISSION);
19754                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19755                        if (isGranted) {
19756                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19757                        }
19758                        if (userSet) {
19759                            serializer.attribute(null, ATTR_USER_SET, "true");
19760                        }
19761                        if (userFixed) {
19762                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19763                        }
19764                        if (revoke) {
19765                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19766                        }
19767                        serializer.endTag(null, TAG_PERMISSION);
19768                    }
19769                }
19770            }
19771
19772            if (pkgGrantsKnown) {
19773                serializer.endTag(null, TAG_GRANT);
19774            }
19775        }
19776
19777        serializer.endTag(null, TAG_ALL_GRANTS);
19778    }
19779
19780    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19781            throws XmlPullParserException, IOException {
19782        String pkgName = null;
19783        int outerDepth = parser.getDepth();
19784        int type;
19785        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19786                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19787            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19788                continue;
19789            }
19790
19791            final String tagName = parser.getName();
19792            if (tagName.equals(TAG_GRANT)) {
19793                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19794                if (DEBUG_BACKUP) {
19795                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19796                }
19797            } else if (tagName.equals(TAG_PERMISSION)) {
19798
19799                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19800                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19801
19802                int newFlagSet = 0;
19803                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19804                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19805                }
19806                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19807                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19808                }
19809                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19810                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19811                }
19812                if (DEBUG_BACKUP) {
19813                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19814                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19815                }
19816                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19817                if (ps != null) {
19818                    // Already installed so we apply the grant immediately
19819                    if (DEBUG_BACKUP) {
19820                        Slog.v(TAG, "        + already installed; applying");
19821                    }
19822                    PermissionsState perms = ps.getPermissionsState();
19823                    BasePermission bp = mSettings.mPermissions.get(permName);
19824                    if (bp != null) {
19825                        if (isGranted) {
19826                            perms.grantRuntimePermission(bp, userId);
19827                        }
19828                        if (newFlagSet != 0) {
19829                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19830                        }
19831                    }
19832                } else {
19833                    // Need to wait for post-restore install to apply the grant
19834                    if (DEBUG_BACKUP) {
19835                        Slog.v(TAG, "        - not yet installed; saving for later");
19836                    }
19837                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19838                            isGranted, newFlagSet, userId);
19839                }
19840            } else {
19841                PackageManagerService.reportSettingsProblem(Log.WARN,
19842                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19843                XmlUtils.skipCurrentTag(parser);
19844            }
19845        }
19846
19847        scheduleWriteSettingsLocked();
19848        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19849    }
19850
19851    @Override
19852    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19853            int sourceUserId, int targetUserId, int flags) {
19854        mContext.enforceCallingOrSelfPermission(
19855                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19856        int callingUid = Binder.getCallingUid();
19857        enforceOwnerRights(ownerPackage, callingUid);
19858        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19859        if (intentFilter.countActions() == 0) {
19860            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19861            return;
19862        }
19863        synchronized (mPackages) {
19864            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19865                    ownerPackage, targetUserId, flags);
19866            CrossProfileIntentResolver resolver =
19867                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19868            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19869            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19870            if (existing != null) {
19871                int size = existing.size();
19872                for (int i = 0; i < size; i++) {
19873                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19874                        return;
19875                    }
19876                }
19877            }
19878            resolver.addFilter(newFilter);
19879            scheduleWritePackageRestrictionsLocked(sourceUserId);
19880        }
19881    }
19882
19883    @Override
19884    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19885        mContext.enforceCallingOrSelfPermission(
19886                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19887        int callingUid = Binder.getCallingUid();
19888        enforceOwnerRights(ownerPackage, callingUid);
19889        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19890        synchronized (mPackages) {
19891            CrossProfileIntentResolver resolver =
19892                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19893            ArraySet<CrossProfileIntentFilter> set =
19894                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19895            for (CrossProfileIntentFilter filter : set) {
19896                if (filter.getOwnerPackage().equals(ownerPackage)) {
19897                    resolver.removeFilter(filter);
19898                }
19899            }
19900            scheduleWritePackageRestrictionsLocked(sourceUserId);
19901        }
19902    }
19903
19904    // Enforcing that callingUid is owning pkg on userId
19905    private void enforceOwnerRights(String pkg, int callingUid) {
19906        // The system owns everything.
19907        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19908            return;
19909        }
19910        int callingUserId = UserHandle.getUserId(callingUid);
19911        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19912        if (pi == null) {
19913            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19914                    + callingUserId);
19915        }
19916        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19917            throw new SecurityException("Calling uid " + callingUid
19918                    + " does not own package " + pkg);
19919        }
19920    }
19921
19922    @Override
19923    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19924        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19925    }
19926
19927    /**
19928     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19929     * then reports the most likely home activity or null if there are more than one.
19930     */
19931    public ComponentName getDefaultHomeActivity(int userId) {
19932        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19933        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19934        if (cn != null) {
19935            return cn;
19936        }
19937
19938        // Find the launcher with the highest priority and return that component if there are no
19939        // other home activity with the same priority.
19940        int lastPriority = Integer.MIN_VALUE;
19941        ComponentName lastComponent = null;
19942        final int size = allHomeCandidates.size();
19943        for (int i = 0; i < size; i++) {
19944            final ResolveInfo ri = allHomeCandidates.get(i);
19945            if (ri.priority > lastPriority) {
19946                lastComponent = ri.activityInfo.getComponentName();
19947                lastPriority = ri.priority;
19948            } else if (ri.priority == lastPriority) {
19949                // Two components found with same priority.
19950                lastComponent = null;
19951            }
19952        }
19953        return lastComponent;
19954    }
19955
19956    private Intent getHomeIntent() {
19957        Intent intent = new Intent(Intent.ACTION_MAIN);
19958        intent.addCategory(Intent.CATEGORY_HOME);
19959        intent.addCategory(Intent.CATEGORY_DEFAULT);
19960        return intent;
19961    }
19962
19963    private IntentFilter getHomeFilter() {
19964        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19965        filter.addCategory(Intent.CATEGORY_HOME);
19966        filter.addCategory(Intent.CATEGORY_DEFAULT);
19967        return filter;
19968    }
19969
19970    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19971            int userId) {
19972        Intent intent  = getHomeIntent();
19973        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19974                PackageManager.GET_META_DATA, userId);
19975        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19976                true, false, false, userId);
19977
19978        allHomeCandidates.clear();
19979        if (list != null) {
19980            for (ResolveInfo ri : list) {
19981                allHomeCandidates.add(ri);
19982            }
19983        }
19984        return (preferred == null || preferred.activityInfo == null)
19985                ? null
19986                : new ComponentName(preferred.activityInfo.packageName,
19987                        preferred.activityInfo.name);
19988    }
19989
19990    @Override
19991    public void setHomeActivity(ComponentName comp, int userId) {
19992        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19993        getHomeActivitiesAsUser(homeActivities, userId);
19994
19995        boolean found = false;
19996
19997        final int size = homeActivities.size();
19998        final ComponentName[] set = new ComponentName[size];
19999        for (int i = 0; i < size; i++) {
20000            final ResolveInfo candidate = homeActivities.get(i);
20001            final ActivityInfo info = candidate.activityInfo;
20002            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20003            set[i] = activityName;
20004            if (!found && activityName.equals(comp)) {
20005                found = true;
20006            }
20007        }
20008        if (!found) {
20009            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20010                    + userId);
20011        }
20012        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20013                set, comp, userId);
20014    }
20015
20016    private @Nullable String getSetupWizardPackageName() {
20017        final Intent intent = new Intent(Intent.ACTION_MAIN);
20018        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20019
20020        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20021                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20022                        | MATCH_DISABLED_COMPONENTS,
20023                UserHandle.myUserId());
20024        if (matches.size() == 1) {
20025            return matches.get(0).getComponentInfo().packageName;
20026        } else {
20027            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20028                    + ": matches=" + matches);
20029            return null;
20030        }
20031    }
20032
20033    private @Nullable String getStorageManagerPackageName() {
20034        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20035
20036        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20037                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20038                        | MATCH_DISABLED_COMPONENTS,
20039                UserHandle.myUserId());
20040        if (matches.size() == 1) {
20041            return matches.get(0).getComponentInfo().packageName;
20042        } else {
20043            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20044                    + matches.size() + ": matches=" + matches);
20045            return null;
20046        }
20047    }
20048
20049    @Override
20050    public void setApplicationEnabledSetting(String appPackageName,
20051            int newState, int flags, int userId, String callingPackage) {
20052        if (!sUserManager.exists(userId)) return;
20053        if (callingPackage == null) {
20054            callingPackage = Integer.toString(Binder.getCallingUid());
20055        }
20056        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20057    }
20058
20059    @Override
20060    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20061        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20062        synchronized (mPackages) {
20063            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20064            if (pkgSetting != null) {
20065                pkgSetting.setUpdateAvailable(updateAvailable);
20066            }
20067        }
20068    }
20069
20070    @Override
20071    public void setComponentEnabledSetting(ComponentName componentName,
20072            int newState, int flags, int userId) {
20073        if (!sUserManager.exists(userId)) return;
20074        setEnabledSetting(componentName.getPackageName(),
20075                componentName.getClassName(), newState, flags, userId, null);
20076    }
20077
20078    private void setEnabledSetting(final String packageName, String className, int newState,
20079            final int flags, int userId, String callingPackage) {
20080        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20081              || newState == COMPONENT_ENABLED_STATE_ENABLED
20082              || newState == COMPONENT_ENABLED_STATE_DISABLED
20083              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20084              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20085            throw new IllegalArgumentException("Invalid new component state: "
20086                    + newState);
20087        }
20088        PackageSetting pkgSetting;
20089        final int uid = Binder.getCallingUid();
20090        final int permission;
20091        if (uid == Process.SYSTEM_UID) {
20092            permission = PackageManager.PERMISSION_GRANTED;
20093        } else {
20094            permission = mContext.checkCallingOrSelfPermission(
20095                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20096        }
20097        enforceCrossUserPermission(uid, userId,
20098                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20099        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20100        boolean sendNow = false;
20101        boolean isApp = (className == null);
20102        String componentName = isApp ? packageName : className;
20103        int packageUid = -1;
20104        ArrayList<String> components;
20105
20106        // writer
20107        synchronized (mPackages) {
20108            pkgSetting = mSettings.mPackages.get(packageName);
20109            if (pkgSetting == null) {
20110                if (className == null) {
20111                    throw new IllegalArgumentException("Unknown package: " + packageName);
20112                }
20113                throw new IllegalArgumentException(
20114                        "Unknown component: " + packageName + "/" + className);
20115            }
20116        }
20117
20118        // Limit who can change which apps
20119        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
20120            // Don't allow apps that don't have permission to modify other apps
20121            if (!allowedByPermission) {
20122                throw new SecurityException(
20123                        "Permission Denial: attempt to change component state from pid="
20124                        + Binder.getCallingPid()
20125                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
20126            }
20127            // Don't allow changing protected packages.
20128            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20129                throw new SecurityException("Cannot disable a protected package: " + packageName);
20130            }
20131        }
20132
20133        synchronized (mPackages) {
20134            if (uid == Process.SHELL_UID
20135                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20136                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20137                // unless it is a test package.
20138                int oldState = pkgSetting.getEnabled(userId);
20139                if (className == null
20140                    &&
20141                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20142                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20143                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20144                    &&
20145                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20146                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20147                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20148                    // ok
20149                } else {
20150                    throw new SecurityException(
20151                            "Shell cannot change component state for " + packageName + "/"
20152                            + className + " to " + newState);
20153                }
20154            }
20155            if (className == null) {
20156                // We're dealing with an application/package level state change
20157                if (pkgSetting.getEnabled(userId) == newState) {
20158                    // Nothing to do
20159                    return;
20160                }
20161                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20162                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20163                    // Don't care about who enables an app.
20164                    callingPackage = null;
20165                }
20166                pkgSetting.setEnabled(newState, userId, callingPackage);
20167                // pkgSetting.pkg.mSetEnabled = newState;
20168            } else {
20169                // We're dealing with a component level state change
20170                // First, verify that this is a valid class name.
20171                PackageParser.Package pkg = pkgSetting.pkg;
20172                if (pkg == null || !pkg.hasComponentClassName(className)) {
20173                    if (pkg != null &&
20174                            pkg.applicationInfo.targetSdkVersion >=
20175                                    Build.VERSION_CODES.JELLY_BEAN) {
20176                        throw new IllegalArgumentException("Component class " + className
20177                                + " does not exist in " + packageName);
20178                    } else {
20179                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20180                                + className + " does not exist in " + packageName);
20181                    }
20182                }
20183                switch (newState) {
20184                case COMPONENT_ENABLED_STATE_ENABLED:
20185                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20186                        return;
20187                    }
20188                    break;
20189                case COMPONENT_ENABLED_STATE_DISABLED:
20190                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20191                        return;
20192                    }
20193                    break;
20194                case COMPONENT_ENABLED_STATE_DEFAULT:
20195                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20196                        return;
20197                    }
20198                    break;
20199                default:
20200                    Slog.e(TAG, "Invalid new component state: " + newState);
20201                    return;
20202                }
20203            }
20204            scheduleWritePackageRestrictionsLocked(userId);
20205            updateSequenceNumberLP(packageName, new int[] { userId });
20206            final long callingId = Binder.clearCallingIdentity();
20207            try {
20208                updateInstantAppInstallerLocked(packageName);
20209            } finally {
20210                Binder.restoreCallingIdentity(callingId);
20211            }
20212            components = mPendingBroadcasts.get(userId, packageName);
20213            final boolean newPackage = components == null;
20214            if (newPackage) {
20215                components = new ArrayList<String>();
20216            }
20217            if (!components.contains(componentName)) {
20218                components.add(componentName);
20219            }
20220            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20221                sendNow = true;
20222                // Purge entry from pending broadcast list if another one exists already
20223                // since we are sending one right away.
20224                mPendingBroadcasts.remove(userId, packageName);
20225            } else {
20226                if (newPackage) {
20227                    mPendingBroadcasts.put(userId, packageName, components);
20228                }
20229                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20230                    // Schedule a message
20231                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20232                }
20233            }
20234        }
20235
20236        long callingId = Binder.clearCallingIdentity();
20237        try {
20238            if (sendNow) {
20239                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20240                sendPackageChangedBroadcast(packageName,
20241                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20242            }
20243        } finally {
20244            Binder.restoreCallingIdentity(callingId);
20245        }
20246    }
20247
20248    @Override
20249    public void flushPackageRestrictionsAsUser(int userId) {
20250        if (!sUserManager.exists(userId)) {
20251            return;
20252        }
20253        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20254                false /* checkShell */, "flushPackageRestrictions");
20255        synchronized (mPackages) {
20256            mSettings.writePackageRestrictionsLPr(userId);
20257            mDirtyUsers.remove(userId);
20258            if (mDirtyUsers.isEmpty()) {
20259                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20260            }
20261        }
20262    }
20263
20264    private void sendPackageChangedBroadcast(String packageName,
20265            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20266        if (DEBUG_INSTALL)
20267            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20268                    + componentNames);
20269        Bundle extras = new Bundle(4);
20270        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20271        String nameList[] = new String[componentNames.size()];
20272        componentNames.toArray(nameList);
20273        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20274        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20275        extras.putInt(Intent.EXTRA_UID, packageUid);
20276        // If this is not reporting a change of the overall package, then only send it
20277        // to registered receivers.  We don't want to launch a swath of apps for every
20278        // little component state change.
20279        final int flags = !componentNames.contains(packageName)
20280                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20281        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20282                new int[] {UserHandle.getUserId(packageUid)});
20283    }
20284
20285    @Override
20286    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20287        if (!sUserManager.exists(userId)) return;
20288        final int uid = Binder.getCallingUid();
20289        final int permission = mContext.checkCallingOrSelfPermission(
20290                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20291        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20292        enforceCrossUserPermission(uid, userId,
20293                true /* requireFullPermission */, true /* checkShell */, "stop package");
20294        // writer
20295        synchronized (mPackages) {
20296            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20297                    allowedByPermission, uid, userId)) {
20298                scheduleWritePackageRestrictionsLocked(userId);
20299            }
20300        }
20301    }
20302
20303    @Override
20304    public String getInstallerPackageName(String packageName) {
20305        // reader
20306        synchronized (mPackages) {
20307            return mSettings.getInstallerPackageNameLPr(packageName);
20308        }
20309    }
20310
20311    public boolean isOrphaned(String packageName) {
20312        // reader
20313        synchronized (mPackages) {
20314            return mSettings.isOrphaned(packageName);
20315        }
20316    }
20317
20318    @Override
20319    public int getApplicationEnabledSetting(String packageName, int userId) {
20320        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20321        int uid = Binder.getCallingUid();
20322        enforceCrossUserPermission(uid, userId,
20323                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20324        // reader
20325        synchronized (mPackages) {
20326            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20327        }
20328    }
20329
20330    @Override
20331    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20332        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20333        int uid = Binder.getCallingUid();
20334        enforceCrossUserPermission(uid, userId,
20335                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20336        // reader
20337        synchronized (mPackages) {
20338            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20339        }
20340    }
20341
20342    @Override
20343    public void enterSafeMode() {
20344        enforceSystemOrRoot("Only the system can request entering safe mode");
20345
20346        if (!mSystemReady) {
20347            mSafeMode = true;
20348        }
20349    }
20350
20351    @Override
20352    public void systemReady() {
20353        mSystemReady = true;
20354        final ContentResolver resolver = mContext.getContentResolver();
20355        ContentObserver co = new ContentObserver(mHandler) {
20356            @Override
20357            public void onChange(boolean selfChange) {
20358                mEphemeralAppsDisabled =
20359                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20360                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20361            }
20362        };
20363        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20364                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20365                false, co, UserHandle.USER_SYSTEM);
20366        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20367                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20368        co.onChange(true);
20369
20370        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20371        // disabled after already being started.
20372        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20373                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20374
20375        // Read the compatibilty setting when the system is ready.
20376        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20377                mContext.getContentResolver(),
20378                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20379        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20380        if (DEBUG_SETTINGS) {
20381            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20382        }
20383
20384        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20385
20386        synchronized (mPackages) {
20387            // Verify that all of the preferred activity components actually
20388            // exist.  It is possible for applications to be updated and at
20389            // that point remove a previously declared activity component that
20390            // had been set as a preferred activity.  We try to clean this up
20391            // the next time we encounter that preferred activity, but it is
20392            // possible for the user flow to never be able to return to that
20393            // situation so here we do a sanity check to make sure we haven't
20394            // left any junk around.
20395            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20396            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20397                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20398                removed.clear();
20399                for (PreferredActivity pa : pir.filterSet()) {
20400                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20401                        removed.add(pa);
20402                    }
20403                }
20404                if (removed.size() > 0) {
20405                    for (int r=0; r<removed.size(); r++) {
20406                        PreferredActivity pa = removed.get(r);
20407                        Slog.w(TAG, "Removing dangling preferred activity: "
20408                                + pa.mPref.mComponent);
20409                        pir.removeFilter(pa);
20410                    }
20411                    mSettings.writePackageRestrictionsLPr(
20412                            mSettings.mPreferredActivities.keyAt(i));
20413                }
20414            }
20415
20416            for (int userId : UserManagerService.getInstance().getUserIds()) {
20417                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20418                    grantPermissionsUserIds = ArrayUtils.appendInt(
20419                            grantPermissionsUserIds, userId);
20420                }
20421            }
20422        }
20423        sUserManager.systemReady();
20424
20425        // If we upgraded grant all default permissions before kicking off.
20426        for (int userId : grantPermissionsUserIds) {
20427            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20428        }
20429
20430        // If we did not grant default permissions, we preload from this the
20431        // default permission exceptions lazily to ensure we don't hit the
20432        // disk on a new user creation.
20433        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20434            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20435        }
20436
20437        // Kick off any messages waiting for system ready
20438        if (mPostSystemReadyMessages != null) {
20439            for (Message msg : mPostSystemReadyMessages) {
20440                msg.sendToTarget();
20441            }
20442            mPostSystemReadyMessages = null;
20443        }
20444
20445        // Watch for external volumes that come and go over time
20446        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20447        storage.registerListener(mStorageListener);
20448
20449        mInstallerService.systemReady();
20450        mPackageDexOptimizer.systemReady();
20451
20452        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20453                StorageManagerInternal.class);
20454        StorageManagerInternal.addExternalStoragePolicy(
20455                new StorageManagerInternal.ExternalStorageMountPolicy() {
20456            @Override
20457            public int getMountMode(int uid, String packageName) {
20458                if (Process.isIsolated(uid)) {
20459                    return Zygote.MOUNT_EXTERNAL_NONE;
20460                }
20461                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20462                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20463                }
20464                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20465                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20466                }
20467                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20468                    return Zygote.MOUNT_EXTERNAL_READ;
20469                }
20470                return Zygote.MOUNT_EXTERNAL_WRITE;
20471            }
20472
20473            @Override
20474            public boolean hasExternalStorage(int uid, String packageName) {
20475                return true;
20476            }
20477        });
20478
20479        // Now that we're mostly running, clean up stale users and apps
20480        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20481        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20482
20483        if (mPrivappPermissionsViolations != null) {
20484            Slog.wtf(TAG,"Signature|privileged permissions not in "
20485                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20486            mPrivappPermissionsViolations = null;
20487        }
20488    }
20489
20490    public void waitForAppDataPrepared() {
20491        if (mPrepareAppDataFuture == null) {
20492            return;
20493        }
20494        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20495        mPrepareAppDataFuture = null;
20496    }
20497
20498    @Override
20499    public boolean isSafeMode() {
20500        return mSafeMode;
20501    }
20502
20503    @Override
20504    public boolean hasSystemUidErrors() {
20505        return mHasSystemUidErrors;
20506    }
20507
20508    static String arrayToString(int[] array) {
20509        StringBuffer buf = new StringBuffer(128);
20510        buf.append('[');
20511        if (array != null) {
20512            for (int i=0; i<array.length; i++) {
20513                if (i > 0) buf.append(", ");
20514                buf.append(array[i]);
20515            }
20516        }
20517        buf.append(']');
20518        return buf.toString();
20519    }
20520
20521    static class DumpState {
20522        public static final int DUMP_LIBS = 1 << 0;
20523        public static final int DUMP_FEATURES = 1 << 1;
20524        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20525        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20526        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20527        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20528        public static final int DUMP_PERMISSIONS = 1 << 6;
20529        public static final int DUMP_PACKAGES = 1 << 7;
20530        public static final int DUMP_SHARED_USERS = 1 << 8;
20531        public static final int DUMP_MESSAGES = 1 << 9;
20532        public static final int DUMP_PROVIDERS = 1 << 10;
20533        public static final int DUMP_VERIFIERS = 1 << 11;
20534        public static final int DUMP_PREFERRED = 1 << 12;
20535        public static final int DUMP_PREFERRED_XML = 1 << 13;
20536        public static final int DUMP_KEYSETS = 1 << 14;
20537        public static final int DUMP_VERSION = 1 << 15;
20538        public static final int DUMP_INSTALLS = 1 << 16;
20539        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20540        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20541        public static final int DUMP_FROZEN = 1 << 19;
20542        public static final int DUMP_DEXOPT = 1 << 20;
20543        public static final int DUMP_COMPILER_STATS = 1 << 21;
20544        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20545
20546        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20547
20548        private int mTypes;
20549
20550        private int mOptions;
20551
20552        private boolean mTitlePrinted;
20553
20554        private SharedUserSetting mSharedUser;
20555
20556        public boolean isDumping(int type) {
20557            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20558                return true;
20559            }
20560
20561            return (mTypes & type) != 0;
20562        }
20563
20564        public void setDump(int type) {
20565            mTypes |= type;
20566        }
20567
20568        public boolean isOptionEnabled(int option) {
20569            return (mOptions & option) != 0;
20570        }
20571
20572        public void setOptionEnabled(int option) {
20573            mOptions |= option;
20574        }
20575
20576        public boolean onTitlePrinted() {
20577            final boolean printed = mTitlePrinted;
20578            mTitlePrinted = true;
20579            return printed;
20580        }
20581
20582        public boolean getTitlePrinted() {
20583            return mTitlePrinted;
20584        }
20585
20586        public void setTitlePrinted(boolean enabled) {
20587            mTitlePrinted = enabled;
20588        }
20589
20590        public SharedUserSetting getSharedUser() {
20591            return mSharedUser;
20592        }
20593
20594        public void setSharedUser(SharedUserSetting user) {
20595            mSharedUser = user;
20596        }
20597    }
20598
20599    @Override
20600    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20601            FileDescriptor err, String[] args, ShellCallback callback,
20602            ResultReceiver resultReceiver) {
20603        (new PackageManagerShellCommand(this)).exec(
20604                this, in, out, err, args, callback, resultReceiver);
20605    }
20606
20607    @Override
20608    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20609        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20610
20611        DumpState dumpState = new DumpState();
20612        boolean fullPreferred = false;
20613        boolean checkin = false;
20614
20615        String packageName = null;
20616        ArraySet<String> permissionNames = null;
20617
20618        int opti = 0;
20619        while (opti < args.length) {
20620            String opt = args[opti];
20621            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20622                break;
20623            }
20624            opti++;
20625
20626            if ("-a".equals(opt)) {
20627                // Right now we only know how to print all.
20628            } else if ("-h".equals(opt)) {
20629                pw.println("Package manager dump options:");
20630                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20631                pw.println("    --checkin: dump for a checkin");
20632                pw.println("    -f: print details of intent filters");
20633                pw.println("    -h: print this help");
20634                pw.println("  cmd may be one of:");
20635                pw.println("    l[ibraries]: list known shared libraries");
20636                pw.println("    f[eatures]: list device features");
20637                pw.println("    k[eysets]: print known keysets");
20638                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20639                pw.println("    perm[issions]: dump permissions");
20640                pw.println("    permission [name ...]: dump declaration and use of given permission");
20641                pw.println("    pref[erred]: print preferred package settings");
20642                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20643                pw.println("    prov[iders]: dump content providers");
20644                pw.println("    p[ackages]: dump installed packages");
20645                pw.println("    s[hared-users]: dump shared user IDs");
20646                pw.println("    m[essages]: print collected runtime messages");
20647                pw.println("    v[erifiers]: print package verifier info");
20648                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20649                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20650                pw.println("    version: print database version info");
20651                pw.println("    write: write current settings now");
20652                pw.println("    installs: details about install sessions");
20653                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20654                pw.println("    dexopt: dump dexopt state");
20655                pw.println("    compiler-stats: dump compiler statistics");
20656                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20657                pw.println("    <package.name>: info about given package");
20658                return;
20659            } else if ("--checkin".equals(opt)) {
20660                checkin = true;
20661            } else if ("-f".equals(opt)) {
20662                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20663            } else if ("--proto".equals(opt)) {
20664                dumpProto(fd);
20665                return;
20666            } else {
20667                pw.println("Unknown argument: " + opt + "; use -h for help");
20668            }
20669        }
20670
20671        // Is the caller requesting to dump a particular piece of data?
20672        if (opti < args.length) {
20673            String cmd = args[opti];
20674            opti++;
20675            // Is this a package name?
20676            if ("android".equals(cmd) || cmd.contains(".")) {
20677                packageName = cmd;
20678                // When dumping a single package, we always dump all of its
20679                // filter information since the amount of data will be reasonable.
20680                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20681            } else if ("check-permission".equals(cmd)) {
20682                if (opti >= args.length) {
20683                    pw.println("Error: check-permission missing permission argument");
20684                    return;
20685                }
20686                String perm = args[opti];
20687                opti++;
20688                if (opti >= args.length) {
20689                    pw.println("Error: check-permission missing package argument");
20690                    return;
20691                }
20692
20693                String pkg = args[opti];
20694                opti++;
20695                int user = UserHandle.getUserId(Binder.getCallingUid());
20696                if (opti < args.length) {
20697                    try {
20698                        user = Integer.parseInt(args[opti]);
20699                    } catch (NumberFormatException e) {
20700                        pw.println("Error: check-permission user argument is not a number: "
20701                                + args[opti]);
20702                        return;
20703                    }
20704                }
20705
20706                // Normalize package name to handle renamed packages and static libs
20707                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20708
20709                pw.println(checkPermission(perm, pkg, user));
20710                return;
20711            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20712                dumpState.setDump(DumpState.DUMP_LIBS);
20713            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20714                dumpState.setDump(DumpState.DUMP_FEATURES);
20715            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20716                if (opti >= args.length) {
20717                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20718                            | DumpState.DUMP_SERVICE_RESOLVERS
20719                            | DumpState.DUMP_RECEIVER_RESOLVERS
20720                            | DumpState.DUMP_CONTENT_RESOLVERS);
20721                } else {
20722                    while (opti < args.length) {
20723                        String name = args[opti];
20724                        if ("a".equals(name) || "activity".equals(name)) {
20725                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20726                        } else if ("s".equals(name) || "service".equals(name)) {
20727                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20728                        } else if ("r".equals(name) || "receiver".equals(name)) {
20729                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20730                        } else if ("c".equals(name) || "content".equals(name)) {
20731                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20732                        } else {
20733                            pw.println("Error: unknown resolver table type: " + name);
20734                            return;
20735                        }
20736                        opti++;
20737                    }
20738                }
20739            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20740                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20741            } else if ("permission".equals(cmd)) {
20742                if (opti >= args.length) {
20743                    pw.println("Error: permission requires permission name");
20744                    return;
20745                }
20746                permissionNames = new ArraySet<>();
20747                while (opti < args.length) {
20748                    permissionNames.add(args[opti]);
20749                    opti++;
20750                }
20751                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20752                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20753            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20754                dumpState.setDump(DumpState.DUMP_PREFERRED);
20755            } else if ("preferred-xml".equals(cmd)) {
20756                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20757                if (opti < args.length && "--full".equals(args[opti])) {
20758                    fullPreferred = true;
20759                    opti++;
20760                }
20761            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20762                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20763            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20764                dumpState.setDump(DumpState.DUMP_PACKAGES);
20765            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20766                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20767            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20768                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20769            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20770                dumpState.setDump(DumpState.DUMP_MESSAGES);
20771            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20772                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20773            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20774                    || "intent-filter-verifiers".equals(cmd)) {
20775                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20776            } else if ("version".equals(cmd)) {
20777                dumpState.setDump(DumpState.DUMP_VERSION);
20778            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20779                dumpState.setDump(DumpState.DUMP_KEYSETS);
20780            } else if ("installs".equals(cmd)) {
20781                dumpState.setDump(DumpState.DUMP_INSTALLS);
20782            } else if ("frozen".equals(cmd)) {
20783                dumpState.setDump(DumpState.DUMP_FROZEN);
20784            } else if ("dexopt".equals(cmd)) {
20785                dumpState.setDump(DumpState.DUMP_DEXOPT);
20786            } else if ("compiler-stats".equals(cmd)) {
20787                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20788            } else if ("enabled-overlays".equals(cmd)) {
20789                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20790            } else if ("write".equals(cmd)) {
20791                synchronized (mPackages) {
20792                    mSettings.writeLPr();
20793                    pw.println("Settings written.");
20794                    return;
20795                }
20796            }
20797        }
20798
20799        if (checkin) {
20800            pw.println("vers,1");
20801        }
20802
20803        // reader
20804        synchronized (mPackages) {
20805            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20806                if (!checkin) {
20807                    if (dumpState.onTitlePrinted())
20808                        pw.println();
20809                    pw.println("Database versions:");
20810                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20811                }
20812            }
20813
20814            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20815                if (!checkin) {
20816                    if (dumpState.onTitlePrinted())
20817                        pw.println();
20818                    pw.println("Verifiers:");
20819                    pw.print("  Required: ");
20820                    pw.print(mRequiredVerifierPackage);
20821                    pw.print(" (uid=");
20822                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20823                            UserHandle.USER_SYSTEM));
20824                    pw.println(")");
20825                } else if (mRequiredVerifierPackage != null) {
20826                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20827                    pw.print(",");
20828                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20829                            UserHandle.USER_SYSTEM));
20830                }
20831            }
20832
20833            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20834                    packageName == null) {
20835                if (mIntentFilterVerifierComponent != null) {
20836                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20837                    if (!checkin) {
20838                        if (dumpState.onTitlePrinted())
20839                            pw.println();
20840                        pw.println("Intent Filter Verifier:");
20841                        pw.print("  Using: ");
20842                        pw.print(verifierPackageName);
20843                        pw.print(" (uid=");
20844                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20845                                UserHandle.USER_SYSTEM));
20846                        pw.println(")");
20847                    } else if (verifierPackageName != null) {
20848                        pw.print("ifv,"); pw.print(verifierPackageName);
20849                        pw.print(",");
20850                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20851                                UserHandle.USER_SYSTEM));
20852                    }
20853                } else {
20854                    pw.println();
20855                    pw.println("No Intent Filter Verifier available!");
20856                }
20857            }
20858
20859            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20860                boolean printedHeader = false;
20861                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20862                while (it.hasNext()) {
20863                    String libName = it.next();
20864                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20865                    if (versionedLib == null) {
20866                        continue;
20867                    }
20868                    final int versionCount = versionedLib.size();
20869                    for (int i = 0; i < versionCount; i++) {
20870                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20871                        if (!checkin) {
20872                            if (!printedHeader) {
20873                                if (dumpState.onTitlePrinted())
20874                                    pw.println();
20875                                pw.println("Libraries:");
20876                                printedHeader = true;
20877                            }
20878                            pw.print("  ");
20879                        } else {
20880                            pw.print("lib,");
20881                        }
20882                        pw.print(libEntry.info.getName());
20883                        if (libEntry.info.isStatic()) {
20884                            pw.print(" version=" + libEntry.info.getVersion());
20885                        }
20886                        if (!checkin) {
20887                            pw.print(" -> ");
20888                        }
20889                        if (libEntry.path != null) {
20890                            pw.print(" (jar) ");
20891                            pw.print(libEntry.path);
20892                        } else {
20893                            pw.print(" (apk) ");
20894                            pw.print(libEntry.apk);
20895                        }
20896                        pw.println();
20897                    }
20898                }
20899            }
20900
20901            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20902                if (dumpState.onTitlePrinted())
20903                    pw.println();
20904                if (!checkin) {
20905                    pw.println("Features:");
20906                }
20907
20908                synchronized (mAvailableFeatures) {
20909                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20910                        if (checkin) {
20911                            pw.print("feat,");
20912                            pw.print(feat.name);
20913                            pw.print(",");
20914                            pw.println(feat.version);
20915                        } else {
20916                            pw.print("  ");
20917                            pw.print(feat.name);
20918                            if (feat.version > 0) {
20919                                pw.print(" version=");
20920                                pw.print(feat.version);
20921                            }
20922                            pw.println();
20923                        }
20924                    }
20925                }
20926            }
20927
20928            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20929                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20930                        : "Activity Resolver Table:", "  ", packageName,
20931                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20932                    dumpState.setTitlePrinted(true);
20933                }
20934            }
20935            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20936                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20937                        : "Receiver Resolver Table:", "  ", packageName,
20938                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20939                    dumpState.setTitlePrinted(true);
20940                }
20941            }
20942            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20943                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20944                        : "Service Resolver Table:", "  ", packageName,
20945                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20946                    dumpState.setTitlePrinted(true);
20947                }
20948            }
20949            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20950                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20951                        : "Provider Resolver Table:", "  ", packageName,
20952                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20953                    dumpState.setTitlePrinted(true);
20954                }
20955            }
20956
20957            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20958                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20959                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20960                    int user = mSettings.mPreferredActivities.keyAt(i);
20961                    if (pir.dump(pw,
20962                            dumpState.getTitlePrinted()
20963                                ? "\nPreferred Activities User " + user + ":"
20964                                : "Preferred Activities User " + user + ":", "  ",
20965                            packageName, true, false)) {
20966                        dumpState.setTitlePrinted(true);
20967                    }
20968                }
20969            }
20970
20971            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20972                pw.flush();
20973                FileOutputStream fout = new FileOutputStream(fd);
20974                BufferedOutputStream str = new BufferedOutputStream(fout);
20975                XmlSerializer serializer = new FastXmlSerializer();
20976                try {
20977                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20978                    serializer.startDocument(null, true);
20979                    serializer.setFeature(
20980                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20981                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20982                    serializer.endDocument();
20983                    serializer.flush();
20984                } catch (IllegalArgumentException e) {
20985                    pw.println("Failed writing: " + e);
20986                } catch (IllegalStateException e) {
20987                    pw.println("Failed writing: " + e);
20988                } catch (IOException e) {
20989                    pw.println("Failed writing: " + e);
20990                }
20991            }
20992
20993            if (!checkin
20994                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20995                    && packageName == null) {
20996                pw.println();
20997                int count = mSettings.mPackages.size();
20998                if (count == 0) {
20999                    pw.println("No applications!");
21000                    pw.println();
21001                } else {
21002                    final String prefix = "  ";
21003                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21004                    if (allPackageSettings.size() == 0) {
21005                        pw.println("No domain preferred apps!");
21006                        pw.println();
21007                    } else {
21008                        pw.println("App verification status:");
21009                        pw.println();
21010                        count = 0;
21011                        for (PackageSetting ps : allPackageSettings) {
21012                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21013                            if (ivi == null || ivi.getPackageName() == null) continue;
21014                            pw.println(prefix + "Package: " + ivi.getPackageName());
21015                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21016                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21017                            pw.println();
21018                            count++;
21019                        }
21020                        if (count == 0) {
21021                            pw.println(prefix + "No app verification established.");
21022                            pw.println();
21023                        }
21024                        for (int userId : sUserManager.getUserIds()) {
21025                            pw.println("App linkages for user " + userId + ":");
21026                            pw.println();
21027                            count = 0;
21028                            for (PackageSetting ps : allPackageSettings) {
21029                                final long status = ps.getDomainVerificationStatusForUser(userId);
21030                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21031                                        && !DEBUG_DOMAIN_VERIFICATION) {
21032                                    continue;
21033                                }
21034                                pw.println(prefix + "Package: " + ps.name);
21035                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21036                                String statusStr = IntentFilterVerificationInfo.
21037                                        getStatusStringFromValue(status);
21038                                pw.println(prefix + "Status:  " + statusStr);
21039                                pw.println();
21040                                count++;
21041                            }
21042                            if (count == 0) {
21043                                pw.println(prefix + "No configured app linkages.");
21044                                pw.println();
21045                            }
21046                        }
21047                    }
21048                }
21049            }
21050
21051            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21052                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21053                if (packageName == null && permissionNames == null) {
21054                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21055                        if (iperm == 0) {
21056                            if (dumpState.onTitlePrinted())
21057                                pw.println();
21058                            pw.println("AppOp Permissions:");
21059                        }
21060                        pw.print("  AppOp Permission ");
21061                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21062                        pw.println(":");
21063                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21064                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21065                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21066                        }
21067                    }
21068                }
21069            }
21070
21071            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21072                boolean printedSomething = false;
21073                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21074                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21075                        continue;
21076                    }
21077                    if (!printedSomething) {
21078                        if (dumpState.onTitlePrinted())
21079                            pw.println();
21080                        pw.println("Registered ContentProviders:");
21081                        printedSomething = true;
21082                    }
21083                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21084                    pw.print("    "); pw.println(p.toString());
21085                }
21086                printedSomething = false;
21087                for (Map.Entry<String, PackageParser.Provider> entry :
21088                        mProvidersByAuthority.entrySet()) {
21089                    PackageParser.Provider p = entry.getValue();
21090                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21091                        continue;
21092                    }
21093                    if (!printedSomething) {
21094                        if (dumpState.onTitlePrinted())
21095                            pw.println();
21096                        pw.println("ContentProvider Authorities:");
21097                        printedSomething = true;
21098                    }
21099                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21100                    pw.print("    "); pw.println(p.toString());
21101                    if (p.info != null && p.info.applicationInfo != null) {
21102                        final String appInfo = p.info.applicationInfo.toString();
21103                        pw.print("      applicationInfo="); pw.println(appInfo);
21104                    }
21105                }
21106            }
21107
21108            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21109                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21110            }
21111
21112            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21113                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21114            }
21115
21116            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21117                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21118            }
21119
21120            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21121                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21122            }
21123
21124            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21125                // XXX should handle packageName != null by dumping only install data that
21126                // the given package is involved with.
21127                if (dumpState.onTitlePrinted()) pw.println();
21128
21129                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21130                ipw.println();
21131                ipw.println("Frozen packages:");
21132                ipw.increaseIndent();
21133                if (mFrozenPackages.size() == 0) {
21134                    ipw.println("(none)");
21135                } else {
21136                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21137                        ipw.println(mFrozenPackages.valueAt(i));
21138                    }
21139                }
21140                ipw.decreaseIndent();
21141            }
21142
21143            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21144                if (dumpState.onTitlePrinted()) pw.println();
21145                dumpDexoptStateLPr(pw, packageName);
21146            }
21147
21148            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21149                if (dumpState.onTitlePrinted()) pw.println();
21150                dumpCompilerStatsLPr(pw, packageName);
21151            }
21152
21153            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21154                if (dumpState.onTitlePrinted()) pw.println();
21155                dumpEnabledOverlaysLPr(pw);
21156            }
21157
21158            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21159                if (dumpState.onTitlePrinted()) pw.println();
21160                mSettings.dumpReadMessagesLPr(pw, dumpState);
21161
21162                pw.println();
21163                pw.println("Package warning messages:");
21164                BufferedReader in = null;
21165                String line = null;
21166                try {
21167                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21168                    while ((line = in.readLine()) != null) {
21169                        if (line.contains("ignored: updated version")) continue;
21170                        pw.println(line);
21171                    }
21172                } catch (IOException ignored) {
21173                } finally {
21174                    IoUtils.closeQuietly(in);
21175                }
21176            }
21177
21178            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21179                BufferedReader in = null;
21180                String line = null;
21181                try {
21182                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21183                    while ((line = in.readLine()) != null) {
21184                        if (line.contains("ignored: updated version")) continue;
21185                        pw.print("msg,");
21186                        pw.println(line);
21187                    }
21188                } catch (IOException ignored) {
21189                } finally {
21190                    IoUtils.closeQuietly(in);
21191                }
21192            }
21193        }
21194
21195        // PackageInstaller should be called outside of mPackages lock
21196        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21197            // XXX should handle packageName != null by dumping only install data that
21198            // the given package is involved with.
21199            if (dumpState.onTitlePrinted()) pw.println();
21200            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21201        }
21202    }
21203
21204    private void dumpProto(FileDescriptor fd) {
21205        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21206
21207        synchronized (mPackages) {
21208            final long requiredVerifierPackageToken =
21209                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21210            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21211            proto.write(
21212                    PackageServiceDumpProto.PackageShortProto.UID,
21213                    getPackageUid(
21214                            mRequiredVerifierPackage,
21215                            MATCH_DEBUG_TRIAGED_MISSING,
21216                            UserHandle.USER_SYSTEM));
21217            proto.end(requiredVerifierPackageToken);
21218
21219            if (mIntentFilterVerifierComponent != null) {
21220                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21221                final long verifierPackageToken =
21222                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21223                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21224                proto.write(
21225                        PackageServiceDumpProto.PackageShortProto.UID,
21226                        getPackageUid(
21227                                verifierPackageName,
21228                                MATCH_DEBUG_TRIAGED_MISSING,
21229                                UserHandle.USER_SYSTEM));
21230                proto.end(verifierPackageToken);
21231            }
21232
21233            dumpSharedLibrariesProto(proto);
21234            dumpFeaturesProto(proto);
21235            mSettings.dumpPackagesProto(proto);
21236            mSettings.dumpSharedUsersProto(proto);
21237            dumpMessagesProto(proto);
21238        }
21239        proto.flush();
21240    }
21241
21242    private void dumpMessagesProto(ProtoOutputStream proto) {
21243        BufferedReader in = null;
21244        String line = null;
21245        try {
21246            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21247            while ((line = in.readLine()) != null) {
21248                if (line.contains("ignored: updated version")) continue;
21249                proto.write(PackageServiceDumpProto.MESSAGES, line);
21250            }
21251        } catch (IOException ignored) {
21252        } finally {
21253            IoUtils.closeQuietly(in);
21254        }
21255    }
21256
21257    private void dumpFeaturesProto(ProtoOutputStream proto) {
21258        synchronized (mAvailableFeatures) {
21259            final int count = mAvailableFeatures.size();
21260            for (int i = 0; i < count; i++) {
21261                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21262                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21263                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21264                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21265                proto.end(featureToken);
21266            }
21267        }
21268    }
21269
21270    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21271        final int count = mSharedLibraries.size();
21272        for (int i = 0; i < count; i++) {
21273            final String libName = mSharedLibraries.keyAt(i);
21274            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21275            if (versionedLib == null) {
21276                continue;
21277            }
21278            final int versionCount = versionedLib.size();
21279            for (int j = 0; j < versionCount; j++) {
21280                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21281                final long sharedLibraryToken =
21282                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21283                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21284                final boolean isJar = (libEntry.path != null);
21285                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21286                if (isJar) {
21287                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21288                } else {
21289                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21290                }
21291                proto.end(sharedLibraryToken);
21292            }
21293        }
21294    }
21295
21296    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21297        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21298        ipw.println();
21299        ipw.println("Dexopt state:");
21300        ipw.increaseIndent();
21301        Collection<PackageParser.Package> packages = null;
21302        if (packageName != null) {
21303            PackageParser.Package targetPackage = mPackages.get(packageName);
21304            if (targetPackage != null) {
21305                packages = Collections.singletonList(targetPackage);
21306            } else {
21307                ipw.println("Unable to find package: " + packageName);
21308                return;
21309            }
21310        } else {
21311            packages = mPackages.values();
21312        }
21313
21314        for (PackageParser.Package pkg : packages) {
21315            ipw.println("[" + pkg.packageName + "]");
21316            ipw.increaseIndent();
21317            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21318            ipw.decreaseIndent();
21319        }
21320    }
21321
21322    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21323        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21324        ipw.println();
21325        ipw.println("Compiler stats:");
21326        ipw.increaseIndent();
21327        Collection<PackageParser.Package> packages = null;
21328        if (packageName != null) {
21329            PackageParser.Package targetPackage = mPackages.get(packageName);
21330            if (targetPackage != null) {
21331                packages = Collections.singletonList(targetPackage);
21332            } else {
21333                ipw.println("Unable to find package: " + packageName);
21334                return;
21335            }
21336        } else {
21337            packages = mPackages.values();
21338        }
21339
21340        for (PackageParser.Package pkg : packages) {
21341            ipw.println("[" + pkg.packageName + "]");
21342            ipw.increaseIndent();
21343
21344            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21345            if (stats == null) {
21346                ipw.println("(No recorded stats)");
21347            } else {
21348                stats.dump(ipw);
21349            }
21350            ipw.decreaseIndent();
21351        }
21352    }
21353
21354    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21355        pw.println("Enabled overlay paths:");
21356        final int N = mEnabledOverlayPaths.size();
21357        for (int i = 0; i < N; i++) {
21358            final int userId = mEnabledOverlayPaths.keyAt(i);
21359            pw.println(String.format("    User %d:", userId));
21360            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21361                mEnabledOverlayPaths.valueAt(i);
21362            final int M = userSpecificOverlays.size();
21363            for (int j = 0; j < M; j++) {
21364                final String targetPackageName = userSpecificOverlays.keyAt(j);
21365                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21366                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21367            }
21368        }
21369    }
21370
21371    private String dumpDomainString(String packageName) {
21372        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21373                .getList();
21374        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21375
21376        ArraySet<String> result = new ArraySet<>();
21377        if (iviList.size() > 0) {
21378            for (IntentFilterVerificationInfo ivi : iviList) {
21379                for (String host : ivi.getDomains()) {
21380                    result.add(host);
21381                }
21382            }
21383        }
21384        if (filters != null && filters.size() > 0) {
21385            for (IntentFilter filter : filters) {
21386                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21387                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21388                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21389                    result.addAll(filter.getHostsList());
21390                }
21391            }
21392        }
21393
21394        StringBuilder sb = new StringBuilder(result.size() * 16);
21395        for (String domain : result) {
21396            if (sb.length() > 0) sb.append(" ");
21397            sb.append(domain);
21398        }
21399        return sb.toString();
21400    }
21401
21402    // ------- apps on sdcard specific code -------
21403    static final boolean DEBUG_SD_INSTALL = false;
21404
21405    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21406
21407    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21408
21409    private boolean mMediaMounted = false;
21410
21411    static String getEncryptKey() {
21412        try {
21413            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21414                    SD_ENCRYPTION_KEYSTORE_NAME);
21415            if (sdEncKey == null) {
21416                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21417                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21418                if (sdEncKey == null) {
21419                    Slog.e(TAG, "Failed to create encryption keys");
21420                    return null;
21421                }
21422            }
21423            return sdEncKey;
21424        } catch (NoSuchAlgorithmException nsae) {
21425            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21426            return null;
21427        } catch (IOException ioe) {
21428            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21429            return null;
21430        }
21431    }
21432
21433    /*
21434     * Update media status on PackageManager.
21435     */
21436    @Override
21437    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21438        int callingUid = Binder.getCallingUid();
21439        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21440            throw new SecurityException("Media status can only be updated by the system");
21441        }
21442        // reader; this apparently protects mMediaMounted, but should probably
21443        // be a different lock in that case.
21444        synchronized (mPackages) {
21445            Log.i(TAG, "Updating external media status from "
21446                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21447                    + (mediaStatus ? "mounted" : "unmounted"));
21448            if (DEBUG_SD_INSTALL)
21449                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21450                        + ", mMediaMounted=" + mMediaMounted);
21451            if (mediaStatus == mMediaMounted) {
21452                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21453                        : 0, -1);
21454                mHandler.sendMessage(msg);
21455                return;
21456            }
21457            mMediaMounted = mediaStatus;
21458        }
21459        // Queue up an async operation since the package installation may take a
21460        // little while.
21461        mHandler.post(new Runnable() {
21462            public void run() {
21463                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21464            }
21465        });
21466    }
21467
21468    /**
21469     * Called by StorageManagerService when the initial ASECs to scan are available.
21470     * Should block until all the ASEC containers are finished being scanned.
21471     */
21472    public void scanAvailableAsecs() {
21473        updateExternalMediaStatusInner(true, false, false);
21474    }
21475
21476    /*
21477     * Collect information of applications on external media, map them against
21478     * existing containers and update information based on current mount status.
21479     * Please note that we always have to report status if reportStatus has been
21480     * set to true especially when unloading packages.
21481     */
21482    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21483            boolean externalStorage) {
21484        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21485        int[] uidArr = EmptyArray.INT;
21486
21487        final String[] list = PackageHelper.getSecureContainerList();
21488        if (ArrayUtils.isEmpty(list)) {
21489            Log.i(TAG, "No secure containers found");
21490        } else {
21491            // Process list of secure containers and categorize them
21492            // as active or stale based on their package internal state.
21493
21494            // reader
21495            synchronized (mPackages) {
21496                for (String cid : list) {
21497                    // Leave stages untouched for now; installer service owns them
21498                    if (PackageInstallerService.isStageName(cid)) continue;
21499
21500                    if (DEBUG_SD_INSTALL)
21501                        Log.i(TAG, "Processing container " + cid);
21502                    String pkgName = getAsecPackageName(cid);
21503                    if (pkgName == null) {
21504                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21505                        continue;
21506                    }
21507                    if (DEBUG_SD_INSTALL)
21508                        Log.i(TAG, "Looking for pkg : " + pkgName);
21509
21510                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21511                    if (ps == null) {
21512                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21513                        continue;
21514                    }
21515
21516                    /*
21517                     * Skip packages that are not external if we're unmounting
21518                     * external storage.
21519                     */
21520                    if (externalStorage && !isMounted && !isExternal(ps)) {
21521                        continue;
21522                    }
21523
21524                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21525                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21526                    // The package status is changed only if the code path
21527                    // matches between settings and the container id.
21528                    if (ps.codePathString != null
21529                            && ps.codePathString.startsWith(args.getCodePath())) {
21530                        if (DEBUG_SD_INSTALL) {
21531                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21532                                    + " at code path: " + ps.codePathString);
21533                        }
21534
21535                        // We do have a valid package installed on sdcard
21536                        processCids.put(args, ps.codePathString);
21537                        final int uid = ps.appId;
21538                        if (uid != -1) {
21539                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21540                        }
21541                    } else {
21542                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21543                                + ps.codePathString);
21544                    }
21545                }
21546            }
21547
21548            Arrays.sort(uidArr);
21549        }
21550
21551        // Process packages with valid entries.
21552        if (isMounted) {
21553            if (DEBUG_SD_INSTALL)
21554                Log.i(TAG, "Loading packages");
21555            loadMediaPackages(processCids, uidArr, externalStorage);
21556            startCleaningPackages();
21557            mInstallerService.onSecureContainersAvailable();
21558        } else {
21559            if (DEBUG_SD_INSTALL)
21560                Log.i(TAG, "Unloading packages");
21561            unloadMediaPackages(processCids, uidArr, reportStatus);
21562        }
21563    }
21564
21565    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21566            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21567        final int size = infos.size();
21568        final String[] packageNames = new String[size];
21569        final int[] packageUids = new int[size];
21570        for (int i = 0; i < size; i++) {
21571            final ApplicationInfo info = infos.get(i);
21572            packageNames[i] = info.packageName;
21573            packageUids[i] = info.uid;
21574        }
21575        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21576                finishedReceiver);
21577    }
21578
21579    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21580            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21581        sendResourcesChangedBroadcast(mediaStatus, replacing,
21582                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21583    }
21584
21585    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21586            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21587        int size = pkgList.length;
21588        if (size > 0) {
21589            // Send broadcasts here
21590            Bundle extras = new Bundle();
21591            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21592            if (uidArr != null) {
21593                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21594            }
21595            if (replacing) {
21596                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21597            }
21598            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21599                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21600            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21601        }
21602    }
21603
21604   /*
21605     * Look at potentially valid container ids from processCids If package
21606     * information doesn't match the one on record or package scanning fails,
21607     * the cid is added to list of removeCids. We currently don't delete stale
21608     * containers.
21609     */
21610    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21611            boolean externalStorage) {
21612        ArrayList<String> pkgList = new ArrayList<String>();
21613        Set<AsecInstallArgs> keys = processCids.keySet();
21614
21615        for (AsecInstallArgs args : keys) {
21616            String codePath = processCids.get(args);
21617            if (DEBUG_SD_INSTALL)
21618                Log.i(TAG, "Loading container : " + args.cid);
21619            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21620            try {
21621                // Make sure there are no container errors first.
21622                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21623                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21624                            + " when installing from sdcard");
21625                    continue;
21626                }
21627                // Check code path here.
21628                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21629                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21630                            + " does not match one in settings " + codePath);
21631                    continue;
21632                }
21633                // Parse package
21634                int parseFlags = mDefParseFlags;
21635                if (args.isExternalAsec()) {
21636                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21637                }
21638                if (args.isFwdLocked()) {
21639                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21640                }
21641
21642                synchronized (mInstallLock) {
21643                    PackageParser.Package pkg = null;
21644                    try {
21645                        // Sadly we don't know the package name yet to freeze it
21646                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21647                                SCAN_IGNORE_FROZEN, 0, null);
21648                    } catch (PackageManagerException e) {
21649                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21650                    }
21651                    // Scan the package
21652                    if (pkg != null) {
21653                        /*
21654                         * TODO why is the lock being held? doPostInstall is
21655                         * called in other places without the lock. This needs
21656                         * to be straightened out.
21657                         */
21658                        // writer
21659                        synchronized (mPackages) {
21660                            retCode = PackageManager.INSTALL_SUCCEEDED;
21661                            pkgList.add(pkg.packageName);
21662                            // Post process args
21663                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21664                                    pkg.applicationInfo.uid);
21665                        }
21666                    } else {
21667                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21668                    }
21669                }
21670
21671            } finally {
21672                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21673                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21674                }
21675            }
21676        }
21677        // writer
21678        synchronized (mPackages) {
21679            // If the platform SDK has changed since the last time we booted,
21680            // we need to re-grant app permission to catch any new ones that
21681            // appear. This is really a hack, and means that apps can in some
21682            // cases get permissions that the user didn't initially explicitly
21683            // allow... it would be nice to have some better way to handle
21684            // this situation.
21685            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21686                    : mSettings.getInternalVersion();
21687            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21688                    : StorageManager.UUID_PRIVATE_INTERNAL;
21689
21690            int updateFlags = UPDATE_PERMISSIONS_ALL;
21691            if (ver.sdkVersion != mSdkVersion) {
21692                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21693                        + mSdkVersion + "; regranting permissions for external");
21694                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21695            }
21696            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21697
21698            // Yay, everything is now upgraded
21699            ver.forceCurrent();
21700
21701            // can downgrade to reader
21702            // Persist settings
21703            mSettings.writeLPr();
21704        }
21705        // Send a broadcast to let everyone know we are done processing
21706        if (pkgList.size() > 0) {
21707            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21708        }
21709    }
21710
21711   /*
21712     * Utility method to unload a list of specified containers
21713     */
21714    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21715        // Just unmount all valid containers.
21716        for (AsecInstallArgs arg : cidArgs) {
21717            synchronized (mInstallLock) {
21718                arg.doPostDeleteLI(false);
21719           }
21720       }
21721   }
21722
21723    /*
21724     * Unload packages mounted on external media. This involves deleting package
21725     * data from internal structures, sending broadcasts about disabled packages,
21726     * gc'ing to free up references, unmounting all secure containers
21727     * corresponding to packages on external media, and posting a
21728     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21729     * that we always have to post this message if status has been requested no
21730     * matter what.
21731     */
21732    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21733            final boolean reportStatus) {
21734        if (DEBUG_SD_INSTALL)
21735            Log.i(TAG, "unloading media packages");
21736        ArrayList<String> pkgList = new ArrayList<String>();
21737        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21738        final Set<AsecInstallArgs> keys = processCids.keySet();
21739        for (AsecInstallArgs args : keys) {
21740            String pkgName = args.getPackageName();
21741            if (DEBUG_SD_INSTALL)
21742                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21743            // Delete package internally
21744            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21745            synchronized (mInstallLock) {
21746                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21747                final boolean res;
21748                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21749                        "unloadMediaPackages")) {
21750                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21751                            null);
21752                }
21753                if (res) {
21754                    pkgList.add(pkgName);
21755                } else {
21756                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21757                    failedList.add(args);
21758                }
21759            }
21760        }
21761
21762        // reader
21763        synchronized (mPackages) {
21764            // We didn't update the settings after removing each package;
21765            // write them now for all packages.
21766            mSettings.writeLPr();
21767        }
21768
21769        // We have to absolutely send UPDATED_MEDIA_STATUS only
21770        // after confirming that all the receivers processed the ordered
21771        // broadcast when packages get disabled, force a gc to clean things up.
21772        // and unload all the containers.
21773        if (pkgList.size() > 0) {
21774            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21775                    new IIntentReceiver.Stub() {
21776                public void performReceive(Intent intent, int resultCode, String data,
21777                        Bundle extras, boolean ordered, boolean sticky,
21778                        int sendingUser) throws RemoteException {
21779                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21780                            reportStatus ? 1 : 0, 1, keys);
21781                    mHandler.sendMessage(msg);
21782                }
21783            });
21784        } else {
21785            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21786                    keys);
21787            mHandler.sendMessage(msg);
21788        }
21789    }
21790
21791    private void loadPrivatePackages(final VolumeInfo vol) {
21792        mHandler.post(new Runnable() {
21793            @Override
21794            public void run() {
21795                loadPrivatePackagesInner(vol);
21796            }
21797        });
21798    }
21799
21800    private void loadPrivatePackagesInner(VolumeInfo vol) {
21801        final String volumeUuid = vol.fsUuid;
21802        if (TextUtils.isEmpty(volumeUuid)) {
21803            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21804            return;
21805        }
21806
21807        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21808        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21809        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21810
21811        final VersionInfo ver;
21812        final List<PackageSetting> packages;
21813        synchronized (mPackages) {
21814            ver = mSettings.findOrCreateVersion(volumeUuid);
21815            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21816        }
21817
21818        for (PackageSetting ps : packages) {
21819            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21820            synchronized (mInstallLock) {
21821                final PackageParser.Package pkg;
21822                try {
21823                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21824                    loaded.add(pkg.applicationInfo);
21825
21826                } catch (PackageManagerException e) {
21827                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21828                }
21829
21830                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21831                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21832                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21833                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21834                }
21835            }
21836        }
21837
21838        // Reconcile app data for all started/unlocked users
21839        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21840        final UserManager um = mContext.getSystemService(UserManager.class);
21841        UserManagerInternal umInternal = getUserManagerInternal();
21842        for (UserInfo user : um.getUsers()) {
21843            final int flags;
21844            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21845                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21846            } else if (umInternal.isUserRunning(user.id)) {
21847                flags = StorageManager.FLAG_STORAGE_DE;
21848            } else {
21849                continue;
21850            }
21851
21852            try {
21853                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21854                synchronized (mInstallLock) {
21855                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21856                }
21857            } catch (IllegalStateException e) {
21858                // Device was probably ejected, and we'll process that event momentarily
21859                Slog.w(TAG, "Failed to prepare storage: " + e);
21860            }
21861        }
21862
21863        synchronized (mPackages) {
21864            int updateFlags = UPDATE_PERMISSIONS_ALL;
21865            if (ver.sdkVersion != mSdkVersion) {
21866                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21867                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21868                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21869            }
21870            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21871
21872            // Yay, everything is now upgraded
21873            ver.forceCurrent();
21874
21875            mSettings.writeLPr();
21876        }
21877
21878        for (PackageFreezer freezer : freezers) {
21879            freezer.close();
21880        }
21881
21882        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21883        sendResourcesChangedBroadcast(true, false, loaded, null);
21884    }
21885
21886    private void unloadPrivatePackages(final VolumeInfo vol) {
21887        mHandler.post(new Runnable() {
21888            @Override
21889            public void run() {
21890                unloadPrivatePackagesInner(vol);
21891            }
21892        });
21893    }
21894
21895    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21896        final String volumeUuid = vol.fsUuid;
21897        if (TextUtils.isEmpty(volumeUuid)) {
21898            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21899            return;
21900        }
21901
21902        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21903        synchronized (mInstallLock) {
21904        synchronized (mPackages) {
21905            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21906            for (PackageSetting ps : packages) {
21907                if (ps.pkg == null) continue;
21908
21909                final ApplicationInfo info = ps.pkg.applicationInfo;
21910                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21911                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21912
21913                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21914                        "unloadPrivatePackagesInner")) {
21915                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21916                            false, null)) {
21917                        unloaded.add(info);
21918                    } else {
21919                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21920                    }
21921                }
21922
21923                // Try very hard to release any references to this package
21924                // so we don't risk the system server being killed due to
21925                // open FDs
21926                AttributeCache.instance().removePackage(ps.name);
21927            }
21928
21929            mSettings.writeLPr();
21930        }
21931        }
21932
21933        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21934        sendResourcesChangedBroadcast(false, false, unloaded, null);
21935
21936        // Try very hard to release any references to this path so we don't risk
21937        // the system server being killed due to open FDs
21938        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21939
21940        for (int i = 0; i < 3; i++) {
21941            System.gc();
21942            System.runFinalization();
21943        }
21944    }
21945
21946    private void assertPackageKnown(String volumeUuid, String packageName)
21947            throws PackageManagerException {
21948        synchronized (mPackages) {
21949            // Normalize package name to handle renamed packages
21950            packageName = normalizePackageNameLPr(packageName);
21951
21952            final PackageSetting ps = mSettings.mPackages.get(packageName);
21953            if (ps == null) {
21954                throw new PackageManagerException("Package " + packageName + " is unknown");
21955            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21956                throw new PackageManagerException(
21957                        "Package " + packageName + " found on unknown volume " + volumeUuid
21958                                + "; expected volume " + ps.volumeUuid);
21959            }
21960        }
21961    }
21962
21963    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21964            throws PackageManagerException {
21965        synchronized (mPackages) {
21966            // Normalize package name to handle renamed packages
21967            packageName = normalizePackageNameLPr(packageName);
21968
21969            final PackageSetting ps = mSettings.mPackages.get(packageName);
21970            if (ps == null) {
21971                throw new PackageManagerException("Package " + packageName + " is unknown");
21972            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21973                throw new PackageManagerException(
21974                        "Package " + packageName + " found on unknown volume " + volumeUuid
21975                                + "; expected volume " + ps.volumeUuid);
21976            } else if (!ps.getInstalled(userId)) {
21977                throw new PackageManagerException(
21978                        "Package " + packageName + " not installed for user " + userId);
21979            }
21980        }
21981    }
21982
21983    private List<String> collectAbsoluteCodePaths() {
21984        synchronized (mPackages) {
21985            List<String> codePaths = new ArrayList<>();
21986            final int packageCount = mSettings.mPackages.size();
21987            for (int i = 0; i < packageCount; i++) {
21988                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21989                codePaths.add(ps.codePath.getAbsolutePath());
21990            }
21991            return codePaths;
21992        }
21993    }
21994
21995    /**
21996     * Examine all apps present on given mounted volume, and destroy apps that
21997     * aren't expected, either due to uninstallation or reinstallation on
21998     * another volume.
21999     */
22000    private void reconcileApps(String volumeUuid) {
22001        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22002        List<File> filesToDelete = null;
22003
22004        final File[] files = FileUtils.listFilesOrEmpty(
22005                Environment.getDataAppDirectory(volumeUuid));
22006        for (File file : files) {
22007            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22008                    && !PackageInstallerService.isStageName(file.getName());
22009            if (!isPackage) {
22010                // Ignore entries which are not packages
22011                continue;
22012            }
22013
22014            String absolutePath = file.getAbsolutePath();
22015
22016            boolean pathValid = false;
22017            final int absoluteCodePathCount = absoluteCodePaths.size();
22018            for (int i = 0; i < absoluteCodePathCount; i++) {
22019                String absoluteCodePath = absoluteCodePaths.get(i);
22020                if (absolutePath.startsWith(absoluteCodePath)) {
22021                    pathValid = true;
22022                    break;
22023                }
22024            }
22025
22026            if (!pathValid) {
22027                if (filesToDelete == null) {
22028                    filesToDelete = new ArrayList<>();
22029                }
22030                filesToDelete.add(file);
22031            }
22032        }
22033
22034        if (filesToDelete != null) {
22035            final int fileToDeleteCount = filesToDelete.size();
22036            for (int i = 0; i < fileToDeleteCount; i++) {
22037                File fileToDelete = filesToDelete.get(i);
22038                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22039                synchronized (mInstallLock) {
22040                    removeCodePathLI(fileToDelete);
22041                }
22042            }
22043        }
22044    }
22045
22046    /**
22047     * Reconcile all app data for the given user.
22048     * <p>
22049     * Verifies that directories exist and that ownership and labeling is
22050     * correct for all installed apps on all mounted volumes.
22051     */
22052    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22053        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22054        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22055            final String volumeUuid = vol.getFsUuid();
22056            synchronized (mInstallLock) {
22057                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22058            }
22059        }
22060    }
22061
22062    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22063            boolean migrateAppData) {
22064        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22065    }
22066
22067    /**
22068     * Reconcile all app data on given mounted volume.
22069     * <p>
22070     * Destroys app data that isn't expected, either due to uninstallation or
22071     * reinstallation on another volume.
22072     * <p>
22073     * Verifies that directories exist and that ownership and labeling is
22074     * correct for all installed apps.
22075     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22076     */
22077    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22078            boolean migrateAppData, boolean onlyCoreApps) {
22079        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22080                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22081        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22082
22083        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22084        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22085
22086        // First look for stale data that doesn't belong, and check if things
22087        // have changed since we did our last restorecon
22088        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22089            if (StorageManager.isFileEncryptedNativeOrEmulated()
22090                    && !StorageManager.isUserKeyUnlocked(userId)) {
22091                throw new RuntimeException(
22092                        "Yikes, someone asked us to reconcile CE storage while " + userId
22093                                + " was still locked; this would have caused massive data loss!");
22094            }
22095
22096            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22097            for (File file : files) {
22098                final String packageName = file.getName();
22099                try {
22100                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22101                } catch (PackageManagerException e) {
22102                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22103                    try {
22104                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22105                                StorageManager.FLAG_STORAGE_CE, 0);
22106                    } catch (InstallerException e2) {
22107                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22108                    }
22109                }
22110            }
22111        }
22112        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22113            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22114            for (File file : files) {
22115                final String packageName = file.getName();
22116                try {
22117                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22118                } catch (PackageManagerException e) {
22119                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22120                    try {
22121                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22122                                StorageManager.FLAG_STORAGE_DE, 0);
22123                    } catch (InstallerException e2) {
22124                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22125                    }
22126                }
22127            }
22128        }
22129
22130        // Ensure that data directories are ready to roll for all packages
22131        // installed for this volume and user
22132        final List<PackageSetting> packages;
22133        synchronized (mPackages) {
22134            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22135        }
22136        int preparedCount = 0;
22137        for (PackageSetting ps : packages) {
22138            final String packageName = ps.name;
22139            if (ps.pkg == null) {
22140                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22141                // TODO: might be due to legacy ASEC apps; we should circle back
22142                // and reconcile again once they're scanned
22143                continue;
22144            }
22145            // Skip non-core apps if requested
22146            if (onlyCoreApps && !ps.pkg.coreApp) {
22147                result.add(packageName);
22148                continue;
22149            }
22150
22151            if (ps.getInstalled(userId)) {
22152                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22153                preparedCount++;
22154            }
22155        }
22156
22157        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22158        return result;
22159    }
22160
22161    /**
22162     * Prepare app data for the given app just after it was installed or
22163     * upgraded. This method carefully only touches users that it's installed
22164     * for, and it forces a restorecon to handle any seinfo changes.
22165     * <p>
22166     * Verifies that directories exist and that ownership and labeling is
22167     * correct for all installed apps. If there is an ownership mismatch, it
22168     * will try recovering system apps by wiping data; third-party app data is
22169     * left intact.
22170     * <p>
22171     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22172     */
22173    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22174        final PackageSetting ps;
22175        synchronized (mPackages) {
22176            ps = mSettings.mPackages.get(pkg.packageName);
22177            mSettings.writeKernelMappingLPr(ps);
22178        }
22179
22180        final UserManager um = mContext.getSystemService(UserManager.class);
22181        UserManagerInternal umInternal = getUserManagerInternal();
22182        for (UserInfo user : um.getUsers()) {
22183            final int flags;
22184            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22185                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22186            } else if (umInternal.isUserRunning(user.id)) {
22187                flags = StorageManager.FLAG_STORAGE_DE;
22188            } else {
22189                continue;
22190            }
22191
22192            if (ps.getInstalled(user.id)) {
22193                // TODO: when user data is locked, mark that we're still dirty
22194                prepareAppDataLIF(pkg, user.id, flags);
22195            }
22196        }
22197    }
22198
22199    /**
22200     * Prepare app data for the given app.
22201     * <p>
22202     * Verifies that directories exist and that ownership and labeling is
22203     * correct for all installed apps. If there is an ownership mismatch, this
22204     * will try recovering system apps by wiping data; third-party app data is
22205     * left intact.
22206     */
22207    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22208        if (pkg == null) {
22209            Slog.wtf(TAG, "Package was null!", new Throwable());
22210            return;
22211        }
22212        prepareAppDataLeafLIF(pkg, userId, flags);
22213        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22214        for (int i = 0; i < childCount; i++) {
22215            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22216        }
22217    }
22218
22219    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22220            boolean maybeMigrateAppData) {
22221        prepareAppDataLIF(pkg, userId, flags);
22222
22223        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22224            // We may have just shuffled around app data directories, so
22225            // prepare them one more time
22226            prepareAppDataLIF(pkg, userId, flags);
22227        }
22228    }
22229
22230    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22231        if (DEBUG_APP_DATA) {
22232            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22233                    + Integer.toHexString(flags));
22234        }
22235
22236        final String volumeUuid = pkg.volumeUuid;
22237        final String packageName = pkg.packageName;
22238        final ApplicationInfo app = pkg.applicationInfo;
22239        final int appId = UserHandle.getAppId(app.uid);
22240
22241        Preconditions.checkNotNull(app.seInfo);
22242
22243        long ceDataInode = -1;
22244        try {
22245            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22246                    appId, app.seInfo, app.targetSdkVersion);
22247        } catch (InstallerException e) {
22248            if (app.isSystemApp()) {
22249                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22250                        + ", but trying to recover: " + e);
22251                destroyAppDataLeafLIF(pkg, userId, flags);
22252                try {
22253                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22254                            appId, app.seInfo, app.targetSdkVersion);
22255                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22256                } catch (InstallerException e2) {
22257                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22258                }
22259            } else {
22260                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22261            }
22262        }
22263
22264        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22265            // TODO: mark this structure as dirty so we persist it!
22266            synchronized (mPackages) {
22267                final PackageSetting ps = mSettings.mPackages.get(packageName);
22268                if (ps != null) {
22269                    ps.setCeDataInode(ceDataInode, userId);
22270                }
22271            }
22272        }
22273
22274        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22275    }
22276
22277    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22278        if (pkg == null) {
22279            Slog.wtf(TAG, "Package was null!", new Throwable());
22280            return;
22281        }
22282        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22283        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22284        for (int i = 0; i < childCount; i++) {
22285            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22286        }
22287    }
22288
22289    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22290        final String volumeUuid = pkg.volumeUuid;
22291        final String packageName = pkg.packageName;
22292        final ApplicationInfo app = pkg.applicationInfo;
22293
22294        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22295            // Create a native library symlink only if we have native libraries
22296            // and if the native libraries are 32 bit libraries. We do not provide
22297            // this symlink for 64 bit libraries.
22298            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22299                final String nativeLibPath = app.nativeLibraryDir;
22300                try {
22301                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22302                            nativeLibPath, userId);
22303                } catch (InstallerException e) {
22304                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22305                }
22306            }
22307        }
22308    }
22309
22310    /**
22311     * For system apps on non-FBE devices, this method migrates any existing
22312     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22313     * requested by the app.
22314     */
22315    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22316        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22317                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22318            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22319                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22320            try {
22321                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22322                        storageTarget);
22323            } catch (InstallerException e) {
22324                logCriticalInfo(Log.WARN,
22325                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22326            }
22327            return true;
22328        } else {
22329            return false;
22330        }
22331    }
22332
22333    public PackageFreezer freezePackage(String packageName, String killReason) {
22334        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22335    }
22336
22337    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22338        return new PackageFreezer(packageName, userId, killReason);
22339    }
22340
22341    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22342            String killReason) {
22343        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22344    }
22345
22346    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22347            String killReason) {
22348        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22349            return new PackageFreezer();
22350        } else {
22351            return freezePackage(packageName, userId, killReason);
22352        }
22353    }
22354
22355    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22356            String killReason) {
22357        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22358    }
22359
22360    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22361            String killReason) {
22362        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22363            return new PackageFreezer();
22364        } else {
22365            return freezePackage(packageName, userId, killReason);
22366        }
22367    }
22368
22369    /**
22370     * Class that freezes and kills the given package upon creation, and
22371     * unfreezes it upon closing. This is typically used when doing surgery on
22372     * app code/data to prevent the app from running while you're working.
22373     */
22374    private class PackageFreezer implements AutoCloseable {
22375        private final String mPackageName;
22376        private final PackageFreezer[] mChildren;
22377
22378        private final boolean mWeFroze;
22379
22380        private final AtomicBoolean mClosed = new AtomicBoolean();
22381        private final CloseGuard mCloseGuard = CloseGuard.get();
22382
22383        /**
22384         * Create and return a stub freezer that doesn't actually do anything,
22385         * typically used when someone requested
22386         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22387         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22388         */
22389        public PackageFreezer() {
22390            mPackageName = null;
22391            mChildren = null;
22392            mWeFroze = false;
22393            mCloseGuard.open("close");
22394        }
22395
22396        public PackageFreezer(String packageName, int userId, String killReason) {
22397            synchronized (mPackages) {
22398                mPackageName = packageName;
22399                mWeFroze = mFrozenPackages.add(mPackageName);
22400
22401                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22402                if (ps != null) {
22403                    killApplication(ps.name, ps.appId, userId, killReason);
22404                }
22405
22406                final PackageParser.Package p = mPackages.get(packageName);
22407                if (p != null && p.childPackages != null) {
22408                    final int N = p.childPackages.size();
22409                    mChildren = new PackageFreezer[N];
22410                    for (int i = 0; i < N; i++) {
22411                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22412                                userId, killReason);
22413                    }
22414                } else {
22415                    mChildren = null;
22416                }
22417            }
22418            mCloseGuard.open("close");
22419        }
22420
22421        @Override
22422        protected void finalize() throws Throwable {
22423            try {
22424                mCloseGuard.warnIfOpen();
22425                close();
22426            } finally {
22427                super.finalize();
22428            }
22429        }
22430
22431        @Override
22432        public void close() {
22433            mCloseGuard.close();
22434            if (mClosed.compareAndSet(false, true)) {
22435                synchronized (mPackages) {
22436                    if (mWeFroze) {
22437                        mFrozenPackages.remove(mPackageName);
22438                    }
22439
22440                    if (mChildren != null) {
22441                        for (PackageFreezer freezer : mChildren) {
22442                            freezer.close();
22443                        }
22444                    }
22445                }
22446            }
22447        }
22448    }
22449
22450    /**
22451     * Verify that given package is currently frozen.
22452     */
22453    private void checkPackageFrozen(String packageName) {
22454        synchronized (mPackages) {
22455            if (!mFrozenPackages.contains(packageName)) {
22456                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22457            }
22458        }
22459    }
22460
22461    @Override
22462    public int movePackage(final String packageName, final String volumeUuid) {
22463        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22464
22465        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22466        final int moveId = mNextMoveId.getAndIncrement();
22467        mHandler.post(new Runnable() {
22468            @Override
22469            public void run() {
22470                try {
22471                    movePackageInternal(packageName, volumeUuid, moveId, user);
22472                } catch (PackageManagerException e) {
22473                    Slog.w(TAG, "Failed to move " + packageName, e);
22474                    mMoveCallbacks.notifyStatusChanged(moveId,
22475                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22476                }
22477            }
22478        });
22479        return moveId;
22480    }
22481
22482    private void movePackageInternal(final String packageName, final String volumeUuid,
22483            final int moveId, UserHandle user) throws PackageManagerException {
22484        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22485        final PackageManager pm = mContext.getPackageManager();
22486
22487        final boolean currentAsec;
22488        final String currentVolumeUuid;
22489        final File codeFile;
22490        final String installerPackageName;
22491        final String packageAbiOverride;
22492        final int appId;
22493        final String seinfo;
22494        final String label;
22495        final int targetSdkVersion;
22496        final PackageFreezer freezer;
22497        final int[] installedUserIds;
22498
22499        // reader
22500        synchronized (mPackages) {
22501            final PackageParser.Package pkg = mPackages.get(packageName);
22502            final PackageSetting ps = mSettings.mPackages.get(packageName);
22503            if (pkg == null || ps == null) {
22504                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22505            }
22506
22507            if (pkg.applicationInfo.isSystemApp()) {
22508                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22509                        "Cannot move system application");
22510            }
22511
22512            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22513            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22514                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22515            if (isInternalStorage && !allow3rdPartyOnInternal) {
22516                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22517                        "3rd party apps are not allowed on internal storage");
22518            }
22519
22520            if (pkg.applicationInfo.isExternalAsec()) {
22521                currentAsec = true;
22522                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22523            } else if (pkg.applicationInfo.isForwardLocked()) {
22524                currentAsec = true;
22525                currentVolumeUuid = "forward_locked";
22526            } else {
22527                currentAsec = false;
22528                currentVolumeUuid = ps.volumeUuid;
22529
22530                final File probe = new File(pkg.codePath);
22531                final File probeOat = new File(probe, "oat");
22532                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22533                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22534                            "Move only supported for modern cluster style installs");
22535                }
22536            }
22537
22538            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22539                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22540                        "Package already moved to " + volumeUuid);
22541            }
22542            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22543                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22544                        "Device admin cannot be moved");
22545            }
22546
22547            if (mFrozenPackages.contains(packageName)) {
22548                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22549                        "Failed to move already frozen package");
22550            }
22551
22552            codeFile = new File(pkg.codePath);
22553            installerPackageName = ps.installerPackageName;
22554            packageAbiOverride = ps.cpuAbiOverrideString;
22555            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22556            seinfo = pkg.applicationInfo.seInfo;
22557            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22558            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22559            freezer = freezePackage(packageName, "movePackageInternal");
22560            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22561        }
22562
22563        final Bundle extras = new Bundle();
22564        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22565        extras.putString(Intent.EXTRA_TITLE, label);
22566        mMoveCallbacks.notifyCreated(moveId, extras);
22567
22568        int installFlags;
22569        final boolean moveCompleteApp;
22570        final File measurePath;
22571
22572        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22573            installFlags = INSTALL_INTERNAL;
22574            moveCompleteApp = !currentAsec;
22575            measurePath = Environment.getDataAppDirectory(volumeUuid);
22576        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22577            installFlags = INSTALL_EXTERNAL;
22578            moveCompleteApp = false;
22579            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22580        } else {
22581            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22582            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22583                    || !volume.isMountedWritable()) {
22584                freezer.close();
22585                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22586                        "Move location not mounted private volume");
22587            }
22588
22589            Preconditions.checkState(!currentAsec);
22590
22591            installFlags = INSTALL_INTERNAL;
22592            moveCompleteApp = true;
22593            measurePath = Environment.getDataAppDirectory(volumeUuid);
22594        }
22595
22596        final PackageStats stats = new PackageStats(null, -1);
22597        synchronized (mInstaller) {
22598            for (int userId : installedUserIds) {
22599                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22600                    freezer.close();
22601                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22602                            "Failed to measure package size");
22603                }
22604            }
22605        }
22606
22607        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22608                + stats.dataSize);
22609
22610        final long startFreeBytes = measurePath.getUsableSpace();
22611        final long sizeBytes;
22612        if (moveCompleteApp) {
22613            sizeBytes = stats.codeSize + stats.dataSize;
22614        } else {
22615            sizeBytes = stats.codeSize;
22616        }
22617
22618        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22619            freezer.close();
22620            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22621                    "Not enough free space to move");
22622        }
22623
22624        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22625
22626        final CountDownLatch installedLatch = new CountDownLatch(1);
22627        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22628            @Override
22629            public void onUserActionRequired(Intent intent) throws RemoteException {
22630                throw new IllegalStateException();
22631            }
22632
22633            @Override
22634            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22635                    Bundle extras) throws RemoteException {
22636                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22637                        + PackageManager.installStatusToString(returnCode, msg));
22638
22639                installedLatch.countDown();
22640                freezer.close();
22641
22642                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22643                switch (status) {
22644                    case PackageInstaller.STATUS_SUCCESS:
22645                        mMoveCallbacks.notifyStatusChanged(moveId,
22646                                PackageManager.MOVE_SUCCEEDED);
22647                        break;
22648                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22649                        mMoveCallbacks.notifyStatusChanged(moveId,
22650                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22651                        break;
22652                    default:
22653                        mMoveCallbacks.notifyStatusChanged(moveId,
22654                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22655                        break;
22656                }
22657            }
22658        };
22659
22660        final MoveInfo move;
22661        if (moveCompleteApp) {
22662            // Kick off a thread to report progress estimates
22663            new Thread() {
22664                @Override
22665                public void run() {
22666                    while (true) {
22667                        try {
22668                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22669                                break;
22670                            }
22671                        } catch (InterruptedException ignored) {
22672                        }
22673
22674                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22675                        final int progress = 10 + (int) MathUtils.constrain(
22676                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22677                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22678                    }
22679                }
22680            }.start();
22681
22682            final String dataAppName = codeFile.getName();
22683            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22684                    dataAppName, appId, seinfo, targetSdkVersion);
22685        } else {
22686            move = null;
22687        }
22688
22689        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22690
22691        final Message msg = mHandler.obtainMessage(INIT_COPY);
22692        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22693        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22694                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22695                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22696                PackageManager.INSTALL_REASON_UNKNOWN);
22697        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22698        msg.obj = params;
22699
22700        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22701                System.identityHashCode(msg.obj));
22702        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22703                System.identityHashCode(msg.obj));
22704
22705        mHandler.sendMessage(msg);
22706    }
22707
22708    @Override
22709    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22710        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22711
22712        final int realMoveId = mNextMoveId.getAndIncrement();
22713        final Bundle extras = new Bundle();
22714        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22715        mMoveCallbacks.notifyCreated(realMoveId, extras);
22716
22717        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22718            @Override
22719            public void onCreated(int moveId, Bundle extras) {
22720                // Ignored
22721            }
22722
22723            @Override
22724            public void onStatusChanged(int moveId, int status, long estMillis) {
22725                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22726            }
22727        };
22728
22729        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22730        storage.setPrimaryStorageUuid(volumeUuid, callback);
22731        return realMoveId;
22732    }
22733
22734    @Override
22735    public int getMoveStatus(int moveId) {
22736        mContext.enforceCallingOrSelfPermission(
22737                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22738        return mMoveCallbacks.mLastStatus.get(moveId);
22739    }
22740
22741    @Override
22742    public void registerMoveCallback(IPackageMoveObserver callback) {
22743        mContext.enforceCallingOrSelfPermission(
22744                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22745        mMoveCallbacks.register(callback);
22746    }
22747
22748    @Override
22749    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22750        mContext.enforceCallingOrSelfPermission(
22751                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22752        mMoveCallbacks.unregister(callback);
22753    }
22754
22755    @Override
22756    public boolean setInstallLocation(int loc) {
22757        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22758                null);
22759        if (getInstallLocation() == loc) {
22760            return true;
22761        }
22762        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22763                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22764            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22765                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22766            return true;
22767        }
22768        return false;
22769   }
22770
22771    @Override
22772    public int getInstallLocation() {
22773        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22774                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22775                PackageHelper.APP_INSTALL_AUTO);
22776    }
22777
22778    /** Called by UserManagerService */
22779    void cleanUpUser(UserManagerService userManager, int userHandle) {
22780        synchronized (mPackages) {
22781            mDirtyUsers.remove(userHandle);
22782            mUserNeedsBadging.delete(userHandle);
22783            mSettings.removeUserLPw(userHandle);
22784            mPendingBroadcasts.remove(userHandle);
22785            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22786            removeUnusedPackagesLPw(userManager, userHandle);
22787        }
22788    }
22789
22790    /**
22791     * We're removing userHandle and would like to remove any downloaded packages
22792     * that are no longer in use by any other user.
22793     * @param userHandle the user being removed
22794     */
22795    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22796        final boolean DEBUG_CLEAN_APKS = false;
22797        int [] users = userManager.getUserIds();
22798        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22799        while (psit.hasNext()) {
22800            PackageSetting ps = psit.next();
22801            if (ps.pkg == null) {
22802                continue;
22803            }
22804            final String packageName = ps.pkg.packageName;
22805            // Skip over if system app
22806            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22807                continue;
22808            }
22809            if (DEBUG_CLEAN_APKS) {
22810                Slog.i(TAG, "Checking package " + packageName);
22811            }
22812            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22813            if (keep) {
22814                if (DEBUG_CLEAN_APKS) {
22815                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22816                }
22817            } else {
22818                for (int i = 0; i < users.length; i++) {
22819                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22820                        keep = true;
22821                        if (DEBUG_CLEAN_APKS) {
22822                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22823                                    + users[i]);
22824                        }
22825                        break;
22826                    }
22827                }
22828            }
22829            if (!keep) {
22830                if (DEBUG_CLEAN_APKS) {
22831                    Slog.i(TAG, "  Removing package " + packageName);
22832                }
22833                mHandler.post(new Runnable() {
22834                    public void run() {
22835                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22836                                userHandle, 0);
22837                    } //end run
22838                });
22839            }
22840        }
22841    }
22842
22843    /** Called by UserManagerService */
22844    void createNewUser(int userId, String[] disallowedPackages) {
22845        synchronized (mInstallLock) {
22846            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22847        }
22848        synchronized (mPackages) {
22849            scheduleWritePackageRestrictionsLocked(userId);
22850            scheduleWritePackageListLocked(userId);
22851            applyFactoryDefaultBrowserLPw(userId);
22852            primeDomainVerificationsLPw(userId);
22853        }
22854    }
22855
22856    void onNewUserCreated(final int userId) {
22857        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22858        // If permission review for legacy apps is required, we represent
22859        // dagerous permissions for such apps as always granted runtime
22860        // permissions to keep per user flag state whether review is needed.
22861        // Hence, if a new user is added we have to propagate dangerous
22862        // permission grants for these legacy apps.
22863        if (mPermissionReviewRequired) {
22864            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22865                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22866        }
22867    }
22868
22869    @Override
22870    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22871        mContext.enforceCallingOrSelfPermission(
22872                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22873                "Only package verification agents can read the verifier device identity");
22874
22875        synchronized (mPackages) {
22876            return mSettings.getVerifierDeviceIdentityLPw();
22877        }
22878    }
22879
22880    @Override
22881    public void setPermissionEnforced(String permission, boolean enforced) {
22882        // TODO: Now that we no longer change GID for storage, this should to away.
22883        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22884                "setPermissionEnforced");
22885        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22886            synchronized (mPackages) {
22887                if (mSettings.mReadExternalStorageEnforced == null
22888                        || mSettings.mReadExternalStorageEnforced != enforced) {
22889                    mSettings.mReadExternalStorageEnforced = enforced;
22890                    mSettings.writeLPr();
22891                }
22892            }
22893            // kill any non-foreground processes so we restart them and
22894            // grant/revoke the GID.
22895            final IActivityManager am = ActivityManager.getService();
22896            if (am != null) {
22897                final long token = Binder.clearCallingIdentity();
22898                try {
22899                    am.killProcessesBelowForeground("setPermissionEnforcement");
22900                } catch (RemoteException e) {
22901                } finally {
22902                    Binder.restoreCallingIdentity(token);
22903                }
22904            }
22905        } else {
22906            throw new IllegalArgumentException("No selective enforcement for " + permission);
22907        }
22908    }
22909
22910    @Override
22911    @Deprecated
22912    public boolean isPermissionEnforced(String permission) {
22913        return true;
22914    }
22915
22916    @Override
22917    public boolean isStorageLow() {
22918        final long token = Binder.clearCallingIdentity();
22919        try {
22920            final DeviceStorageMonitorInternal
22921                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22922            if (dsm != null) {
22923                return dsm.isMemoryLow();
22924            } else {
22925                return false;
22926            }
22927        } finally {
22928            Binder.restoreCallingIdentity(token);
22929        }
22930    }
22931
22932    @Override
22933    public IPackageInstaller getPackageInstaller() {
22934        return mInstallerService;
22935    }
22936
22937    private boolean userNeedsBadging(int userId) {
22938        int index = mUserNeedsBadging.indexOfKey(userId);
22939        if (index < 0) {
22940            final UserInfo userInfo;
22941            final long token = Binder.clearCallingIdentity();
22942            try {
22943                userInfo = sUserManager.getUserInfo(userId);
22944            } finally {
22945                Binder.restoreCallingIdentity(token);
22946            }
22947            final boolean b;
22948            if (userInfo != null && userInfo.isManagedProfile()) {
22949                b = true;
22950            } else {
22951                b = false;
22952            }
22953            mUserNeedsBadging.put(userId, b);
22954            return b;
22955        }
22956        return mUserNeedsBadging.valueAt(index);
22957    }
22958
22959    @Override
22960    public KeySet getKeySetByAlias(String packageName, String alias) {
22961        if (packageName == null || alias == null) {
22962            return null;
22963        }
22964        synchronized(mPackages) {
22965            final PackageParser.Package pkg = mPackages.get(packageName);
22966            if (pkg == null) {
22967                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22968                throw new IllegalArgumentException("Unknown package: " + packageName);
22969            }
22970            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22971            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22972        }
22973    }
22974
22975    @Override
22976    public KeySet getSigningKeySet(String packageName) {
22977        if (packageName == null) {
22978            return null;
22979        }
22980        synchronized(mPackages) {
22981            final PackageParser.Package pkg = mPackages.get(packageName);
22982            if (pkg == null) {
22983                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22984                throw new IllegalArgumentException("Unknown package: " + packageName);
22985            }
22986            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22987                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22988                throw new SecurityException("May not access signing KeySet of other apps.");
22989            }
22990            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22991            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22992        }
22993    }
22994
22995    @Override
22996    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22997        if (packageName == null || ks == null) {
22998            return false;
22999        }
23000        synchronized(mPackages) {
23001            final PackageParser.Package pkg = mPackages.get(packageName);
23002            if (pkg == null) {
23003                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23004                throw new IllegalArgumentException("Unknown package: " + packageName);
23005            }
23006            IBinder ksh = ks.getToken();
23007            if (ksh instanceof KeySetHandle) {
23008                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23009                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23010            }
23011            return false;
23012        }
23013    }
23014
23015    @Override
23016    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23017        if (packageName == null || ks == null) {
23018            return false;
23019        }
23020        synchronized(mPackages) {
23021            final PackageParser.Package pkg = mPackages.get(packageName);
23022            if (pkg == null) {
23023                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23024                throw new IllegalArgumentException("Unknown package: " + packageName);
23025            }
23026            IBinder ksh = ks.getToken();
23027            if (ksh instanceof KeySetHandle) {
23028                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23029                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23030            }
23031            return false;
23032        }
23033    }
23034
23035    private void deletePackageIfUnusedLPr(final String packageName) {
23036        PackageSetting ps = mSettings.mPackages.get(packageName);
23037        if (ps == null) {
23038            return;
23039        }
23040        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23041            // TODO Implement atomic delete if package is unused
23042            // It is currently possible that the package will be deleted even if it is installed
23043            // after this method returns.
23044            mHandler.post(new Runnable() {
23045                public void run() {
23046                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23047                            0, PackageManager.DELETE_ALL_USERS);
23048                }
23049            });
23050        }
23051    }
23052
23053    /**
23054     * Check and throw if the given before/after packages would be considered a
23055     * downgrade.
23056     */
23057    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23058            throws PackageManagerException {
23059        if (after.versionCode < before.mVersionCode) {
23060            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23061                    "Update version code " + after.versionCode + " is older than current "
23062                    + before.mVersionCode);
23063        } else if (after.versionCode == before.mVersionCode) {
23064            if (after.baseRevisionCode < before.baseRevisionCode) {
23065                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23066                        "Update base revision code " + after.baseRevisionCode
23067                        + " is older than current " + before.baseRevisionCode);
23068            }
23069
23070            if (!ArrayUtils.isEmpty(after.splitNames)) {
23071                for (int i = 0; i < after.splitNames.length; i++) {
23072                    final String splitName = after.splitNames[i];
23073                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23074                    if (j != -1) {
23075                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23076                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23077                                    "Update split " + splitName + " revision code "
23078                                    + after.splitRevisionCodes[i] + " is older than current "
23079                                    + before.splitRevisionCodes[j]);
23080                        }
23081                    }
23082                }
23083            }
23084        }
23085    }
23086
23087    private static class MoveCallbacks extends Handler {
23088        private static final int MSG_CREATED = 1;
23089        private static final int MSG_STATUS_CHANGED = 2;
23090
23091        private final RemoteCallbackList<IPackageMoveObserver>
23092                mCallbacks = new RemoteCallbackList<>();
23093
23094        private final SparseIntArray mLastStatus = new SparseIntArray();
23095
23096        public MoveCallbacks(Looper looper) {
23097            super(looper);
23098        }
23099
23100        public void register(IPackageMoveObserver callback) {
23101            mCallbacks.register(callback);
23102        }
23103
23104        public void unregister(IPackageMoveObserver callback) {
23105            mCallbacks.unregister(callback);
23106        }
23107
23108        @Override
23109        public void handleMessage(Message msg) {
23110            final SomeArgs args = (SomeArgs) msg.obj;
23111            final int n = mCallbacks.beginBroadcast();
23112            for (int i = 0; i < n; i++) {
23113                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23114                try {
23115                    invokeCallback(callback, msg.what, args);
23116                } catch (RemoteException ignored) {
23117                }
23118            }
23119            mCallbacks.finishBroadcast();
23120            args.recycle();
23121        }
23122
23123        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23124                throws RemoteException {
23125            switch (what) {
23126                case MSG_CREATED: {
23127                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23128                    break;
23129                }
23130                case MSG_STATUS_CHANGED: {
23131                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23132                    break;
23133                }
23134            }
23135        }
23136
23137        private void notifyCreated(int moveId, Bundle extras) {
23138            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23139
23140            final SomeArgs args = SomeArgs.obtain();
23141            args.argi1 = moveId;
23142            args.arg2 = extras;
23143            obtainMessage(MSG_CREATED, args).sendToTarget();
23144        }
23145
23146        private void notifyStatusChanged(int moveId, int status) {
23147            notifyStatusChanged(moveId, status, -1);
23148        }
23149
23150        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23151            Slog.v(TAG, "Move " + moveId + " status " + status);
23152
23153            final SomeArgs args = SomeArgs.obtain();
23154            args.argi1 = moveId;
23155            args.argi2 = status;
23156            args.arg3 = estMillis;
23157            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23158
23159            synchronized (mLastStatus) {
23160                mLastStatus.put(moveId, status);
23161            }
23162        }
23163    }
23164
23165    private final static class OnPermissionChangeListeners extends Handler {
23166        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23167
23168        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23169                new RemoteCallbackList<>();
23170
23171        public OnPermissionChangeListeners(Looper looper) {
23172            super(looper);
23173        }
23174
23175        @Override
23176        public void handleMessage(Message msg) {
23177            switch (msg.what) {
23178                case MSG_ON_PERMISSIONS_CHANGED: {
23179                    final int uid = msg.arg1;
23180                    handleOnPermissionsChanged(uid);
23181                } break;
23182            }
23183        }
23184
23185        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23186            mPermissionListeners.register(listener);
23187
23188        }
23189
23190        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23191            mPermissionListeners.unregister(listener);
23192        }
23193
23194        public void onPermissionsChanged(int uid) {
23195            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23196                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23197            }
23198        }
23199
23200        private void handleOnPermissionsChanged(int uid) {
23201            final int count = mPermissionListeners.beginBroadcast();
23202            try {
23203                for (int i = 0; i < count; i++) {
23204                    IOnPermissionsChangeListener callback = mPermissionListeners
23205                            .getBroadcastItem(i);
23206                    try {
23207                        callback.onPermissionsChanged(uid);
23208                    } catch (RemoteException e) {
23209                        Log.e(TAG, "Permission listener is dead", e);
23210                    }
23211                }
23212            } finally {
23213                mPermissionListeners.finishBroadcast();
23214            }
23215        }
23216    }
23217
23218    private class PackageManagerInternalImpl extends PackageManagerInternal {
23219        @Override
23220        public void setLocationPackagesProvider(PackagesProvider provider) {
23221            synchronized (mPackages) {
23222                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23223            }
23224        }
23225
23226        @Override
23227        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23228            synchronized (mPackages) {
23229                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23230            }
23231        }
23232
23233        @Override
23234        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23235            synchronized (mPackages) {
23236                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23237            }
23238        }
23239
23240        @Override
23241        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23242            synchronized (mPackages) {
23243                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23244            }
23245        }
23246
23247        @Override
23248        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23249            synchronized (mPackages) {
23250                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23251            }
23252        }
23253
23254        @Override
23255        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23256            synchronized (mPackages) {
23257                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23258            }
23259        }
23260
23261        @Override
23262        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23263            synchronized (mPackages) {
23264                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23265                        packageName, userId);
23266            }
23267        }
23268
23269        @Override
23270        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23271            synchronized (mPackages) {
23272                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23273                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23274                        packageName, userId);
23275            }
23276        }
23277
23278        @Override
23279        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23280            synchronized (mPackages) {
23281                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23282                        packageName, userId);
23283            }
23284        }
23285
23286        @Override
23287        public void setKeepUninstalledPackages(final List<String> packageList) {
23288            Preconditions.checkNotNull(packageList);
23289            List<String> removedFromList = null;
23290            synchronized (mPackages) {
23291                if (mKeepUninstalledPackages != null) {
23292                    final int packagesCount = mKeepUninstalledPackages.size();
23293                    for (int i = 0; i < packagesCount; i++) {
23294                        String oldPackage = mKeepUninstalledPackages.get(i);
23295                        if (packageList != null && packageList.contains(oldPackage)) {
23296                            continue;
23297                        }
23298                        if (removedFromList == null) {
23299                            removedFromList = new ArrayList<>();
23300                        }
23301                        removedFromList.add(oldPackage);
23302                    }
23303                }
23304                mKeepUninstalledPackages = new ArrayList<>(packageList);
23305                if (removedFromList != null) {
23306                    final int removedCount = removedFromList.size();
23307                    for (int i = 0; i < removedCount; i++) {
23308                        deletePackageIfUnusedLPr(removedFromList.get(i));
23309                    }
23310                }
23311            }
23312        }
23313
23314        @Override
23315        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23316            synchronized (mPackages) {
23317                // If we do not support permission review, done.
23318                if (!mPermissionReviewRequired) {
23319                    return false;
23320                }
23321
23322                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23323                if (packageSetting == null) {
23324                    return false;
23325                }
23326
23327                // Permission review applies only to apps not supporting the new permission model.
23328                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23329                    return false;
23330                }
23331
23332                // Legacy apps have the permission and get user consent on launch.
23333                PermissionsState permissionsState = packageSetting.getPermissionsState();
23334                return permissionsState.isPermissionReviewRequired(userId);
23335            }
23336        }
23337
23338        @Override
23339        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23340            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23341        }
23342
23343        @Override
23344        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23345                int userId) {
23346            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23347        }
23348
23349        @Override
23350        public void setDeviceAndProfileOwnerPackages(
23351                int deviceOwnerUserId, String deviceOwnerPackage,
23352                SparseArray<String> profileOwnerPackages) {
23353            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23354                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23355        }
23356
23357        @Override
23358        public boolean isPackageDataProtected(int userId, String packageName) {
23359            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23360        }
23361
23362        @Override
23363        public boolean isPackageEphemeral(int userId, String packageName) {
23364            synchronized (mPackages) {
23365                final PackageSetting ps = mSettings.mPackages.get(packageName);
23366                return ps != null ? ps.getInstantApp(userId) : false;
23367            }
23368        }
23369
23370        @Override
23371        public boolean wasPackageEverLaunched(String packageName, int userId) {
23372            synchronized (mPackages) {
23373                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23374            }
23375        }
23376
23377        @Override
23378        public void grantRuntimePermission(String packageName, String name, int userId,
23379                boolean overridePolicy) {
23380            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23381                    overridePolicy);
23382        }
23383
23384        @Override
23385        public void revokeRuntimePermission(String packageName, String name, int userId,
23386                boolean overridePolicy) {
23387            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23388                    overridePolicy);
23389        }
23390
23391        @Override
23392        public String getNameForUid(int uid) {
23393            return PackageManagerService.this.getNameForUid(uid);
23394        }
23395
23396        @Override
23397        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23398                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23399            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23400                    responseObj, origIntent, resolvedType, callingPackage, userId);
23401        }
23402
23403        @Override
23404        public void grantEphemeralAccess(int userId, Intent intent,
23405                int targetAppId, int ephemeralAppId) {
23406            synchronized (mPackages) {
23407                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23408                        targetAppId, ephemeralAppId);
23409            }
23410        }
23411
23412        @Override
23413        public boolean isInstantAppInstallerComponent(ComponentName component) {
23414            synchronized (mPackages) {
23415                return mInstantAppInstallerActivity != null
23416                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23417            }
23418        }
23419
23420        @Override
23421        public void pruneInstantApps() {
23422            synchronized (mPackages) {
23423                mInstantAppRegistry.pruneInstantAppsLPw();
23424            }
23425        }
23426
23427        @Override
23428        public String getSetupWizardPackageName() {
23429            return mSetupWizardPackage;
23430        }
23431
23432        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23433            if (policy != null) {
23434                mExternalSourcesPolicy = policy;
23435            }
23436        }
23437
23438        @Override
23439        public boolean isPackagePersistent(String packageName) {
23440            synchronized (mPackages) {
23441                PackageParser.Package pkg = mPackages.get(packageName);
23442                return pkg != null
23443                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23444                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23445                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23446                        : false;
23447            }
23448        }
23449
23450        @Override
23451        public List<PackageInfo> getOverlayPackages(int userId) {
23452            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23453            synchronized (mPackages) {
23454                for (PackageParser.Package p : mPackages.values()) {
23455                    if (p.mOverlayTarget != null) {
23456                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23457                        if (pkg != null) {
23458                            overlayPackages.add(pkg);
23459                        }
23460                    }
23461                }
23462            }
23463            return overlayPackages;
23464        }
23465
23466        @Override
23467        public List<String> getTargetPackageNames(int userId) {
23468            List<String> targetPackages = new ArrayList<>();
23469            synchronized (mPackages) {
23470                for (PackageParser.Package p : mPackages.values()) {
23471                    if (p.mOverlayTarget == null) {
23472                        targetPackages.add(p.packageName);
23473                    }
23474                }
23475            }
23476            return targetPackages;
23477        }
23478
23479        @Override
23480        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23481                @Nullable List<String> overlayPackageNames) {
23482            synchronized (mPackages) {
23483                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23484                    Slog.e(TAG, "failed to find package " + targetPackageName);
23485                    return false;
23486                }
23487
23488                ArrayList<String> paths = null;
23489                if (overlayPackageNames != null) {
23490                    final int N = overlayPackageNames.size();
23491                    paths = new ArrayList<>(N);
23492                    for (int i = 0; i < N; i++) {
23493                        final String packageName = overlayPackageNames.get(i);
23494                        final PackageParser.Package pkg = mPackages.get(packageName);
23495                        if (pkg == null) {
23496                            Slog.e(TAG, "failed to find package " + packageName);
23497                            return false;
23498                        }
23499                        paths.add(pkg.baseCodePath);
23500                    }
23501                }
23502
23503                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23504                    mEnabledOverlayPaths.get(userId);
23505                if (userSpecificOverlays == null) {
23506                    userSpecificOverlays = new ArrayMap<>();
23507                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23508                }
23509
23510                if (paths != null && paths.size() > 0) {
23511                    userSpecificOverlays.put(targetPackageName, paths);
23512                } else {
23513                    userSpecificOverlays.remove(targetPackageName);
23514                }
23515                return true;
23516            }
23517        }
23518
23519        @Override
23520        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23521                int flags, int userId) {
23522            return resolveIntentInternal(
23523                    intent, resolvedType, flags, userId, true /*includeInstantApps*/);
23524        }
23525
23526        @Override
23527        public ResolveInfo resolveService(Intent intent, String resolvedType,
23528                int flags, int userId, int callingUid) {
23529            return resolveServiceInternal(
23530                    intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/);
23531        }
23532
23533        @Override
23534        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23535            synchronized (mPackages) {
23536                mIsolatedOwners.put(isolatedUid, ownerUid);
23537            }
23538        }
23539
23540        @Override
23541        public void removeIsolatedUid(int isolatedUid) {
23542            synchronized (mPackages) {
23543                mIsolatedOwners.delete(isolatedUid);
23544            }
23545        }
23546    }
23547
23548    @Override
23549    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23550        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23551        synchronized (mPackages) {
23552            final long identity = Binder.clearCallingIdentity();
23553            try {
23554                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23555                        packageNames, userId);
23556            } finally {
23557                Binder.restoreCallingIdentity(identity);
23558            }
23559        }
23560    }
23561
23562    @Override
23563    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23564        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23565        synchronized (mPackages) {
23566            final long identity = Binder.clearCallingIdentity();
23567            try {
23568                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23569                        packageNames, userId);
23570            } finally {
23571                Binder.restoreCallingIdentity(identity);
23572            }
23573        }
23574    }
23575
23576    private static void enforceSystemOrPhoneCaller(String tag) {
23577        int callingUid = Binder.getCallingUid();
23578        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23579            throw new SecurityException(
23580                    "Cannot call " + tag + " from UID " + callingUid);
23581        }
23582    }
23583
23584    boolean isHistoricalPackageUsageAvailable() {
23585        return mPackageUsage.isHistoricalPackageUsageAvailable();
23586    }
23587
23588    /**
23589     * Return a <b>copy</b> of the collection of packages known to the package manager.
23590     * @return A copy of the values of mPackages.
23591     */
23592    Collection<PackageParser.Package> getPackages() {
23593        synchronized (mPackages) {
23594            return new ArrayList<>(mPackages.values());
23595        }
23596    }
23597
23598    /**
23599     * Logs process start information (including base APK hash) to the security log.
23600     * @hide
23601     */
23602    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23603            String apkFile, int pid) {
23604        if (!SecurityLog.isLoggingEnabled()) {
23605            return;
23606        }
23607        Bundle data = new Bundle();
23608        data.putLong("startTimestamp", System.currentTimeMillis());
23609        data.putString("processName", processName);
23610        data.putInt("uid", uid);
23611        data.putString("seinfo", seinfo);
23612        data.putString("apkFile", apkFile);
23613        data.putInt("pid", pid);
23614        Message msg = mProcessLoggingHandler.obtainMessage(
23615                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23616        msg.setData(data);
23617        mProcessLoggingHandler.sendMessage(msg);
23618    }
23619
23620    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23621        return mCompilerStats.getPackageStats(pkgName);
23622    }
23623
23624    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23625        return getOrCreateCompilerPackageStats(pkg.packageName);
23626    }
23627
23628    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23629        return mCompilerStats.getOrCreatePackageStats(pkgName);
23630    }
23631
23632    public void deleteCompilerPackageStats(String pkgName) {
23633        mCompilerStats.deletePackageStats(pkgName);
23634    }
23635
23636    @Override
23637    public int getInstallReason(String packageName, int userId) {
23638        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23639                true /* requireFullPermission */, false /* checkShell */,
23640                "get install reason");
23641        synchronized (mPackages) {
23642            final PackageSetting ps = mSettings.mPackages.get(packageName);
23643            if (ps != null) {
23644                return ps.getInstallReason(userId);
23645            }
23646        }
23647        return PackageManager.INSTALL_REASON_UNKNOWN;
23648    }
23649
23650    @Override
23651    public boolean canRequestPackageInstalls(String packageName, int userId) {
23652        int callingUid = Binder.getCallingUid();
23653        int uid = getPackageUid(packageName, 0, userId);
23654        if (callingUid != uid && callingUid != Process.ROOT_UID
23655                && callingUid != Process.SYSTEM_UID) {
23656            throw new SecurityException(
23657                    "Caller uid " + callingUid + " does not own package " + packageName);
23658        }
23659        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23660        if (info == null) {
23661            return false;
23662        }
23663        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23664            throw new UnsupportedOperationException(
23665                    "Operation only supported on apps targeting Android O or higher");
23666        }
23667        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23668        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23669        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23670            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23671        }
23672        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23673            return false;
23674        }
23675        if (mExternalSourcesPolicy != null) {
23676            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23677            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23678                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23679            }
23680        }
23681        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23682    }
23683
23684    @Override
23685    public ComponentName getInstantAppResolverSettingsComponent() {
23686        return mInstantAppResolverSettingsComponent;
23687    }
23688
23689    @Override
23690    public ComponentName getInstantAppInstallerComponent() {
23691        return mInstantAppInstallerActivity == null
23692                ? null : mInstantAppInstallerActivity.getComponentName();
23693    }
23694
23695    @Override
23696    public String getInstantAppAndroidId(String packageName, int userId) {
23697        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23698                "getInstantAppAndroidId");
23699        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23700                true /* requireFullPermission */, false /* checkShell */,
23701                "getInstantAppAndroidId");
23702        // Make sure the target is an Instant App.
23703        if (!isInstantApp(packageName, userId)) {
23704            return null;
23705        }
23706        synchronized (mPackages) {
23707            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23708        }
23709    }
23710}
23711
23712interface PackageSender {
23713    void sendPackageBroadcast(final String action, final String pkg,
23714        final Bundle extras, final int flags, final String targetPkg,
23715        final IIntentReceiver finishedReceiver, final int[] userIds);
23716    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
23717        int appId, int... userIds);
23718}
23719