PackageManagerService.java revision ee3b42af3f23c37cbd2799c1527f89ac623844be
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
96import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
97import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
104
105import android.Manifest;
106import android.annotation.NonNull;
107import android.annotation.Nullable;
108import android.app.ActivityManager;
109import android.app.AppOpsManager;
110import android.app.IActivityManager;
111import android.app.ResourcesManager;
112import android.app.admin.IDevicePolicyManager;
113import android.app.admin.SecurityLog;
114import android.app.backup.IBackupManager;
115import android.content.BroadcastReceiver;
116import android.content.ComponentName;
117import android.content.ContentResolver;
118import android.content.Context;
119import android.content.IIntentReceiver;
120import android.content.Intent;
121import android.content.IntentFilter;
122import android.content.IntentSender;
123import android.content.IntentSender.SendIntentException;
124import android.content.ServiceConnection;
125import android.content.pm.ActivityInfo;
126import android.content.pm.ApplicationInfo;
127import android.content.pm.AppsQueryHelper;
128import android.content.pm.ChangedPackages;
129import android.content.pm.ComponentInfo;
130import android.content.pm.InstantAppRequest;
131import android.content.pm.AuxiliaryResolveInfo;
132import android.content.pm.FallbackCategoryProvider;
133import android.content.pm.FeatureInfo;
134import android.content.pm.IOnPermissionsChangeListener;
135import android.content.pm.IPackageDataObserver;
136import android.content.pm.IPackageDeleteObserver;
137import android.content.pm.IPackageDeleteObserver2;
138import android.content.pm.IPackageInstallObserver2;
139import android.content.pm.IPackageInstaller;
140import android.content.pm.IPackageManager;
141import android.content.pm.IPackageMoveObserver;
142import android.content.pm.IPackageStatsObserver;
143import android.content.pm.InstantAppInfo;
144import android.content.pm.InstantAppResolveInfo;
145import android.content.pm.InstrumentationInfo;
146import android.content.pm.IntentFilterVerificationInfo;
147import android.content.pm.KeySet;
148import android.content.pm.PackageCleanItem;
149import android.content.pm.PackageInfo;
150import android.content.pm.PackageInfoLite;
151import android.content.pm.PackageInstaller;
152import android.content.pm.PackageManager;
153import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
154import android.content.pm.PackageManagerInternal;
155import android.content.pm.PackageParser;
156import android.content.pm.PackageParser.ActivityIntentInfo;
157import android.content.pm.PackageParser.PackageLite;
158import android.content.pm.PackageParser.PackageParserException;
159import android.content.pm.PackageStats;
160import android.content.pm.PackageUserState;
161import android.content.pm.ParceledListSlice;
162import android.content.pm.PermissionGroupInfo;
163import android.content.pm.PermissionInfo;
164import android.content.pm.ProviderInfo;
165import android.content.pm.ResolveInfo;
166import android.content.pm.ServiceInfo;
167import android.content.pm.SharedLibraryInfo;
168import android.content.pm.Signature;
169import android.content.pm.UserInfo;
170import android.content.pm.VerifierDeviceIdentity;
171import android.content.pm.VerifierInfo;
172import android.content.pm.VersionedPackage;
173import android.content.res.Resources;
174import android.database.ContentObserver;
175import android.graphics.Bitmap;
176import android.hardware.display.DisplayManager;
177import android.net.Uri;
178import android.os.Binder;
179import android.os.Build;
180import android.os.Bundle;
181import android.os.Debug;
182import android.os.Environment;
183import android.os.Environment.UserEnvironment;
184import android.os.FileUtils;
185import android.os.Handler;
186import android.os.IBinder;
187import android.os.Looper;
188import android.os.Message;
189import android.os.Parcel;
190import android.os.ParcelFileDescriptor;
191import android.os.PatternMatcher;
192import android.os.Process;
193import android.os.RemoteCallbackList;
194import android.os.RemoteException;
195import android.os.ResultReceiver;
196import android.os.SELinux;
197import android.os.ServiceManager;
198import android.os.ShellCallback;
199import android.os.SystemClock;
200import android.os.SystemProperties;
201import android.os.Trace;
202import android.os.UserHandle;
203import android.os.UserManager;
204import android.os.UserManagerInternal;
205import android.os.storage.IStorageManager;
206import android.os.storage.StorageEventListener;
207import android.os.storage.StorageManager;
208import android.os.storage.StorageManagerInternal;
209import android.os.storage.VolumeInfo;
210import android.os.storage.VolumeRecord;
211import android.provider.Settings.Global;
212import android.provider.Settings.Secure;
213import android.security.KeyStore;
214import android.security.SystemKeyStore;
215import android.service.pm.PackageServiceDumpProto;
216import android.system.ErrnoException;
217import android.system.Os;
218import android.text.TextUtils;
219import android.text.format.DateUtils;
220import android.util.ArrayMap;
221import android.util.ArraySet;
222import android.util.Base64;
223import android.util.DisplayMetrics;
224import android.util.EventLog;
225import android.util.ExceptionUtils;
226import android.util.Log;
227import android.util.LogPrinter;
228import android.util.MathUtils;
229import android.util.PackageUtils;
230import android.util.Pair;
231import android.util.PrintStreamPrinter;
232import android.util.Slog;
233import android.util.SparseArray;
234import android.util.SparseBooleanArray;
235import android.util.SparseIntArray;
236import android.util.Xml;
237import android.util.jar.StrictJarFile;
238import android.util.proto.ProtoOutputStream;
239import android.view.Display;
240
241import com.android.internal.R;
242import com.android.internal.annotations.GuardedBy;
243import com.android.internal.app.IMediaContainerService;
244import com.android.internal.app.ResolverActivity;
245import com.android.internal.content.NativeLibraryHelper;
246import com.android.internal.content.PackageHelper;
247import com.android.internal.logging.MetricsLogger;
248import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
249import com.android.internal.os.IParcelFileDescriptorFactory;
250import com.android.internal.os.RoSystemProperties;
251import com.android.internal.os.SomeArgs;
252import com.android.internal.os.Zygote;
253import com.android.internal.telephony.CarrierAppUtils;
254import com.android.internal.util.ArrayUtils;
255import com.android.internal.util.ConcurrentUtils;
256import com.android.internal.util.DumpUtils;
257import com.android.internal.util.FastPrintWriter;
258import com.android.internal.util.FastXmlSerializer;
259import com.android.internal.util.IndentingPrintWriter;
260import com.android.internal.util.Preconditions;
261import com.android.internal.util.XmlUtils;
262import com.android.server.AttributeCache;
263import com.android.server.DeviceIdleController;
264import com.android.server.EventLogTags;
265import com.android.server.FgThread;
266import com.android.server.IntentResolver;
267import com.android.server.LocalServices;
268import com.android.server.LockGuard;
269import com.android.server.ServiceThread;
270import com.android.server.SystemConfig;
271import com.android.server.SystemServerInitThreadPool;
272import com.android.server.Watchdog;
273import com.android.server.net.NetworkPolicyManagerInternal;
274import com.android.server.pm.Installer.InstallerException;
275import com.android.server.pm.PermissionsState.PermissionState;
276import com.android.server.pm.Settings.DatabaseVersion;
277import com.android.server.pm.Settings.VersionInfo;
278import com.android.server.pm.dex.DexManager;
279import com.android.server.storage.DeviceStorageMonitorInternal;
280
281import dalvik.system.CloseGuard;
282import dalvik.system.DexFile;
283import dalvik.system.VMRuntime;
284
285import libcore.io.IoUtils;
286import libcore.util.EmptyArray;
287
288import org.xmlpull.v1.XmlPullParser;
289import org.xmlpull.v1.XmlPullParserException;
290import org.xmlpull.v1.XmlSerializer;
291
292import java.io.BufferedOutputStream;
293import java.io.BufferedReader;
294import java.io.ByteArrayInputStream;
295import java.io.ByteArrayOutputStream;
296import java.io.File;
297import java.io.FileDescriptor;
298import java.io.FileInputStream;
299import java.io.FileOutputStream;
300import java.io.FileReader;
301import java.io.FilenameFilter;
302import java.io.IOException;
303import java.io.PrintWriter;
304import java.nio.charset.StandardCharsets;
305import java.security.DigestInputStream;
306import java.security.MessageDigest;
307import java.security.NoSuchAlgorithmException;
308import java.security.PublicKey;
309import java.security.SecureRandom;
310import java.security.cert.Certificate;
311import java.security.cert.CertificateEncodingException;
312import java.security.cert.CertificateException;
313import java.text.SimpleDateFormat;
314import java.util.ArrayList;
315import java.util.Arrays;
316import java.util.Collection;
317import java.util.Collections;
318import java.util.Comparator;
319import java.util.Date;
320import java.util.HashMap;
321import java.util.HashSet;
322import java.util.Iterator;
323import java.util.List;
324import java.util.Map;
325import java.util.Objects;
326import java.util.Set;
327import java.util.concurrent.CountDownLatch;
328import java.util.concurrent.Future;
329import java.util.concurrent.TimeUnit;
330import java.util.concurrent.atomic.AtomicBoolean;
331import java.util.concurrent.atomic.AtomicInteger;
332
333/**
334 * Keep track of all those APKs everywhere.
335 * <p>
336 * Internally there are two important locks:
337 * <ul>
338 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
339 * and other related state. It is a fine-grained lock that should only be held
340 * momentarily, as it's one of the most contended locks in the system.
341 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
342 * operations typically involve heavy lifting of application data on disk. Since
343 * {@code installd} is single-threaded, and it's operations can often be slow,
344 * this lock should never be acquired while already holding {@link #mPackages}.
345 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
346 * holding {@link #mInstallLock}.
347 * </ul>
348 * Many internal methods rely on the caller to hold the appropriate locks, and
349 * this contract is expressed through method name suffixes:
350 * <ul>
351 * <li>fooLI(): the caller must hold {@link #mInstallLock}
352 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
353 * being modified must be frozen
354 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
355 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
356 * </ul>
357 * <p>
358 * Because this class is very central to the platform's security; please run all
359 * CTS and unit tests whenever making modifications:
360 *
361 * <pre>
362 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
363 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
364 * </pre>
365 */
366public class PackageManagerService extends IPackageManager.Stub {
367    static final String TAG = "PackageManager";
368    static final boolean DEBUG_SETTINGS = false;
369    static final boolean DEBUG_PREFERRED = false;
370    static final boolean DEBUG_UPGRADE = false;
371    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
372    private static final boolean DEBUG_BACKUP = false;
373    private static final boolean DEBUG_INSTALL = false;
374    private static final boolean DEBUG_REMOVE = false;
375    private static final boolean DEBUG_BROADCASTS = false;
376    private static final boolean DEBUG_SHOW_INFO = false;
377    private static final boolean DEBUG_PACKAGE_INFO = false;
378    private static final boolean DEBUG_INTENT_MATCHING = false;
379    private static final boolean DEBUG_PACKAGE_SCANNING = false;
380    private static final boolean DEBUG_VERIFY = false;
381    private static final boolean DEBUG_FILTERS = false;
382
383    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
384    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
385    // user, but by default initialize to this.
386    public static final boolean DEBUG_DEXOPT = false;
387
388    private static final boolean DEBUG_ABI_SELECTION = false;
389    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
390    private static final boolean DEBUG_TRIAGED_MISSING = false;
391    private static final boolean DEBUG_APP_DATA = false;
392
393    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
394    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
395
396    private static final boolean HIDE_EPHEMERAL_APIS = false;
397
398    private static final boolean ENABLE_FREE_CACHE_V2 =
399            SystemProperties.getBoolean("fw.free_cache_v2", true);
400
401    private static final int RADIO_UID = Process.PHONE_UID;
402    private static final int LOG_UID = Process.LOG_UID;
403    private static final int NFC_UID = Process.NFC_UID;
404    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
405    private static final int SHELL_UID = Process.SHELL_UID;
406
407    // Cap the size of permission trees that 3rd party apps can define
408    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
409
410    // Suffix used during package installation when copying/moving
411    // package apks to install directory.
412    private static final String INSTALL_PACKAGE_SUFFIX = "-";
413
414    static final int SCAN_NO_DEX = 1<<1;
415    static final int SCAN_FORCE_DEX = 1<<2;
416    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
417    static final int SCAN_NEW_INSTALL = 1<<4;
418    static final int SCAN_UPDATE_TIME = 1<<5;
419    static final int SCAN_BOOTING = 1<<6;
420    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
421    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
422    static final int SCAN_REPLACING = 1<<9;
423    static final int SCAN_REQUIRE_KNOWN = 1<<10;
424    static final int SCAN_MOVE = 1<<11;
425    static final int SCAN_INITIAL = 1<<12;
426    static final int SCAN_CHECK_ONLY = 1<<13;
427    static final int SCAN_DONT_KILL_APP = 1<<14;
428    static final int SCAN_IGNORE_FROZEN = 1<<15;
429    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
430    static final int SCAN_AS_INSTANT_APP = 1<<17;
431    static final int SCAN_AS_FULL_APP = 1<<18;
432    /** Should not be with the scan flags */
433    static final int FLAGS_REMOVE_CHATTY = 1<<31;
434
435    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
436
437    private static final int[] EMPTY_INT_ARRAY = new int[0];
438
439    /**
440     * Timeout (in milliseconds) after which the watchdog should declare that
441     * our handler thread is wedged.  The usual default for such things is one
442     * minute but we sometimes do very lengthy I/O operations on this thread,
443     * such as installing multi-gigabyte applications, so ours needs to be longer.
444     */
445    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
446
447    /**
448     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
449     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
450     * settings entry if available, otherwise we use the hardcoded default.  If it's been
451     * more than this long since the last fstrim, we force one during the boot sequence.
452     *
453     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
454     * one gets run at the next available charging+idle time.  This final mandatory
455     * no-fstrim check kicks in only of the other scheduling criteria is never met.
456     */
457    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
458
459    /**
460     * Whether verification is enabled by default.
461     */
462    private static final boolean DEFAULT_VERIFY_ENABLE = true;
463
464    /**
465     * The default maximum time to wait for the verification agent to return in
466     * milliseconds.
467     */
468    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
469
470    /**
471     * The default response for package verification timeout.
472     *
473     * This can be either PackageManager.VERIFICATION_ALLOW or
474     * PackageManager.VERIFICATION_REJECT.
475     */
476    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
477
478    static final String PLATFORM_PACKAGE_NAME = "android";
479
480    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
481
482    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
483            DEFAULT_CONTAINER_PACKAGE,
484            "com.android.defcontainer.DefaultContainerService");
485
486    private static final String KILL_APP_REASON_GIDS_CHANGED =
487            "permission grant or revoke changed gids";
488
489    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
490            "permissions revoked";
491
492    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
493
494    private static final String PACKAGE_SCHEME = "package";
495
496    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
497
498    /** Permission grant: not grant the permission. */
499    private static final int GRANT_DENIED = 1;
500
501    /** Permission grant: grant the permission as an install permission. */
502    private static final int GRANT_INSTALL = 2;
503
504    /** Permission grant: grant the permission as a runtime one. */
505    private static final int GRANT_RUNTIME = 3;
506
507    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
508    private static final int GRANT_UPGRADE = 4;
509
510    /** Canonical intent used to identify what counts as a "web browser" app */
511    private static final Intent sBrowserIntent;
512    static {
513        sBrowserIntent = new Intent();
514        sBrowserIntent.setAction(Intent.ACTION_VIEW);
515        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
516        sBrowserIntent.setData(Uri.parse("http:"));
517    }
518
519    /**
520     * The set of all protected actions [i.e. those actions for which a high priority
521     * intent filter is disallowed].
522     */
523    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
524    static {
525        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
526        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
527        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
528        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
529    }
530
531    // Compilation reasons.
532    public static final int REASON_FIRST_BOOT = 0;
533    public static final int REASON_BOOT = 1;
534    public static final int REASON_INSTALL = 2;
535    public static final int REASON_BACKGROUND_DEXOPT = 3;
536    public static final int REASON_AB_OTA = 4;
537    public static final int REASON_FORCED_DEXOPT = 5;
538
539    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
540
541    /** All dangerous permission names in the same order as the events in MetricsEvent */
542    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
543            Manifest.permission.READ_CALENDAR,
544            Manifest.permission.WRITE_CALENDAR,
545            Manifest.permission.CAMERA,
546            Manifest.permission.READ_CONTACTS,
547            Manifest.permission.WRITE_CONTACTS,
548            Manifest.permission.GET_ACCOUNTS,
549            Manifest.permission.ACCESS_FINE_LOCATION,
550            Manifest.permission.ACCESS_COARSE_LOCATION,
551            Manifest.permission.RECORD_AUDIO,
552            Manifest.permission.READ_PHONE_STATE,
553            Manifest.permission.CALL_PHONE,
554            Manifest.permission.READ_CALL_LOG,
555            Manifest.permission.WRITE_CALL_LOG,
556            Manifest.permission.ADD_VOICEMAIL,
557            Manifest.permission.USE_SIP,
558            Manifest.permission.PROCESS_OUTGOING_CALLS,
559            Manifest.permission.READ_CELL_BROADCASTS,
560            Manifest.permission.BODY_SENSORS,
561            Manifest.permission.SEND_SMS,
562            Manifest.permission.RECEIVE_SMS,
563            Manifest.permission.READ_SMS,
564            Manifest.permission.RECEIVE_WAP_PUSH,
565            Manifest.permission.RECEIVE_MMS,
566            Manifest.permission.READ_EXTERNAL_STORAGE,
567            Manifest.permission.WRITE_EXTERNAL_STORAGE,
568            Manifest.permission.READ_PHONE_NUMBERS,
569            Manifest.permission.ANSWER_PHONE_CALLS);
570
571
572    /**
573     * Version number for the package parser cache. Increment this whenever the format or
574     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
575     */
576    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
577
578    /**
579     * Whether the package parser cache is enabled.
580     */
581    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
582
583    final ServiceThread mHandlerThread;
584
585    final PackageHandler mHandler;
586
587    private final ProcessLoggingHandler mProcessLoggingHandler;
588
589    /**
590     * Messages for {@link #mHandler} that need to wait for system ready before
591     * being dispatched.
592     */
593    private ArrayList<Message> mPostSystemReadyMessages;
594
595    final int mSdkVersion = Build.VERSION.SDK_INT;
596
597    final Context mContext;
598    final boolean mFactoryTest;
599    final boolean mOnlyCore;
600    final DisplayMetrics mMetrics;
601    final int mDefParseFlags;
602    final String[] mSeparateProcesses;
603    final boolean mIsUpgrade;
604    final boolean mIsPreNUpgrade;
605    final boolean mIsPreNMR1Upgrade;
606
607    // Have we told the Activity Manager to whitelist the default container service by uid yet?
608    @GuardedBy("mPackages")
609    boolean mDefaultContainerWhitelisted = false;
610
611    @GuardedBy("mPackages")
612    private boolean mDexOptDialogShown;
613
614    /** The location for ASEC container files on internal storage. */
615    final String mAsecInternalPath;
616
617    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
618    // LOCK HELD.  Can be called with mInstallLock held.
619    @GuardedBy("mInstallLock")
620    final Installer mInstaller;
621
622    /** Directory where installed third-party apps stored */
623    final File mAppInstallDir;
624
625    /**
626     * Directory to which applications installed internally have their
627     * 32 bit native libraries copied.
628     */
629    private File mAppLib32InstallDir;
630
631    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
632    // apps.
633    final File mDrmAppPrivateInstallDir;
634
635    // ----------------------------------------------------------------
636
637    // Lock for state used when installing and doing other long running
638    // operations.  Methods that must be called with this lock held have
639    // the suffix "LI".
640    final Object mInstallLock = new Object();
641
642    // ----------------------------------------------------------------
643
644    // Keys are String (package name), values are Package.  This also serves
645    // as the lock for the global state.  Methods that must be called with
646    // this lock held have the prefix "LP".
647    @GuardedBy("mPackages")
648    final ArrayMap<String, PackageParser.Package> mPackages =
649            new ArrayMap<String, PackageParser.Package>();
650
651    final ArrayMap<String, Set<String>> mKnownCodebase =
652            new ArrayMap<String, Set<String>>();
653
654    // Keys are isolated uids and values are the uid of the application
655    // that created the isolated proccess.
656    @GuardedBy("mPackages")
657    final SparseIntArray mIsolatedOwners = new SparseIntArray();
658
659    // List of APK paths to load for each user and package. This data is never
660    // persisted by the package manager. Instead, the overlay manager will
661    // ensure the data is up-to-date in runtime.
662    @GuardedBy("mPackages")
663    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
664        new SparseArray<ArrayMap<String, ArrayList<String>>>();
665
666    /**
667     * Tracks new system packages [received in an OTA] that we expect to
668     * find updated user-installed versions. Keys are package name, values
669     * are package location.
670     */
671    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
672    /**
673     * Tracks high priority intent filters for protected actions. During boot, certain
674     * filter actions are protected and should never be allowed to have a high priority
675     * intent filter for them. However, there is one, and only one exception -- the
676     * setup wizard. It must be able to define a high priority intent filter for these
677     * actions to ensure there are no escapes from the wizard. We need to delay processing
678     * of these during boot as we need to look at all of the system packages in order
679     * to know which component is the setup wizard.
680     */
681    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
682    /**
683     * Whether or not processing protected filters should be deferred.
684     */
685    private boolean mDeferProtectedFilters = true;
686
687    /**
688     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
689     */
690    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
691    /**
692     * Whether or not system app permissions should be promoted from install to runtime.
693     */
694    boolean mPromoteSystemApps;
695
696    @GuardedBy("mPackages")
697    final Settings mSettings;
698
699    /**
700     * Set of package names that are currently "frozen", which means active
701     * surgery is being done on the code/data for that package. The platform
702     * will refuse to launch frozen packages to avoid race conditions.
703     *
704     * @see PackageFreezer
705     */
706    @GuardedBy("mPackages")
707    final ArraySet<String> mFrozenPackages = new ArraySet<>();
708
709    final ProtectedPackages mProtectedPackages;
710
711    boolean mFirstBoot;
712
713    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
714
715    // System configuration read by SystemConfig.
716    final int[] mGlobalGids;
717    final SparseArray<ArraySet<String>> mSystemPermissions;
718    @GuardedBy("mAvailableFeatures")
719    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
720
721    // If mac_permissions.xml was found for seinfo labeling.
722    boolean mFoundPolicyFile;
723
724    private final InstantAppRegistry mInstantAppRegistry;
725
726    @GuardedBy("mPackages")
727    int mChangedPackagesSequenceNumber;
728    /**
729     * List of changed [installed, removed or updated] packages.
730     * mapping from user id -> sequence number -> package name
731     */
732    @GuardedBy("mPackages")
733    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
734    /**
735     * The sequence number of the last change to a package.
736     * mapping from user id -> package name -> sequence number
737     */
738    @GuardedBy("mPackages")
739    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
740
741    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
742        @Override public boolean hasFeature(String feature) {
743            return PackageManagerService.this.hasSystemFeature(feature, 0);
744        }
745    };
746
747    public static final class SharedLibraryEntry {
748        public final String path;
749        public final String apk;
750        public final SharedLibraryInfo info;
751
752        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
753                String declaringPackageName, int declaringPackageVersionCode) {
754            path = _path;
755            apk = _apk;
756            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
757                    declaringPackageName, declaringPackageVersionCode), null);
758        }
759    }
760
761    // Currently known shared libraries.
762    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
763    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
764            new ArrayMap<>();
765
766    // All available activities, for your resolving pleasure.
767    final ActivityIntentResolver mActivities =
768            new ActivityIntentResolver();
769
770    // All available receivers, for your resolving pleasure.
771    final ActivityIntentResolver mReceivers =
772            new ActivityIntentResolver();
773
774    // All available services, for your resolving pleasure.
775    final ServiceIntentResolver mServices = new ServiceIntentResolver();
776
777    // All available providers, for your resolving pleasure.
778    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
779
780    // Mapping from provider base names (first directory in content URI codePath)
781    // to the provider information.
782    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
783            new ArrayMap<String, PackageParser.Provider>();
784
785    // Mapping from instrumentation class names to info about them.
786    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
787            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
788
789    // Mapping from permission names to info about them.
790    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
791            new ArrayMap<String, PackageParser.PermissionGroup>();
792
793    // Packages whose data we have transfered into another package, thus
794    // should no longer exist.
795    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
796
797    // Broadcast actions that are only available to the system.
798    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
799
800    /** List of packages waiting for verification. */
801    final SparseArray<PackageVerificationState> mPendingVerification
802            = new SparseArray<PackageVerificationState>();
803
804    /** Set of packages associated with each app op permission. */
805    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
806
807    final PackageInstallerService mInstallerService;
808
809    private final PackageDexOptimizer mPackageDexOptimizer;
810    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
811    // is used by other apps).
812    private final DexManager mDexManager;
813
814    private AtomicInteger mNextMoveId = new AtomicInteger();
815    private final MoveCallbacks mMoveCallbacks;
816
817    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
818
819    // Cache of users who need badging.
820    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
821
822    /** Token for keys in mPendingVerification. */
823    private int mPendingVerificationToken = 0;
824
825    volatile boolean mSystemReady;
826    volatile boolean mSafeMode;
827    volatile boolean mHasSystemUidErrors;
828    private volatile boolean mEphemeralAppsDisabled;
829
830    ApplicationInfo mAndroidApplication;
831    final ActivityInfo mResolveActivity = new ActivityInfo();
832    final ResolveInfo mResolveInfo = new ResolveInfo();
833    ComponentName mResolveComponentName;
834    PackageParser.Package mPlatformPackage;
835    ComponentName mCustomResolverComponentName;
836
837    boolean mResolverReplaced = false;
838
839    private final @Nullable ComponentName mIntentFilterVerifierComponent;
840    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
841
842    private int mIntentFilterVerificationToken = 0;
843
844    /** The service connection to the ephemeral resolver */
845    final EphemeralResolverConnection mInstantAppResolverConnection;
846    /** Component used to show resolver settings for Instant Apps */
847    final ComponentName mInstantAppResolverSettingsComponent;
848
849    /** Activity used to install instant applications */
850    ActivityInfo mInstantAppInstallerActivity;
851    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
852
853    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
854            = new SparseArray<IntentFilterVerificationState>();
855
856    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
857
858    // List of packages names to keep cached, even if they are uninstalled for all users
859    private List<String> mKeepUninstalledPackages;
860
861    private UserManagerInternal mUserManagerInternal;
862
863    private DeviceIdleController.LocalService mDeviceIdleController;
864
865    private File mCacheDir;
866
867    private ArraySet<String> mPrivappPermissionsViolations;
868
869    private Future<?> mPrepareAppDataFuture;
870
871    private static class IFVerificationParams {
872        PackageParser.Package pkg;
873        boolean replacing;
874        int userId;
875        int verifierUid;
876
877        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
878                int _userId, int _verifierUid) {
879            pkg = _pkg;
880            replacing = _replacing;
881            userId = _userId;
882            replacing = _replacing;
883            verifierUid = _verifierUid;
884        }
885    }
886
887    private interface IntentFilterVerifier<T extends IntentFilter> {
888        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
889                                               T filter, String packageName);
890        void startVerifications(int userId);
891        void receiveVerificationResponse(int verificationId);
892    }
893
894    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
895        private Context mContext;
896        private ComponentName mIntentFilterVerifierComponent;
897        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
898
899        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
900            mContext = context;
901            mIntentFilterVerifierComponent = verifierComponent;
902        }
903
904        private String getDefaultScheme() {
905            return IntentFilter.SCHEME_HTTPS;
906        }
907
908        @Override
909        public void startVerifications(int userId) {
910            // Launch verifications requests
911            int count = mCurrentIntentFilterVerifications.size();
912            for (int n=0; n<count; n++) {
913                int verificationId = mCurrentIntentFilterVerifications.get(n);
914                final IntentFilterVerificationState ivs =
915                        mIntentFilterVerificationStates.get(verificationId);
916
917                String packageName = ivs.getPackageName();
918
919                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
920                final int filterCount = filters.size();
921                ArraySet<String> domainsSet = new ArraySet<>();
922                for (int m=0; m<filterCount; m++) {
923                    PackageParser.ActivityIntentInfo filter = filters.get(m);
924                    domainsSet.addAll(filter.getHostsList());
925                }
926                synchronized (mPackages) {
927                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
928                            packageName, domainsSet) != null) {
929                        scheduleWriteSettingsLocked();
930                    }
931                }
932                sendVerificationRequest(userId, verificationId, ivs);
933            }
934            mCurrentIntentFilterVerifications.clear();
935        }
936
937        private void sendVerificationRequest(int userId, int verificationId,
938                IntentFilterVerificationState ivs) {
939
940            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
941            verificationIntent.putExtra(
942                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
943                    verificationId);
944            verificationIntent.putExtra(
945                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
946                    getDefaultScheme());
947            verificationIntent.putExtra(
948                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
949                    ivs.getHostsString());
950            verificationIntent.putExtra(
951                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
952                    ivs.getPackageName());
953            verificationIntent.setComponent(mIntentFilterVerifierComponent);
954            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
955
956            UserHandle user = new UserHandle(userId);
957            mContext.sendBroadcastAsUser(verificationIntent, user);
958            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
959                    "Sending IntentFilter verification broadcast");
960        }
961
962        public void receiveVerificationResponse(int verificationId) {
963            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
964
965            final boolean verified = ivs.isVerified();
966
967            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
968            final int count = filters.size();
969            if (DEBUG_DOMAIN_VERIFICATION) {
970                Slog.i(TAG, "Received verification response " + verificationId
971                        + " for " + count + " filters, verified=" + verified);
972            }
973            for (int n=0; n<count; n++) {
974                PackageParser.ActivityIntentInfo filter = filters.get(n);
975                filter.setVerified(verified);
976
977                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
978                        + " verified with result:" + verified + " and hosts:"
979                        + ivs.getHostsString());
980            }
981
982            mIntentFilterVerificationStates.remove(verificationId);
983
984            final String packageName = ivs.getPackageName();
985            IntentFilterVerificationInfo ivi = null;
986
987            synchronized (mPackages) {
988                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
989            }
990            if (ivi == null) {
991                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
992                        + verificationId + " packageName:" + packageName);
993                return;
994            }
995            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
996                    "Updating IntentFilterVerificationInfo for package " + packageName
997                            +" verificationId:" + verificationId);
998
999            synchronized (mPackages) {
1000                if (verified) {
1001                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1002                } else {
1003                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1004                }
1005                scheduleWriteSettingsLocked();
1006
1007                final int userId = ivs.getUserId();
1008                if (userId != UserHandle.USER_ALL) {
1009                    final int userStatus =
1010                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1011
1012                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1013                    boolean needUpdate = false;
1014
1015                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1016                    // already been set by the User thru the Disambiguation dialog
1017                    switch (userStatus) {
1018                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1019                            if (verified) {
1020                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1021                            } else {
1022                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1023                            }
1024                            needUpdate = true;
1025                            break;
1026
1027                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1028                            if (verified) {
1029                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1030                                needUpdate = true;
1031                            }
1032                            break;
1033
1034                        default:
1035                            // Nothing to do
1036                    }
1037
1038                    if (needUpdate) {
1039                        mSettings.updateIntentFilterVerificationStatusLPw(
1040                                packageName, updatedStatus, userId);
1041                        scheduleWritePackageRestrictionsLocked(userId);
1042                    }
1043                }
1044            }
1045        }
1046
1047        @Override
1048        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1049                    ActivityIntentInfo filter, String packageName) {
1050            if (!hasValidDomains(filter)) {
1051                return false;
1052            }
1053            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1054            if (ivs == null) {
1055                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1056                        packageName);
1057            }
1058            if (DEBUG_DOMAIN_VERIFICATION) {
1059                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1060            }
1061            ivs.addFilter(filter);
1062            return true;
1063        }
1064
1065        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1066                int userId, int verificationId, String packageName) {
1067            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1068                    verifierUid, userId, packageName);
1069            ivs.setPendingState();
1070            synchronized (mPackages) {
1071                mIntentFilterVerificationStates.append(verificationId, ivs);
1072                mCurrentIntentFilterVerifications.add(verificationId);
1073            }
1074            return ivs;
1075        }
1076    }
1077
1078    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1079        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1080                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1081                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1082    }
1083
1084    // Set of pending broadcasts for aggregating enable/disable of components.
1085    static class PendingPackageBroadcasts {
1086        // for each user id, a map of <package name -> components within that package>
1087        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1088
1089        public PendingPackageBroadcasts() {
1090            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1091        }
1092
1093        public ArrayList<String> get(int userId, String packageName) {
1094            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1095            return packages.get(packageName);
1096        }
1097
1098        public void put(int userId, String packageName, ArrayList<String> components) {
1099            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1100            packages.put(packageName, components);
1101        }
1102
1103        public void remove(int userId, String packageName) {
1104            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1105            if (packages != null) {
1106                packages.remove(packageName);
1107            }
1108        }
1109
1110        public void remove(int userId) {
1111            mUidMap.remove(userId);
1112        }
1113
1114        public int userIdCount() {
1115            return mUidMap.size();
1116        }
1117
1118        public int userIdAt(int n) {
1119            return mUidMap.keyAt(n);
1120        }
1121
1122        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1123            return mUidMap.get(userId);
1124        }
1125
1126        public int size() {
1127            // total number of pending broadcast entries across all userIds
1128            int num = 0;
1129            for (int i = 0; i< mUidMap.size(); i++) {
1130                num += mUidMap.valueAt(i).size();
1131            }
1132            return num;
1133        }
1134
1135        public void clear() {
1136            mUidMap.clear();
1137        }
1138
1139        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1140            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1141            if (map == null) {
1142                map = new ArrayMap<String, ArrayList<String>>();
1143                mUidMap.put(userId, map);
1144            }
1145            return map;
1146        }
1147    }
1148    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1149
1150    // Service Connection to remote media container service to copy
1151    // package uri's from external media onto secure containers
1152    // or internal storage.
1153    private IMediaContainerService mContainerService = null;
1154
1155    static final int SEND_PENDING_BROADCAST = 1;
1156    static final int MCS_BOUND = 3;
1157    static final int END_COPY = 4;
1158    static final int INIT_COPY = 5;
1159    static final int MCS_UNBIND = 6;
1160    static final int START_CLEANING_PACKAGE = 7;
1161    static final int FIND_INSTALL_LOC = 8;
1162    static final int POST_INSTALL = 9;
1163    static final int MCS_RECONNECT = 10;
1164    static final int MCS_GIVE_UP = 11;
1165    static final int UPDATED_MEDIA_STATUS = 12;
1166    static final int WRITE_SETTINGS = 13;
1167    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1168    static final int PACKAGE_VERIFIED = 15;
1169    static final int CHECK_PENDING_VERIFICATION = 16;
1170    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1171    static final int INTENT_FILTER_VERIFIED = 18;
1172    static final int WRITE_PACKAGE_LIST = 19;
1173    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1174
1175    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1176
1177    // Delay time in millisecs
1178    static final int BROADCAST_DELAY = 10 * 1000;
1179
1180    static UserManagerService sUserManager;
1181
1182    // Stores a list of users whose package restrictions file needs to be updated
1183    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1184
1185    final private DefaultContainerConnection mDefContainerConn =
1186            new DefaultContainerConnection();
1187    class DefaultContainerConnection implements ServiceConnection {
1188        public void onServiceConnected(ComponentName name, IBinder service) {
1189            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1190            final IMediaContainerService imcs = IMediaContainerService.Stub
1191                    .asInterface(Binder.allowBlocking(service));
1192            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1193        }
1194
1195        public void onServiceDisconnected(ComponentName name) {
1196            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1197        }
1198    }
1199
1200    // Recordkeeping of restore-after-install operations that are currently in flight
1201    // between the Package Manager and the Backup Manager
1202    static class PostInstallData {
1203        public InstallArgs args;
1204        public PackageInstalledInfo res;
1205
1206        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1207            args = _a;
1208            res = _r;
1209        }
1210    }
1211
1212    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1213    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1214
1215    // XML tags for backup/restore of various bits of state
1216    private static final String TAG_PREFERRED_BACKUP = "pa";
1217    private static final String TAG_DEFAULT_APPS = "da";
1218    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1219
1220    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1221    private static final String TAG_ALL_GRANTS = "rt-grants";
1222    private static final String TAG_GRANT = "grant";
1223    private static final String ATTR_PACKAGE_NAME = "pkg";
1224
1225    private static final String TAG_PERMISSION = "perm";
1226    private static final String ATTR_PERMISSION_NAME = "name";
1227    private static final String ATTR_IS_GRANTED = "g";
1228    private static final String ATTR_USER_SET = "set";
1229    private static final String ATTR_USER_FIXED = "fixed";
1230    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1231
1232    // System/policy permission grants are not backed up
1233    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1234            FLAG_PERMISSION_POLICY_FIXED
1235            | FLAG_PERMISSION_SYSTEM_FIXED
1236            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1237
1238    // And we back up these user-adjusted states
1239    private static final int USER_RUNTIME_GRANT_MASK =
1240            FLAG_PERMISSION_USER_SET
1241            | FLAG_PERMISSION_USER_FIXED
1242            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1243
1244    final @Nullable String mRequiredVerifierPackage;
1245    final @NonNull String mRequiredInstallerPackage;
1246    final @NonNull String mRequiredUninstallerPackage;
1247    final @Nullable String mSetupWizardPackage;
1248    final @Nullable String mStorageManagerPackage;
1249    final @NonNull String mServicesSystemSharedLibraryPackageName;
1250    final @NonNull String mSharedSystemSharedLibraryPackageName;
1251
1252    final boolean mPermissionReviewRequired;
1253
1254    private final PackageUsage mPackageUsage = new PackageUsage();
1255    private final CompilerStats mCompilerStats = new CompilerStats();
1256
1257    class PackageHandler extends Handler {
1258        private boolean mBound = false;
1259        final ArrayList<HandlerParams> mPendingInstalls =
1260            new ArrayList<HandlerParams>();
1261
1262        private boolean connectToService() {
1263            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1264                    " DefaultContainerService");
1265            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1266            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1267            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1268                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1269                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1270                mBound = true;
1271                return true;
1272            }
1273            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1274            return false;
1275        }
1276
1277        private void disconnectService() {
1278            mContainerService = null;
1279            mBound = false;
1280            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1281            mContext.unbindService(mDefContainerConn);
1282            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1283        }
1284
1285        PackageHandler(Looper looper) {
1286            super(looper);
1287        }
1288
1289        public void handleMessage(Message msg) {
1290            try {
1291                doHandleMessage(msg);
1292            } finally {
1293                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1294            }
1295        }
1296
1297        void doHandleMessage(Message msg) {
1298            switch (msg.what) {
1299                case INIT_COPY: {
1300                    HandlerParams params = (HandlerParams) msg.obj;
1301                    int idx = mPendingInstalls.size();
1302                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1303                    // If a bind was already initiated we dont really
1304                    // need to do anything. The pending install
1305                    // will be processed later on.
1306                    if (!mBound) {
1307                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1308                                System.identityHashCode(mHandler));
1309                        // If this is the only one pending we might
1310                        // have to bind to the service again.
1311                        if (!connectToService()) {
1312                            Slog.e(TAG, "Failed to bind to media container service");
1313                            params.serviceError();
1314                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1315                                    System.identityHashCode(mHandler));
1316                            if (params.traceMethod != null) {
1317                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1318                                        params.traceCookie);
1319                            }
1320                            return;
1321                        } else {
1322                            // Once we bind to the service, the first
1323                            // pending request will be processed.
1324                            mPendingInstalls.add(idx, params);
1325                        }
1326                    } else {
1327                        mPendingInstalls.add(idx, params);
1328                        // Already bound to the service. Just make
1329                        // sure we trigger off processing the first request.
1330                        if (idx == 0) {
1331                            mHandler.sendEmptyMessage(MCS_BOUND);
1332                        }
1333                    }
1334                    break;
1335                }
1336                case MCS_BOUND: {
1337                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1338                    if (msg.obj != null) {
1339                        mContainerService = (IMediaContainerService) msg.obj;
1340                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1341                                System.identityHashCode(mHandler));
1342                    }
1343                    if (mContainerService == null) {
1344                        if (!mBound) {
1345                            // Something seriously wrong since we are not bound and we are not
1346                            // waiting for connection. Bail out.
1347                            Slog.e(TAG, "Cannot bind to media container service");
1348                            for (HandlerParams params : mPendingInstalls) {
1349                                // Indicate service bind error
1350                                params.serviceError();
1351                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1352                                        System.identityHashCode(params));
1353                                if (params.traceMethod != null) {
1354                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1355                                            params.traceMethod, params.traceCookie);
1356                                }
1357                                return;
1358                            }
1359                            mPendingInstalls.clear();
1360                        } else {
1361                            Slog.w(TAG, "Waiting to connect to media container service");
1362                        }
1363                    } else if (mPendingInstalls.size() > 0) {
1364                        HandlerParams params = mPendingInstalls.get(0);
1365                        if (params != null) {
1366                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1367                                    System.identityHashCode(params));
1368                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1369                            if (params.startCopy()) {
1370                                // We are done...  look for more work or to
1371                                // go idle.
1372                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1373                                        "Checking for more work or unbind...");
1374                                // Delete pending install
1375                                if (mPendingInstalls.size() > 0) {
1376                                    mPendingInstalls.remove(0);
1377                                }
1378                                if (mPendingInstalls.size() == 0) {
1379                                    if (mBound) {
1380                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1381                                                "Posting delayed MCS_UNBIND");
1382                                        removeMessages(MCS_UNBIND);
1383                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1384                                        // Unbind after a little delay, to avoid
1385                                        // continual thrashing.
1386                                        sendMessageDelayed(ubmsg, 10000);
1387                                    }
1388                                } else {
1389                                    // There are more pending requests in queue.
1390                                    // Just post MCS_BOUND message to trigger processing
1391                                    // of next pending install.
1392                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1393                                            "Posting MCS_BOUND for next work");
1394                                    mHandler.sendEmptyMessage(MCS_BOUND);
1395                                }
1396                            }
1397                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1398                        }
1399                    } else {
1400                        // Should never happen ideally.
1401                        Slog.w(TAG, "Empty queue");
1402                    }
1403                    break;
1404                }
1405                case MCS_RECONNECT: {
1406                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1407                    if (mPendingInstalls.size() > 0) {
1408                        if (mBound) {
1409                            disconnectService();
1410                        }
1411                        if (!connectToService()) {
1412                            Slog.e(TAG, "Failed to bind to media container service");
1413                            for (HandlerParams params : mPendingInstalls) {
1414                                // Indicate service bind error
1415                                params.serviceError();
1416                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1417                                        System.identityHashCode(params));
1418                            }
1419                            mPendingInstalls.clear();
1420                        }
1421                    }
1422                    break;
1423                }
1424                case MCS_UNBIND: {
1425                    // If there is no actual work left, then time to unbind.
1426                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1427
1428                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1429                        if (mBound) {
1430                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1431
1432                            disconnectService();
1433                        }
1434                    } else if (mPendingInstalls.size() > 0) {
1435                        // There are more pending requests in queue.
1436                        // Just post MCS_BOUND message to trigger processing
1437                        // of next pending install.
1438                        mHandler.sendEmptyMessage(MCS_BOUND);
1439                    }
1440
1441                    break;
1442                }
1443                case MCS_GIVE_UP: {
1444                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1445                    HandlerParams params = mPendingInstalls.remove(0);
1446                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1447                            System.identityHashCode(params));
1448                    break;
1449                }
1450                case SEND_PENDING_BROADCAST: {
1451                    String packages[];
1452                    ArrayList<String> components[];
1453                    int size = 0;
1454                    int uids[];
1455                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1456                    synchronized (mPackages) {
1457                        if (mPendingBroadcasts == null) {
1458                            return;
1459                        }
1460                        size = mPendingBroadcasts.size();
1461                        if (size <= 0) {
1462                            // Nothing to be done. Just return
1463                            return;
1464                        }
1465                        packages = new String[size];
1466                        components = new ArrayList[size];
1467                        uids = new int[size];
1468                        int i = 0;  // filling out the above arrays
1469
1470                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1471                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1472                            Iterator<Map.Entry<String, ArrayList<String>>> it
1473                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1474                                            .entrySet().iterator();
1475                            while (it.hasNext() && i < size) {
1476                                Map.Entry<String, ArrayList<String>> ent = it.next();
1477                                packages[i] = ent.getKey();
1478                                components[i] = ent.getValue();
1479                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1480                                uids[i] = (ps != null)
1481                                        ? UserHandle.getUid(packageUserId, ps.appId)
1482                                        : -1;
1483                                i++;
1484                            }
1485                        }
1486                        size = i;
1487                        mPendingBroadcasts.clear();
1488                    }
1489                    // Send broadcasts
1490                    for (int i = 0; i < size; i++) {
1491                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1492                    }
1493                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1494                    break;
1495                }
1496                case START_CLEANING_PACKAGE: {
1497                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1498                    final String packageName = (String)msg.obj;
1499                    final int userId = msg.arg1;
1500                    final boolean andCode = msg.arg2 != 0;
1501                    synchronized (mPackages) {
1502                        if (userId == UserHandle.USER_ALL) {
1503                            int[] users = sUserManager.getUserIds();
1504                            for (int user : users) {
1505                                mSettings.addPackageToCleanLPw(
1506                                        new PackageCleanItem(user, packageName, andCode));
1507                            }
1508                        } else {
1509                            mSettings.addPackageToCleanLPw(
1510                                    new PackageCleanItem(userId, packageName, andCode));
1511                        }
1512                    }
1513                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1514                    startCleaningPackages();
1515                } break;
1516                case POST_INSTALL: {
1517                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1518
1519                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1520                    final boolean didRestore = (msg.arg2 != 0);
1521                    mRunningInstalls.delete(msg.arg1);
1522
1523                    if (data != null) {
1524                        InstallArgs args = data.args;
1525                        PackageInstalledInfo parentRes = data.res;
1526
1527                        final boolean grantPermissions = (args.installFlags
1528                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1529                        final boolean killApp = (args.installFlags
1530                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1531                        final String[] grantedPermissions = args.installGrantPermissions;
1532
1533                        // Handle the parent package
1534                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1535                                grantedPermissions, didRestore, args.installerPackageName,
1536                                args.observer);
1537
1538                        // Handle the child packages
1539                        final int childCount = (parentRes.addedChildPackages != null)
1540                                ? parentRes.addedChildPackages.size() : 0;
1541                        for (int i = 0; i < childCount; i++) {
1542                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1543                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1544                                    grantedPermissions, false, args.installerPackageName,
1545                                    args.observer);
1546                        }
1547
1548                        // Log tracing if needed
1549                        if (args.traceMethod != null) {
1550                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1551                                    args.traceCookie);
1552                        }
1553                    } else {
1554                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1555                    }
1556
1557                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1558                } break;
1559                case UPDATED_MEDIA_STATUS: {
1560                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1561                    boolean reportStatus = msg.arg1 == 1;
1562                    boolean doGc = msg.arg2 == 1;
1563                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1564                    if (doGc) {
1565                        // Force a gc to clear up stale containers.
1566                        Runtime.getRuntime().gc();
1567                    }
1568                    if (msg.obj != null) {
1569                        @SuppressWarnings("unchecked")
1570                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1571                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1572                        // Unload containers
1573                        unloadAllContainers(args);
1574                    }
1575                    if (reportStatus) {
1576                        try {
1577                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1578                                    "Invoking StorageManagerService call back");
1579                            PackageHelper.getStorageManager().finishMediaUpdate();
1580                        } catch (RemoteException e) {
1581                            Log.e(TAG, "StorageManagerService not running?");
1582                        }
1583                    }
1584                } break;
1585                case WRITE_SETTINGS: {
1586                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1587                    synchronized (mPackages) {
1588                        removeMessages(WRITE_SETTINGS);
1589                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1590                        mSettings.writeLPr();
1591                        mDirtyUsers.clear();
1592                    }
1593                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1594                } break;
1595                case WRITE_PACKAGE_RESTRICTIONS: {
1596                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1597                    synchronized (mPackages) {
1598                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1599                        for (int userId : mDirtyUsers) {
1600                            mSettings.writePackageRestrictionsLPr(userId);
1601                        }
1602                        mDirtyUsers.clear();
1603                    }
1604                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1605                } break;
1606                case WRITE_PACKAGE_LIST: {
1607                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1608                    synchronized (mPackages) {
1609                        removeMessages(WRITE_PACKAGE_LIST);
1610                        mSettings.writePackageListLPr(msg.arg1);
1611                    }
1612                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1613                } break;
1614                case CHECK_PENDING_VERIFICATION: {
1615                    final int verificationId = msg.arg1;
1616                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1617
1618                    if ((state != null) && !state.timeoutExtended()) {
1619                        final InstallArgs args = state.getInstallArgs();
1620                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1621
1622                        Slog.i(TAG, "Verification timed out for " + originUri);
1623                        mPendingVerification.remove(verificationId);
1624
1625                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1626
1627                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1628                            Slog.i(TAG, "Continuing with installation of " + originUri);
1629                            state.setVerifierResponse(Binder.getCallingUid(),
1630                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1631                            broadcastPackageVerified(verificationId, originUri,
1632                                    PackageManager.VERIFICATION_ALLOW,
1633                                    state.getInstallArgs().getUser());
1634                            try {
1635                                ret = args.copyApk(mContainerService, true);
1636                            } catch (RemoteException e) {
1637                                Slog.e(TAG, "Could not contact the ContainerService");
1638                            }
1639                        } else {
1640                            broadcastPackageVerified(verificationId, originUri,
1641                                    PackageManager.VERIFICATION_REJECT,
1642                                    state.getInstallArgs().getUser());
1643                        }
1644
1645                        Trace.asyncTraceEnd(
1646                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1647
1648                        processPendingInstall(args, ret);
1649                        mHandler.sendEmptyMessage(MCS_UNBIND);
1650                    }
1651                    break;
1652                }
1653                case PACKAGE_VERIFIED: {
1654                    final int verificationId = msg.arg1;
1655
1656                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1657                    if (state == null) {
1658                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1659                        break;
1660                    }
1661
1662                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1663
1664                    state.setVerifierResponse(response.callerUid, response.code);
1665
1666                    if (state.isVerificationComplete()) {
1667                        mPendingVerification.remove(verificationId);
1668
1669                        final InstallArgs args = state.getInstallArgs();
1670                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1671
1672                        int ret;
1673                        if (state.isInstallAllowed()) {
1674                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1675                            broadcastPackageVerified(verificationId, originUri,
1676                                    response.code, state.getInstallArgs().getUser());
1677                            try {
1678                                ret = args.copyApk(mContainerService, true);
1679                            } catch (RemoteException e) {
1680                                Slog.e(TAG, "Could not contact the ContainerService");
1681                            }
1682                        } else {
1683                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1684                        }
1685
1686                        Trace.asyncTraceEnd(
1687                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1688
1689                        processPendingInstall(args, ret);
1690                        mHandler.sendEmptyMessage(MCS_UNBIND);
1691                    }
1692
1693                    break;
1694                }
1695                case START_INTENT_FILTER_VERIFICATIONS: {
1696                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1697                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1698                            params.replacing, params.pkg);
1699                    break;
1700                }
1701                case INTENT_FILTER_VERIFIED: {
1702                    final int verificationId = msg.arg1;
1703
1704                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1705                            verificationId);
1706                    if (state == null) {
1707                        Slog.w(TAG, "Invalid IntentFilter verification token "
1708                                + verificationId + " received");
1709                        break;
1710                    }
1711
1712                    final int userId = state.getUserId();
1713
1714                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1715                            "Processing IntentFilter verification with token:"
1716                            + verificationId + " and userId:" + userId);
1717
1718                    final IntentFilterVerificationResponse response =
1719                            (IntentFilterVerificationResponse) msg.obj;
1720
1721                    state.setVerifierResponse(response.callerUid, response.code);
1722
1723                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1724                            "IntentFilter verification with token:" + verificationId
1725                            + " and userId:" + userId
1726                            + " is settings verifier response with response code:"
1727                            + response.code);
1728
1729                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1730                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1731                                + response.getFailedDomainsString());
1732                    }
1733
1734                    if (state.isVerificationComplete()) {
1735                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1736                    } else {
1737                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1738                                "IntentFilter verification with token:" + verificationId
1739                                + " was not said to be complete");
1740                    }
1741
1742                    break;
1743                }
1744                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1745                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1746                            mInstantAppResolverConnection,
1747                            (InstantAppRequest) msg.obj,
1748                            mInstantAppInstallerActivity,
1749                            mHandler);
1750                }
1751            }
1752        }
1753    }
1754
1755    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1756            boolean killApp, String[] grantedPermissions,
1757            boolean launchedForRestore, String installerPackage,
1758            IPackageInstallObserver2 installObserver) {
1759        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1760            // Send the removed broadcasts
1761            if (res.removedInfo != null) {
1762                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1763            }
1764
1765            // Now that we successfully installed the package, grant runtime
1766            // permissions if requested before broadcasting the install. Also
1767            // for legacy apps in permission review mode we clear the permission
1768            // review flag which is used to emulate runtime permissions for
1769            // legacy apps.
1770            if (grantPermissions) {
1771                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1772            }
1773
1774            final boolean update = res.removedInfo != null
1775                    && res.removedInfo.removedPackage != null;
1776
1777            // If this is the first time we have child packages for a disabled privileged
1778            // app that had no children, we grant requested runtime permissions to the new
1779            // children if the parent on the system image had them already granted.
1780            if (res.pkg.parentPackage != null) {
1781                synchronized (mPackages) {
1782                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1783                }
1784            }
1785
1786            synchronized (mPackages) {
1787                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1788            }
1789
1790            final String packageName = res.pkg.applicationInfo.packageName;
1791
1792            // Determine the set of users who are adding this package for
1793            // the first time vs. those who are seeing an update.
1794            int[] firstUsers = EMPTY_INT_ARRAY;
1795            int[] updateUsers = EMPTY_INT_ARRAY;
1796            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1797            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1798            for (int newUser : res.newUsers) {
1799                if (ps.getInstantApp(newUser)) {
1800                    continue;
1801                }
1802                if (allNewUsers) {
1803                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1804                    continue;
1805                }
1806                boolean isNew = true;
1807                for (int origUser : res.origUsers) {
1808                    if (origUser == newUser) {
1809                        isNew = false;
1810                        break;
1811                    }
1812                }
1813                if (isNew) {
1814                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1815                } else {
1816                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1817                }
1818            }
1819
1820            // Send installed broadcasts if the package is not a static shared lib.
1821            if (res.pkg.staticSharedLibName == null) {
1822                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1823
1824                // Send added for users that see the package for the first time
1825                // sendPackageAddedForNewUsers also deals with system apps
1826                int appId = UserHandle.getAppId(res.uid);
1827                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1828                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1829
1830                // Send added for users that don't see the package for the first time
1831                Bundle extras = new Bundle(1);
1832                extras.putInt(Intent.EXTRA_UID, res.uid);
1833                if (update) {
1834                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1835                } else {
1836                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_ADDED, packageName,
1837                            extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
1838                            null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1839                }
1840                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1841                        extras, 0 /*flags*/, null /*targetPackage*/,
1842                        null /*finishedReceiver*/, updateUsers);
1843
1844                // Send replaced for users that don't see the package for the first time
1845                if (update) {
1846                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1847                            packageName, extras, 0 /*flags*/,
1848                            null /*targetPackage*/, null /*finishedReceiver*/,
1849                            updateUsers);
1850                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1851                            null /*package*/, null /*extras*/, 0 /*flags*/,
1852                            packageName /*targetPackage*/,
1853                            null /*finishedReceiver*/, updateUsers);
1854                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1855                    // First-install and we did a restore, so we're responsible for the
1856                    // first-launch broadcast.
1857                    if (DEBUG_BACKUP) {
1858                        Slog.i(TAG, "Post-restore of " + packageName
1859                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1860                    }
1861                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1862                }
1863
1864                // Send broadcast package appeared if forward locked/external for all users
1865                // treat asec-hosted packages like removable media on upgrade
1866                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1867                    if (DEBUG_INSTALL) {
1868                        Slog.i(TAG, "upgrading pkg " + res.pkg
1869                                + " is ASEC-hosted -> AVAILABLE");
1870                    }
1871                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1872                    ArrayList<String> pkgList = new ArrayList<>(1);
1873                    pkgList.add(packageName);
1874                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1875                }
1876            }
1877
1878            // Work that needs to happen on first install within each user
1879            if (firstUsers != null && firstUsers.length > 0) {
1880                synchronized (mPackages) {
1881                    for (int userId : firstUsers) {
1882                        // If this app is a browser and it's newly-installed for some
1883                        // users, clear any default-browser state in those users. The
1884                        // app's nature doesn't depend on the user, so we can just check
1885                        // its browser nature in any user and generalize.
1886                        if (packageIsBrowser(packageName, userId)) {
1887                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1888                        }
1889
1890                        // We may also need to apply pending (restored) runtime
1891                        // permission grants within these users.
1892                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1893                    }
1894                }
1895            }
1896
1897            // Log current value of "unknown sources" setting
1898            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1899                    getUnknownSourcesSettings());
1900
1901            // Force a gc to clear up things
1902            Runtime.getRuntime().gc();
1903
1904            // Remove the replaced package's older resources safely now
1905            // We delete after a gc for applications  on sdcard.
1906            if (res.removedInfo != null && res.removedInfo.args != null) {
1907                synchronized (mInstallLock) {
1908                    res.removedInfo.args.doPostDeleteLI(true);
1909                }
1910            }
1911
1912            // Notify DexManager that the package was installed for new users.
1913            // The updated users should already be indexed and the package code paths
1914            // should not change.
1915            // Don't notify the manager for ephemeral apps as they are not expected to
1916            // survive long enough to benefit of background optimizations.
1917            for (int userId : firstUsers) {
1918                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1919                // There's a race currently where some install events may interleave with an uninstall.
1920                // This can lead to package info being null (b/36642664).
1921                if (info != null) {
1922                    mDexManager.notifyPackageInstalled(info, userId);
1923                }
1924            }
1925        }
1926
1927        // If someone is watching installs - notify them
1928        if (installObserver != null) {
1929            try {
1930                Bundle extras = extrasForInstallResult(res);
1931                installObserver.onPackageInstalled(res.name, res.returnCode,
1932                        res.returnMsg, extras);
1933            } catch (RemoteException e) {
1934                Slog.i(TAG, "Observer no longer exists.");
1935            }
1936        }
1937    }
1938
1939    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1940            PackageParser.Package pkg) {
1941        if (pkg.parentPackage == null) {
1942            return;
1943        }
1944        if (pkg.requestedPermissions == null) {
1945            return;
1946        }
1947        final PackageSetting disabledSysParentPs = mSettings
1948                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1949        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1950                || !disabledSysParentPs.isPrivileged()
1951                || (disabledSysParentPs.childPackageNames != null
1952                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1953            return;
1954        }
1955        final int[] allUserIds = sUserManager.getUserIds();
1956        final int permCount = pkg.requestedPermissions.size();
1957        for (int i = 0; i < permCount; i++) {
1958            String permission = pkg.requestedPermissions.get(i);
1959            BasePermission bp = mSettings.mPermissions.get(permission);
1960            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1961                continue;
1962            }
1963            for (int userId : allUserIds) {
1964                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1965                        permission, userId)) {
1966                    grantRuntimePermission(pkg.packageName, permission, userId);
1967                }
1968            }
1969        }
1970    }
1971
1972    private StorageEventListener mStorageListener = new StorageEventListener() {
1973        @Override
1974        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1975            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1976                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1977                    final String volumeUuid = vol.getFsUuid();
1978
1979                    // Clean up any users or apps that were removed or recreated
1980                    // while this volume was missing
1981                    sUserManager.reconcileUsers(volumeUuid);
1982                    reconcileApps(volumeUuid);
1983
1984                    // Clean up any install sessions that expired or were
1985                    // cancelled while this volume was missing
1986                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1987
1988                    loadPrivatePackages(vol);
1989
1990                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1991                    unloadPrivatePackages(vol);
1992                }
1993            }
1994
1995            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1996                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1997                    updateExternalMediaStatus(true, false);
1998                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1999                    updateExternalMediaStatus(false, false);
2000                }
2001            }
2002        }
2003
2004        @Override
2005        public void onVolumeForgotten(String fsUuid) {
2006            if (TextUtils.isEmpty(fsUuid)) {
2007                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2008                return;
2009            }
2010
2011            // Remove any apps installed on the forgotten volume
2012            synchronized (mPackages) {
2013                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2014                for (PackageSetting ps : packages) {
2015                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2016                    deletePackageVersioned(new VersionedPackage(ps.name,
2017                            PackageManager.VERSION_CODE_HIGHEST),
2018                            new LegacyPackageDeleteObserver(null).getBinder(),
2019                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2020                    // Try very hard to release any references to this package
2021                    // so we don't risk the system server being killed due to
2022                    // open FDs
2023                    AttributeCache.instance().removePackage(ps.name);
2024                }
2025
2026                mSettings.onVolumeForgotten(fsUuid);
2027                mSettings.writeLPr();
2028            }
2029        }
2030    };
2031
2032    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2033            String[] grantedPermissions) {
2034        for (int userId : userIds) {
2035            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2036        }
2037    }
2038
2039    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2040            String[] grantedPermissions) {
2041        SettingBase sb = (SettingBase) pkg.mExtras;
2042        if (sb == null) {
2043            return;
2044        }
2045
2046        PermissionsState permissionsState = sb.getPermissionsState();
2047
2048        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2049                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2050
2051        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2052                >= Build.VERSION_CODES.M;
2053
2054        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2055
2056        for (String permission : pkg.requestedPermissions) {
2057            final BasePermission bp;
2058            synchronized (mPackages) {
2059                bp = mSettings.mPermissions.get(permission);
2060            }
2061            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2062                    && (!instantApp || bp.isInstant())
2063                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2064                    && (grantedPermissions == null
2065                           || ArrayUtils.contains(grantedPermissions, permission))) {
2066                final int flags = permissionsState.getPermissionFlags(permission, userId);
2067                if (supportsRuntimePermissions) {
2068                    // Installer cannot change immutable permissions.
2069                    if ((flags & immutableFlags) == 0) {
2070                        grantRuntimePermission(pkg.packageName, permission, userId);
2071                    }
2072                } else if (mPermissionReviewRequired) {
2073                    // In permission review mode we clear the review flag when we
2074                    // are asked to install the app with all permissions granted.
2075                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2076                        updatePermissionFlags(permission, pkg.packageName,
2077                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2078                    }
2079                }
2080            }
2081        }
2082    }
2083
2084    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2085        Bundle extras = null;
2086        switch (res.returnCode) {
2087            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2088                extras = new Bundle();
2089                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2090                        res.origPermission);
2091                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2092                        res.origPackage);
2093                break;
2094            }
2095            case PackageManager.INSTALL_SUCCEEDED: {
2096                extras = new Bundle();
2097                extras.putBoolean(Intent.EXTRA_REPLACING,
2098                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2099                break;
2100            }
2101        }
2102        return extras;
2103    }
2104
2105    void scheduleWriteSettingsLocked() {
2106        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2107            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2108        }
2109    }
2110
2111    void scheduleWritePackageListLocked(int userId) {
2112        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2113            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2114            msg.arg1 = userId;
2115            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2116        }
2117    }
2118
2119    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2120        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2121        scheduleWritePackageRestrictionsLocked(userId);
2122    }
2123
2124    void scheduleWritePackageRestrictionsLocked(int userId) {
2125        final int[] userIds = (userId == UserHandle.USER_ALL)
2126                ? sUserManager.getUserIds() : new int[]{userId};
2127        for (int nextUserId : userIds) {
2128            if (!sUserManager.exists(nextUserId)) return;
2129            mDirtyUsers.add(nextUserId);
2130            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2131                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2132            }
2133        }
2134    }
2135
2136    public static PackageManagerService main(Context context, Installer installer,
2137            boolean factoryTest, boolean onlyCore) {
2138        // Self-check for initial settings.
2139        PackageManagerServiceCompilerMapping.checkProperties();
2140
2141        PackageManagerService m = new PackageManagerService(context, installer,
2142                factoryTest, onlyCore);
2143        m.enableSystemUserPackages();
2144        ServiceManager.addService("package", m);
2145        return m;
2146    }
2147
2148    private void enableSystemUserPackages() {
2149        if (!UserManager.isSplitSystemUser()) {
2150            return;
2151        }
2152        // For system user, enable apps based on the following conditions:
2153        // - app is whitelisted or belong to one of these groups:
2154        //   -- system app which has no launcher icons
2155        //   -- system app which has INTERACT_ACROSS_USERS permission
2156        //   -- system IME app
2157        // - app is not in the blacklist
2158        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2159        Set<String> enableApps = new ArraySet<>();
2160        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2161                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2162                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2163        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2164        enableApps.addAll(wlApps);
2165        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2166                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2167        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2168        enableApps.removeAll(blApps);
2169        Log.i(TAG, "Applications installed for system user: " + enableApps);
2170        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2171                UserHandle.SYSTEM);
2172        final int allAppsSize = allAps.size();
2173        synchronized (mPackages) {
2174            for (int i = 0; i < allAppsSize; i++) {
2175                String pName = allAps.get(i);
2176                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2177                // Should not happen, but we shouldn't be failing if it does
2178                if (pkgSetting == null) {
2179                    continue;
2180                }
2181                boolean install = enableApps.contains(pName);
2182                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2183                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2184                            + " for system user");
2185                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2186                }
2187            }
2188            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2189        }
2190    }
2191
2192    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2193        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2194                Context.DISPLAY_SERVICE);
2195        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2196    }
2197
2198    /**
2199     * Requests that files preopted on a secondary system partition be copied to the data partition
2200     * if possible.  Note that the actual copying of the files is accomplished by init for security
2201     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2202     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2203     */
2204    private static void requestCopyPreoptedFiles() {
2205        final int WAIT_TIME_MS = 100;
2206        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2207        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2208            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2209            // We will wait for up to 100 seconds.
2210            final long timeStart = SystemClock.uptimeMillis();
2211            final long timeEnd = timeStart + 100 * 1000;
2212            long timeNow = timeStart;
2213            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2214                try {
2215                    Thread.sleep(WAIT_TIME_MS);
2216                } catch (InterruptedException e) {
2217                    // Do nothing
2218                }
2219                timeNow = SystemClock.uptimeMillis();
2220                if (timeNow > timeEnd) {
2221                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2222                    Slog.wtf(TAG, "cppreopt did not finish!");
2223                    break;
2224                }
2225            }
2226
2227            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2228        }
2229    }
2230
2231    public PackageManagerService(Context context, Installer installer,
2232            boolean factoryTest, boolean onlyCore) {
2233        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2234        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2235        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2236                SystemClock.uptimeMillis());
2237
2238        if (mSdkVersion <= 0) {
2239            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2240        }
2241
2242        mContext = context;
2243
2244        mPermissionReviewRequired = context.getResources().getBoolean(
2245                R.bool.config_permissionReviewRequired);
2246
2247        mFactoryTest = factoryTest;
2248        mOnlyCore = onlyCore;
2249        mMetrics = new DisplayMetrics();
2250        mSettings = new Settings(mPackages);
2251        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2252                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2253        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2254                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2255        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2256                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2257        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2258                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2259        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2260                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2261        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2262                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2263
2264        String separateProcesses = SystemProperties.get("debug.separate_processes");
2265        if (separateProcesses != null && separateProcesses.length() > 0) {
2266            if ("*".equals(separateProcesses)) {
2267                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2268                mSeparateProcesses = null;
2269                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2270            } else {
2271                mDefParseFlags = 0;
2272                mSeparateProcesses = separateProcesses.split(",");
2273                Slog.w(TAG, "Running with debug.separate_processes: "
2274                        + separateProcesses);
2275            }
2276        } else {
2277            mDefParseFlags = 0;
2278            mSeparateProcesses = null;
2279        }
2280
2281        mInstaller = installer;
2282        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2283                "*dexopt*");
2284        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2285        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2286
2287        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2288                FgThread.get().getLooper());
2289
2290        getDefaultDisplayMetrics(context, mMetrics);
2291
2292        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2293        SystemConfig systemConfig = SystemConfig.getInstance();
2294        mGlobalGids = systemConfig.getGlobalGids();
2295        mSystemPermissions = systemConfig.getSystemPermissions();
2296        mAvailableFeatures = systemConfig.getAvailableFeatures();
2297        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2298
2299        mProtectedPackages = new ProtectedPackages(mContext);
2300
2301        synchronized (mInstallLock) {
2302        // writer
2303        synchronized (mPackages) {
2304            mHandlerThread = new ServiceThread(TAG,
2305                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2306            mHandlerThread.start();
2307            mHandler = new PackageHandler(mHandlerThread.getLooper());
2308            mProcessLoggingHandler = new ProcessLoggingHandler();
2309            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2310
2311            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2312            mInstantAppRegistry = new InstantAppRegistry(this);
2313
2314            File dataDir = Environment.getDataDirectory();
2315            mAppInstallDir = new File(dataDir, "app");
2316            mAppLib32InstallDir = new File(dataDir, "app-lib");
2317            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2318            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2319            sUserManager = new UserManagerService(context, this,
2320                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2321
2322            // Propagate permission configuration in to package manager.
2323            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2324                    = systemConfig.getPermissions();
2325            for (int i=0; i<permConfig.size(); i++) {
2326                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2327                BasePermission bp = mSettings.mPermissions.get(perm.name);
2328                if (bp == null) {
2329                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2330                    mSettings.mPermissions.put(perm.name, bp);
2331                }
2332                if (perm.gids != null) {
2333                    bp.setGids(perm.gids, perm.perUser);
2334                }
2335            }
2336
2337            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2338            final int builtInLibCount = libConfig.size();
2339            for (int i = 0; i < builtInLibCount; i++) {
2340                String name = libConfig.keyAt(i);
2341                String path = libConfig.valueAt(i);
2342                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2343                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2344            }
2345
2346            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2347
2348            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2349            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2350            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2351
2352            // Clean up orphaned packages for which the code path doesn't exist
2353            // and they are an update to a system app - caused by bug/32321269
2354            final int packageSettingCount = mSettings.mPackages.size();
2355            for (int i = packageSettingCount - 1; i >= 0; i--) {
2356                PackageSetting ps = mSettings.mPackages.valueAt(i);
2357                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2358                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2359                    mSettings.mPackages.removeAt(i);
2360                    mSettings.enableSystemPackageLPw(ps.name);
2361                }
2362            }
2363
2364            if (mFirstBoot) {
2365                requestCopyPreoptedFiles();
2366            }
2367
2368            String customResolverActivity = Resources.getSystem().getString(
2369                    R.string.config_customResolverActivity);
2370            if (TextUtils.isEmpty(customResolverActivity)) {
2371                customResolverActivity = null;
2372            } else {
2373                mCustomResolverComponentName = ComponentName.unflattenFromString(
2374                        customResolverActivity);
2375            }
2376
2377            long startTime = SystemClock.uptimeMillis();
2378
2379            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2380                    startTime);
2381
2382            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2383            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2384
2385            if (bootClassPath == null) {
2386                Slog.w(TAG, "No BOOTCLASSPATH found!");
2387            }
2388
2389            if (systemServerClassPath == null) {
2390                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2391            }
2392
2393            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2394
2395            final VersionInfo ver = mSettings.getInternalVersion();
2396            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2397            if (mIsUpgrade) {
2398                logCriticalInfo(Log.INFO,
2399                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2400            }
2401
2402            // when upgrading from pre-M, promote system app permissions from install to runtime
2403            mPromoteSystemApps =
2404                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2405
2406            // When upgrading from pre-N, we need to handle package extraction like first boot,
2407            // as there is no profiling data available.
2408            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2409
2410            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2411
2412            // save off the names of pre-existing system packages prior to scanning; we don't
2413            // want to automatically grant runtime permissions for new system apps
2414            if (mPromoteSystemApps) {
2415                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2416                while (pkgSettingIter.hasNext()) {
2417                    PackageSetting ps = pkgSettingIter.next();
2418                    if (isSystemApp(ps)) {
2419                        mExistingSystemPackages.add(ps.name);
2420                    }
2421                }
2422            }
2423
2424            mCacheDir = preparePackageParserCache(mIsUpgrade);
2425
2426            // Set flag to monitor and not change apk file paths when
2427            // scanning install directories.
2428            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2429
2430            if (mIsUpgrade || mFirstBoot) {
2431                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2432            }
2433
2434            // Collect vendor overlay packages. (Do this before scanning any apps.)
2435            // For security and version matching reason, only consider
2436            // overlay packages if they reside in the right directory.
2437            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2438                    | PackageParser.PARSE_IS_SYSTEM
2439                    | PackageParser.PARSE_IS_SYSTEM_DIR
2440                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2441
2442            // Find base frameworks (resource packages without code).
2443            scanDirTracedLI(frameworkDir, mDefParseFlags
2444                    | PackageParser.PARSE_IS_SYSTEM
2445                    | PackageParser.PARSE_IS_SYSTEM_DIR
2446                    | PackageParser.PARSE_IS_PRIVILEGED,
2447                    scanFlags | SCAN_NO_DEX, 0);
2448
2449            // Collected privileged system packages.
2450            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2451            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2452                    | PackageParser.PARSE_IS_SYSTEM
2453                    | PackageParser.PARSE_IS_SYSTEM_DIR
2454                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2455
2456            // Collect ordinary system packages.
2457            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2458            scanDirTracedLI(systemAppDir, mDefParseFlags
2459                    | PackageParser.PARSE_IS_SYSTEM
2460                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2461
2462            // Collect all vendor packages.
2463            File vendorAppDir = new File("/vendor/app");
2464            try {
2465                vendorAppDir = vendorAppDir.getCanonicalFile();
2466            } catch (IOException e) {
2467                // failed to look up canonical path, continue with original one
2468            }
2469            scanDirTracedLI(vendorAppDir, mDefParseFlags
2470                    | PackageParser.PARSE_IS_SYSTEM
2471                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2472
2473            // Collect all OEM packages.
2474            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2475            scanDirTracedLI(oemAppDir, mDefParseFlags
2476                    | PackageParser.PARSE_IS_SYSTEM
2477                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2478
2479            // Prune any system packages that no longer exist.
2480            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2481            if (!mOnlyCore) {
2482                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2483                while (psit.hasNext()) {
2484                    PackageSetting ps = psit.next();
2485
2486                    /*
2487                     * If this is not a system app, it can't be a
2488                     * disable system app.
2489                     */
2490                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2491                        continue;
2492                    }
2493
2494                    /*
2495                     * If the package is scanned, it's not erased.
2496                     */
2497                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2498                    if (scannedPkg != null) {
2499                        /*
2500                         * If the system app is both scanned and in the
2501                         * disabled packages list, then it must have been
2502                         * added via OTA. Remove it from the currently
2503                         * scanned package so the previously user-installed
2504                         * application can be scanned.
2505                         */
2506                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2507                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2508                                    + ps.name + "; removing system app.  Last known codePath="
2509                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2510                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2511                                    + scannedPkg.mVersionCode);
2512                            removePackageLI(scannedPkg, true);
2513                            mExpectingBetter.put(ps.name, ps.codePath);
2514                        }
2515
2516                        continue;
2517                    }
2518
2519                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2520                        psit.remove();
2521                        logCriticalInfo(Log.WARN, "System package " + ps.name
2522                                + " no longer exists; it's data will be wiped");
2523                        // Actual deletion of code and data will be handled by later
2524                        // reconciliation step
2525                    } else {
2526                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2527                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2528                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2529                        }
2530                    }
2531                }
2532            }
2533
2534            //look for any incomplete package installations
2535            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2536            for (int i = 0; i < deletePkgsList.size(); i++) {
2537                // Actual deletion of code and data will be handled by later
2538                // reconciliation step
2539                final String packageName = deletePkgsList.get(i).name;
2540                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2541                synchronized (mPackages) {
2542                    mSettings.removePackageLPw(packageName);
2543                }
2544            }
2545
2546            //delete tmp files
2547            deleteTempPackageFiles();
2548
2549            // Remove any shared userIDs that have no associated packages
2550            mSettings.pruneSharedUsersLPw();
2551
2552            if (!mOnlyCore) {
2553                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2554                        SystemClock.uptimeMillis());
2555                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2556
2557                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2558                        | PackageParser.PARSE_FORWARD_LOCK,
2559                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2560
2561                /**
2562                 * Remove disable package settings for any updated system
2563                 * apps that were removed via an OTA. If they're not a
2564                 * previously-updated app, remove them completely.
2565                 * Otherwise, just revoke their system-level permissions.
2566                 */
2567                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2568                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2569                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2570
2571                    String msg;
2572                    if (deletedPkg == null) {
2573                        msg = "Updated system package " + deletedAppName
2574                                + " no longer exists; it's data will be wiped";
2575                        // Actual deletion of code and data will be handled by later
2576                        // reconciliation step
2577                    } else {
2578                        msg = "Updated system app + " + deletedAppName
2579                                + " no longer present; removing system privileges for "
2580                                + deletedAppName;
2581
2582                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2583
2584                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2585                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2586                    }
2587                    logCriticalInfo(Log.WARN, msg);
2588                }
2589
2590                /**
2591                 * Make sure all system apps that we expected to appear on
2592                 * the userdata partition actually showed up. If they never
2593                 * appeared, crawl back and revive the system version.
2594                 */
2595                for (int i = 0; i < mExpectingBetter.size(); i++) {
2596                    final String packageName = mExpectingBetter.keyAt(i);
2597                    if (!mPackages.containsKey(packageName)) {
2598                        final File scanFile = mExpectingBetter.valueAt(i);
2599
2600                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2601                                + " but never showed up; reverting to system");
2602
2603                        int reparseFlags = mDefParseFlags;
2604                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2605                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2606                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2607                                    | PackageParser.PARSE_IS_PRIVILEGED;
2608                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2609                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2610                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2611                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2612                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2613                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2614                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2615                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2616                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2617                        } else {
2618                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2619                            continue;
2620                        }
2621
2622                        mSettings.enableSystemPackageLPw(packageName);
2623
2624                        try {
2625                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2626                        } catch (PackageManagerException e) {
2627                            Slog.e(TAG, "Failed to parse original system package: "
2628                                    + e.getMessage());
2629                        }
2630                    }
2631                }
2632            }
2633            mExpectingBetter.clear();
2634
2635            // Resolve the storage manager.
2636            mStorageManagerPackage = getStorageManagerPackageName();
2637
2638            // Resolve protected action filters. Only the setup wizard is allowed to
2639            // have a high priority filter for these actions.
2640            mSetupWizardPackage = getSetupWizardPackageName();
2641            if (mProtectedFilters.size() > 0) {
2642                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2643                    Slog.i(TAG, "No setup wizard;"
2644                        + " All protected intents capped to priority 0");
2645                }
2646                for (ActivityIntentInfo filter : mProtectedFilters) {
2647                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2648                        if (DEBUG_FILTERS) {
2649                            Slog.i(TAG, "Found setup wizard;"
2650                                + " allow priority " + filter.getPriority() + ";"
2651                                + " package: " + filter.activity.info.packageName
2652                                + " activity: " + filter.activity.className
2653                                + " priority: " + filter.getPriority());
2654                        }
2655                        // skip setup wizard; allow it to keep the high priority filter
2656                        continue;
2657                    }
2658                    Slog.w(TAG, "Protected action; cap priority to 0;"
2659                            + " package: " + filter.activity.info.packageName
2660                            + " activity: " + filter.activity.className
2661                            + " origPrio: " + filter.getPriority());
2662                    filter.setPriority(0);
2663                }
2664            }
2665            mDeferProtectedFilters = false;
2666            mProtectedFilters.clear();
2667
2668            // Now that we know all of the shared libraries, update all clients to have
2669            // the correct library paths.
2670            updateAllSharedLibrariesLPw(null);
2671
2672            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2673                // NOTE: We ignore potential failures here during a system scan (like
2674                // the rest of the commands above) because there's precious little we
2675                // can do about it. A settings error is reported, though.
2676                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2677            }
2678
2679            // Now that we know all the packages we are keeping,
2680            // read and update their last usage times.
2681            mPackageUsage.read(mPackages);
2682            mCompilerStats.read();
2683
2684            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2685                    SystemClock.uptimeMillis());
2686            Slog.i(TAG, "Time to scan packages: "
2687                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2688                    + " seconds");
2689
2690            // If the platform SDK has changed since the last time we booted,
2691            // we need to re-grant app permission to catch any new ones that
2692            // appear.  This is really a hack, and means that apps can in some
2693            // cases get permissions that the user didn't initially explicitly
2694            // allow...  it would be nice to have some better way to handle
2695            // this situation.
2696            int updateFlags = UPDATE_PERMISSIONS_ALL;
2697            if (ver.sdkVersion != mSdkVersion) {
2698                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2699                        + mSdkVersion + "; regranting permissions for internal storage");
2700                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2701            }
2702            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2703            ver.sdkVersion = mSdkVersion;
2704
2705            // If this is the first boot or an update from pre-M, and it is a normal
2706            // boot, then we need to initialize the default preferred apps across
2707            // all defined users.
2708            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2709                for (UserInfo user : sUserManager.getUsers(true)) {
2710                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2711                    applyFactoryDefaultBrowserLPw(user.id);
2712                    primeDomainVerificationsLPw(user.id);
2713                }
2714            }
2715
2716            // Prepare storage for system user really early during boot,
2717            // since core system apps like SettingsProvider and SystemUI
2718            // can't wait for user to start
2719            final int storageFlags;
2720            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2721                storageFlags = StorageManager.FLAG_STORAGE_DE;
2722            } else {
2723                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2724            }
2725            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2726                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2727                    true /* onlyCoreApps */);
2728            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2729                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "fixup");
2730                try {
2731                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2732                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2733                } catch (InstallerException e) {
2734                    Slog.w(TAG, "Trouble fixing GIDs", e);
2735                }
2736                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2737
2738                if (deferPackages == null || deferPackages.isEmpty()) {
2739                    return;
2740                }
2741                int count = 0;
2742                for (String pkgName : deferPackages) {
2743                    PackageParser.Package pkg = null;
2744                    synchronized (mPackages) {
2745                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2746                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2747                            pkg = ps.pkg;
2748                        }
2749                    }
2750                    if (pkg != null) {
2751                        synchronized (mInstallLock) {
2752                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2753                                    true /* maybeMigrateAppData */);
2754                        }
2755                        count++;
2756                    }
2757                }
2758                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2759            }, "prepareAppData");
2760
2761            // If this is first boot after an OTA, and a normal boot, then
2762            // we need to clear code cache directories.
2763            // Note that we do *not* clear the application profiles. These remain valid
2764            // across OTAs and are used to drive profile verification (post OTA) and
2765            // profile compilation (without waiting to collect a fresh set of profiles).
2766            if (mIsUpgrade && !onlyCore) {
2767                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2768                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2769                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2770                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2771                        // No apps are running this early, so no need to freeze
2772                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2773                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2774                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2775                    }
2776                }
2777                ver.fingerprint = Build.FINGERPRINT;
2778            }
2779
2780            checkDefaultBrowser();
2781
2782            // clear only after permissions and other defaults have been updated
2783            mExistingSystemPackages.clear();
2784            mPromoteSystemApps = false;
2785
2786            // All the changes are done during package scanning.
2787            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2788
2789            // can downgrade to reader
2790            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2791            mSettings.writeLPr();
2792            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2793
2794            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2795                    SystemClock.uptimeMillis());
2796
2797            if (!mOnlyCore) {
2798                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2799                mRequiredInstallerPackage = getRequiredInstallerLPr();
2800                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2801                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2802                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2803                        mIntentFilterVerifierComponent);
2804                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2805                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2806                        SharedLibraryInfo.VERSION_UNDEFINED);
2807                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2808                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2809                        SharedLibraryInfo.VERSION_UNDEFINED);
2810            } else {
2811                mRequiredVerifierPackage = null;
2812                mRequiredInstallerPackage = null;
2813                mRequiredUninstallerPackage = null;
2814                mIntentFilterVerifierComponent = null;
2815                mIntentFilterVerifier = null;
2816                mServicesSystemSharedLibraryPackageName = null;
2817                mSharedSystemSharedLibraryPackageName = null;
2818            }
2819
2820            mInstallerService = new PackageInstallerService(context, this);
2821            final Pair<ComponentName, String> instantAppResolverComponent =
2822                    getInstantAppResolverLPr();
2823            if (instantAppResolverComponent != null) {
2824                if (DEBUG_EPHEMERAL) {
2825                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2826                }
2827                mInstantAppResolverConnection = new EphemeralResolverConnection(
2828                        mContext, instantAppResolverComponent.first,
2829                        instantAppResolverComponent.second);
2830                mInstantAppResolverSettingsComponent =
2831                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2832            } else {
2833                mInstantAppResolverConnection = null;
2834                mInstantAppResolverSettingsComponent = null;
2835            }
2836            updateInstantAppInstallerLocked(null);
2837
2838            // Read and update the usage of dex files.
2839            // Do this at the end of PM init so that all the packages have their
2840            // data directory reconciled.
2841            // At this point we know the code paths of the packages, so we can validate
2842            // the disk file and build the internal cache.
2843            // The usage file is expected to be small so loading and verifying it
2844            // should take a fairly small time compare to the other activities (e.g. package
2845            // scanning).
2846            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2847            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2848            for (int userId : currentUserIds) {
2849                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2850            }
2851            mDexManager.load(userPackages);
2852        } // synchronized (mPackages)
2853        } // synchronized (mInstallLock)
2854
2855        // Now after opening every single application zip, make sure they
2856        // are all flushed.  Not really needed, but keeps things nice and
2857        // tidy.
2858        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2859        Runtime.getRuntime().gc();
2860        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2861
2862        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2863        FallbackCategoryProvider.loadFallbacks();
2864        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2865
2866        // The initial scanning above does many calls into installd while
2867        // holding the mPackages lock, but we're mostly interested in yelling
2868        // once we have a booted system.
2869        mInstaller.setWarnIfHeld(mPackages);
2870
2871        // Expose private service for system components to use.
2872        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2873        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2874    }
2875
2876    private void updateInstantAppInstallerLocked(String modifiedPackage) {
2877        // we're only interested in updating the installer appliction when 1) it's not
2878        // already set or 2) the modified package is the installer
2879        if (mInstantAppInstallerActivity != null
2880                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
2881                        .equals(modifiedPackage)) {
2882            return;
2883        }
2884        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
2885    }
2886
2887    private static File preparePackageParserCache(boolean isUpgrade) {
2888        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2889            return null;
2890        }
2891
2892        // Disable package parsing on eng builds to allow for faster incremental development.
2893        if ("eng".equals(Build.TYPE)) {
2894            return null;
2895        }
2896
2897        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2898            Slog.i(TAG, "Disabling package parser cache due to system property.");
2899            return null;
2900        }
2901
2902        // The base directory for the package parser cache lives under /data/system/.
2903        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2904                "package_cache");
2905        if (cacheBaseDir == null) {
2906            return null;
2907        }
2908
2909        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2910        // This also serves to "GC" unused entries when the package cache version changes (which
2911        // can only happen during upgrades).
2912        if (isUpgrade) {
2913            FileUtils.deleteContents(cacheBaseDir);
2914        }
2915
2916
2917        // Return the versioned package cache directory. This is something like
2918        // "/data/system/package_cache/1"
2919        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2920
2921        // The following is a workaround to aid development on non-numbered userdebug
2922        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2923        // the system partition is newer.
2924        //
2925        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2926        // that starts with "eng." to signify that this is an engineering build and not
2927        // destined for release.
2928        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2929            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2930
2931            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2932            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2933            // in general and should not be used for production changes. In this specific case,
2934            // we know that they will work.
2935            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2936            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2937                FileUtils.deleteContents(cacheBaseDir);
2938                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2939            }
2940        }
2941
2942        return cacheDir;
2943    }
2944
2945    @Override
2946    public boolean isFirstBoot() {
2947        return mFirstBoot;
2948    }
2949
2950    @Override
2951    public boolean isOnlyCoreApps() {
2952        return mOnlyCore;
2953    }
2954
2955    @Override
2956    public boolean isUpgrade() {
2957        return mIsUpgrade;
2958    }
2959
2960    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2961        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2962
2963        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2964                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2965                UserHandle.USER_SYSTEM);
2966        if (matches.size() == 1) {
2967            return matches.get(0).getComponentInfo().packageName;
2968        } else if (matches.size() == 0) {
2969            Log.e(TAG, "There should probably be a verifier, but, none were found");
2970            return null;
2971        }
2972        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2973    }
2974
2975    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2976        synchronized (mPackages) {
2977            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2978            if (libraryEntry == null) {
2979                throw new IllegalStateException("Missing required shared library:" + name);
2980            }
2981            return libraryEntry.apk;
2982        }
2983    }
2984
2985    private @NonNull String getRequiredInstallerLPr() {
2986        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2987        intent.addCategory(Intent.CATEGORY_DEFAULT);
2988        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2989
2990        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2991                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2992                UserHandle.USER_SYSTEM);
2993        if (matches.size() == 1) {
2994            ResolveInfo resolveInfo = matches.get(0);
2995            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2996                throw new RuntimeException("The installer must be a privileged app");
2997            }
2998            return matches.get(0).getComponentInfo().packageName;
2999        } else {
3000            throw new RuntimeException("There must be exactly one installer; found " + matches);
3001        }
3002    }
3003
3004    private @NonNull String getRequiredUninstallerLPr() {
3005        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3006        intent.addCategory(Intent.CATEGORY_DEFAULT);
3007        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3008
3009        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3010                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3011                UserHandle.USER_SYSTEM);
3012        if (resolveInfo == null ||
3013                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3014            throw new RuntimeException("There must be exactly one uninstaller; found "
3015                    + resolveInfo);
3016        }
3017        return resolveInfo.getComponentInfo().packageName;
3018    }
3019
3020    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3021        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3022
3023        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3024                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3025                UserHandle.USER_SYSTEM);
3026        ResolveInfo best = null;
3027        final int N = matches.size();
3028        for (int i = 0; i < N; i++) {
3029            final ResolveInfo cur = matches.get(i);
3030            final String packageName = cur.getComponentInfo().packageName;
3031            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3032                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3033                continue;
3034            }
3035
3036            if (best == null || cur.priority > best.priority) {
3037                best = cur;
3038            }
3039        }
3040
3041        if (best != null) {
3042            return best.getComponentInfo().getComponentName();
3043        } else {
3044            throw new RuntimeException("There must be at least one intent filter verifier");
3045        }
3046    }
3047
3048    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3049        final String[] packageArray =
3050                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3051        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3052            if (DEBUG_EPHEMERAL) {
3053                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3054            }
3055            return null;
3056        }
3057
3058        final int callingUid = Binder.getCallingUid();
3059        final int resolveFlags =
3060                MATCH_DIRECT_BOOT_AWARE
3061                | MATCH_DIRECT_BOOT_UNAWARE
3062                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3063        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3064        final Intent resolverIntent = new Intent(actionName);
3065        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3066                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3067        // temporarily look for the old action
3068        if (resolvers.size() == 0) {
3069            if (DEBUG_EPHEMERAL) {
3070                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3071            }
3072            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3073            resolverIntent.setAction(actionName);
3074            resolvers = queryIntentServicesInternal(resolverIntent, null,
3075                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3076        }
3077        final int N = resolvers.size();
3078        if (N == 0) {
3079            if (DEBUG_EPHEMERAL) {
3080                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3081            }
3082            return null;
3083        }
3084
3085        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3086        for (int i = 0; i < N; i++) {
3087            final ResolveInfo info = resolvers.get(i);
3088
3089            if (info.serviceInfo == null) {
3090                continue;
3091            }
3092
3093            final String packageName = info.serviceInfo.packageName;
3094            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3095                if (DEBUG_EPHEMERAL) {
3096                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3097                            + " pkg: " + packageName + ", info:" + info);
3098                }
3099                continue;
3100            }
3101
3102            if (DEBUG_EPHEMERAL) {
3103                Slog.v(TAG, "Ephemeral resolver found;"
3104                        + " pkg: " + packageName + ", info:" + info);
3105            }
3106            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3107        }
3108        if (DEBUG_EPHEMERAL) {
3109            Slog.v(TAG, "Ephemeral resolver NOT found");
3110        }
3111        return null;
3112    }
3113
3114    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3115        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3116        intent.addCategory(Intent.CATEGORY_DEFAULT);
3117        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3118
3119        final int resolveFlags =
3120                MATCH_DIRECT_BOOT_AWARE
3121                | MATCH_DIRECT_BOOT_UNAWARE
3122                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3123        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3124                resolveFlags, UserHandle.USER_SYSTEM);
3125        // temporarily look for the old action
3126        if (matches.isEmpty()) {
3127            if (DEBUG_EPHEMERAL) {
3128                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3129            }
3130            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3131            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3132                    resolveFlags, UserHandle.USER_SYSTEM);
3133        }
3134        Iterator<ResolveInfo> iter = matches.iterator();
3135        while (iter.hasNext()) {
3136            final ResolveInfo rInfo = iter.next();
3137            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3138            if (ps != null) {
3139                final PermissionsState permissionsState = ps.getPermissionsState();
3140                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3141                    continue;
3142                }
3143            }
3144            iter.remove();
3145        }
3146        if (matches.size() == 0) {
3147            return null;
3148        } else if (matches.size() == 1) {
3149            return (ActivityInfo) matches.get(0).getComponentInfo();
3150        } else {
3151            throw new RuntimeException(
3152                    "There must be at most one ephemeral installer; found " + matches);
3153        }
3154    }
3155
3156    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3157            @NonNull ComponentName resolver) {
3158        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3159                .addCategory(Intent.CATEGORY_DEFAULT)
3160                .setPackage(resolver.getPackageName());
3161        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3162        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3163                UserHandle.USER_SYSTEM);
3164        // temporarily look for the old action
3165        if (matches.isEmpty()) {
3166            if (DEBUG_EPHEMERAL) {
3167                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3168            }
3169            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3170            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3171                    UserHandle.USER_SYSTEM);
3172        }
3173        if (matches.isEmpty()) {
3174            return null;
3175        }
3176        return matches.get(0).getComponentInfo().getComponentName();
3177    }
3178
3179    private void primeDomainVerificationsLPw(int userId) {
3180        if (DEBUG_DOMAIN_VERIFICATION) {
3181            Slog.d(TAG, "Priming domain verifications in user " + userId);
3182        }
3183
3184        SystemConfig systemConfig = SystemConfig.getInstance();
3185        ArraySet<String> packages = systemConfig.getLinkedApps();
3186
3187        for (String packageName : packages) {
3188            PackageParser.Package pkg = mPackages.get(packageName);
3189            if (pkg != null) {
3190                if (!pkg.isSystemApp()) {
3191                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3192                    continue;
3193                }
3194
3195                ArraySet<String> domains = null;
3196                for (PackageParser.Activity a : pkg.activities) {
3197                    for (ActivityIntentInfo filter : a.intents) {
3198                        if (hasValidDomains(filter)) {
3199                            if (domains == null) {
3200                                domains = new ArraySet<String>();
3201                            }
3202                            domains.addAll(filter.getHostsList());
3203                        }
3204                    }
3205                }
3206
3207                if (domains != null && domains.size() > 0) {
3208                    if (DEBUG_DOMAIN_VERIFICATION) {
3209                        Slog.v(TAG, "      + " + packageName);
3210                    }
3211                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3212                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3213                    // and then 'always' in the per-user state actually used for intent resolution.
3214                    final IntentFilterVerificationInfo ivi;
3215                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3216                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3217                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3218                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3219                } else {
3220                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3221                            + "' does not handle web links");
3222                }
3223            } else {
3224                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3225            }
3226        }
3227
3228        scheduleWritePackageRestrictionsLocked(userId);
3229        scheduleWriteSettingsLocked();
3230    }
3231
3232    private void applyFactoryDefaultBrowserLPw(int userId) {
3233        // The default browser app's package name is stored in a string resource,
3234        // with a product-specific overlay used for vendor customization.
3235        String browserPkg = mContext.getResources().getString(
3236                com.android.internal.R.string.default_browser);
3237        if (!TextUtils.isEmpty(browserPkg)) {
3238            // non-empty string => required to be a known package
3239            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3240            if (ps == null) {
3241                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3242                browserPkg = null;
3243            } else {
3244                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3245            }
3246        }
3247
3248        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3249        // default.  If there's more than one, just leave everything alone.
3250        if (browserPkg == null) {
3251            calculateDefaultBrowserLPw(userId);
3252        }
3253    }
3254
3255    private void calculateDefaultBrowserLPw(int userId) {
3256        List<String> allBrowsers = resolveAllBrowserApps(userId);
3257        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3258        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3259    }
3260
3261    private List<String> resolveAllBrowserApps(int userId) {
3262        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3263        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3264                PackageManager.MATCH_ALL, userId);
3265
3266        final int count = list.size();
3267        List<String> result = new ArrayList<String>(count);
3268        for (int i=0; i<count; i++) {
3269            ResolveInfo info = list.get(i);
3270            if (info.activityInfo == null
3271                    || !info.handleAllWebDataURI
3272                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3273                    || result.contains(info.activityInfo.packageName)) {
3274                continue;
3275            }
3276            result.add(info.activityInfo.packageName);
3277        }
3278
3279        return result;
3280    }
3281
3282    private boolean packageIsBrowser(String packageName, int userId) {
3283        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3284                PackageManager.MATCH_ALL, userId);
3285        final int N = list.size();
3286        for (int i = 0; i < N; i++) {
3287            ResolveInfo info = list.get(i);
3288            if (packageName.equals(info.activityInfo.packageName)) {
3289                return true;
3290            }
3291        }
3292        return false;
3293    }
3294
3295    private void checkDefaultBrowser() {
3296        final int myUserId = UserHandle.myUserId();
3297        final String packageName = getDefaultBrowserPackageName(myUserId);
3298        if (packageName != null) {
3299            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3300            if (info == null) {
3301                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3302                synchronized (mPackages) {
3303                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3304                }
3305            }
3306        }
3307    }
3308
3309    @Override
3310    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3311            throws RemoteException {
3312        try {
3313            return super.onTransact(code, data, reply, flags);
3314        } catch (RuntimeException e) {
3315            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3316                Slog.wtf(TAG, "Package Manager Crash", e);
3317            }
3318            throw e;
3319        }
3320    }
3321
3322    static int[] appendInts(int[] cur, int[] add) {
3323        if (add == null) return cur;
3324        if (cur == null) return add;
3325        final int N = add.length;
3326        for (int i=0; i<N; i++) {
3327            cur = appendInt(cur, add[i]);
3328        }
3329        return cur;
3330    }
3331
3332    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3333        if (!sUserManager.exists(userId)) return null;
3334        if (ps == null) {
3335            return null;
3336        }
3337        final PackageParser.Package p = ps.pkg;
3338        if (p == null) {
3339            return null;
3340        }
3341        // Filter out ephemeral app metadata:
3342        //   * The system/shell/root can see metadata for any app
3343        //   * An installed app can see metadata for 1) other installed apps
3344        //     and 2) ephemeral apps that have explicitly interacted with it
3345        //   * Ephemeral apps can only see their own data and exposed installed apps
3346        //   * Holding a signature permission allows seeing instant apps
3347        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3348        if (callingAppId != Process.SYSTEM_UID
3349                && callingAppId != Process.SHELL_UID
3350                && callingAppId != Process.ROOT_UID
3351                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3352                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3353            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3354            if (instantAppPackageName != null) {
3355                // ephemeral apps can only get information on themselves or
3356                // installed apps that are exposed.
3357                if (!instantAppPackageName.equals(p.packageName)
3358                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3359                    return null;
3360                }
3361            } else {
3362                if (ps.getInstantApp(userId)) {
3363                    // only get access to the ephemeral app if we've been granted access
3364                    if (!mInstantAppRegistry.isInstantAccessGranted(
3365                            userId, callingAppId, ps.appId)) {
3366                        return null;
3367                    }
3368                }
3369            }
3370        }
3371
3372        final PermissionsState permissionsState = ps.getPermissionsState();
3373
3374        // Compute GIDs only if requested
3375        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3376                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3377        // Compute granted permissions only if package has requested permissions
3378        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3379                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3380        final PackageUserState state = ps.readUserState(userId);
3381
3382        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3383                && ps.isSystem()) {
3384            flags |= MATCH_ANY_USER;
3385        }
3386
3387        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3388                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3389
3390        if (packageInfo == null) {
3391            return null;
3392        }
3393
3394        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3395
3396        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3397                resolveExternalPackageNameLPr(p);
3398
3399        return packageInfo;
3400    }
3401
3402    @Override
3403    public void checkPackageStartable(String packageName, int userId) {
3404        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3405
3406        synchronized (mPackages) {
3407            final PackageSetting ps = mSettings.mPackages.get(packageName);
3408            if (ps == null) {
3409                throw new SecurityException("Package " + packageName + " was not found!");
3410            }
3411
3412            if (!ps.getInstalled(userId)) {
3413                throw new SecurityException(
3414                        "Package " + packageName + " was not installed for user " + userId + "!");
3415            }
3416
3417            if (mSafeMode && !ps.isSystem()) {
3418                throw new SecurityException("Package " + packageName + " not a system app!");
3419            }
3420
3421            if (mFrozenPackages.contains(packageName)) {
3422                throw new SecurityException("Package " + packageName + " is currently frozen!");
3423            }
3424
3425            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3426                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3427                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3428            }
3429        }
3430    }
3431
3432    @Override
3433    public boolean isPackageAvailable(String packageName, int userId) {
3434        if (!sUserManager.exists(userId)) return false;
3435        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3436                false /* requireFullPermission */, false /* checkShell */, "is package available");
3437        synchronized (mPackages) {
3438            PackageParser.Package p = mPackages.get(packageName);
3439            if (p != null) {
3440                final PackageSetting ps = (PackageSetting) p.mExtras;
3441                if (ps != null) {
3442                    final PackageUserState state = ps.readUserState(userId);
3443                    if (state != null) {
3444                        return PackageParser.isAvailable(state);
3445                    }
3446                }
3447            }
3448        }
3449        return false;
3450    }
3451
3452    @Override
3453    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3454        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3455                flags, userId);
3456    }
3457
3458    @Override
3459    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3460            int flags, int userId) {
3461        return getPackageInfoInternal(versionedPackage.getPackageName(),
3462                // TODO: We will change version code to long, so in the new API it is long
3463                (int) versionedPackage.getVersionCode(), flags, userId);
3464    }
3465
3466    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3467            int flags, int userId) {
3468        if (!sUserManager.exists(userId)) return null;
3469        flags = updateFlagsForPackage(flags, userId, packageName);
3470        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3471                false /* requireFullPermission */, false /* checkShell */, "get package info");
3472
3473        // reader
3474        synchronized (mPackages) {
3475            // Normalize package name to handle renamed packages and static libs
3476            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3477
3478            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3479            if (matchFactoryOnly) {
3480                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3481                if (ps != null) {
3482                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3483                        return null;
3484                    }
3485                    return generatePackageInfo(ps, flags, userId);
3486                }
3487            }
3488
3489            PackageParser.Package p = mPackages.get(packageName);
3490            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3491                return null;
3492            }
3493            if (DEBUG_PACKAGE_INFO)
3494                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3495            if (p != null) {
3496                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3497                        Binder.getCallingUid(), userId)) {
3498                    return null;
3499                }
3500                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3501            }
3502            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3503                final PackageSetting ps = mSettings.mPackages.get(packageName);
3504                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3505                    return null;
3506                }
3507                return generatePackageInfo(ps, flags, userId);
3508            }
3509        }
3510        return null;
3511    }
3512
3513
3514    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3515        // System/shell/root get to see all static libs
3516        final int appId = UserHandle.getAppId(uid);
3517        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3518                || appId == Process.ROOT_UID) {
3519            return false;
3520        }
3521
3522        // No package means no static lib as it is always on internal storage
3523        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3524            return false;
3525        }
3526
3527        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3528                ps.pkg.staticSharedLibVersion);
3529        if (libEntry == null) {
3530            return false;
3531        }
3532
3533        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3534        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3535        if (uidPackageNames == null) {
3536            return true;
3537        }
3538
3539        for (String uidPackageName : uidPackageNames) {
3540            if (ps.name.equals(uidPackageName)) {
3541                return false;
3542            }
3543            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3544            if (uidPs != null) {
3545                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3546                        libEntry.info.getName());
3547                if (index < 0) {
3548                    continue;
3549                }
3550                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3551                    return false;
3552                }
3553            }
3554        }
3555        return true;
3556    }
3557
3558    @Override
3559    public String[] currentToCanonicalPackageNames(String[] names) {
3560        String[] out = new String[names.length];
3561        // reader
3562        synchronized (mPackages) {
3563            for (int i=names.length-1; i>=0; i--) {
3564                PackageSetting ps = mSettings.mPackages.get(names[i]);
3565                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3566            }
3567        }
3568        return out;
3569    }
3570
3571    @Override
3572    public String[] canonicalToCurrentPackageNames(String[] names) {
3573        String[] out = new String[names.length];
3574        // reader
3575        synchronized (mPackages) {
3576            for (int i=names.length-1; i>=0; i--) {
3577                String cur = mSettings.getRenamedPackageLPr(names[i]);
3578                out[i] = cur != null ? cur : names[i];
3579            }
3580        }
3581        return out;
3582    }
3583
3584    @Override
3585    public int getPackageUid(String packageName, int flags, int userId) {
3586        if (!sUserManager.exists(userId)) return -1;
3587        flags = updateFlagsForPackage(flags, userId, packageName);
3588        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3589                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3590
3591        // reader
3592        synchronized (mPackages) {
3593            final PackageParser.Package p = mPackages.get(packageName);
3594            if (p != null && p.isMatch(flags)) {
3595                return UserHandle.getUid(userId, p.applicationInfo.uid);
3596            }
3597            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3598                final PackageSetting ps = mSettings.mPackages.get(packageName);
3599                if (ps != null && ps.isMatch(flags)) {
3600                    return UserHandle.getUid(userId, ps.appId);
3601                }
3602            }
3603        }
3604
3605        return -1;
3606    }
3607
3608    @Override
3609    public int[] getPackageGids(String packageName, int flags, int userId) {
3610        if (!sUserManager.exists(userId)) return null;
3611        flags = updateFlagsForPackage(flags, userId, packageName);
3612        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3613                false /* requireFullPermission */, false /* checkShell */,
3614                "getPackageGids");
3615
3616        // reader
3617        synchronized (mPackages) {
3618            final PackageParser.Package p = mPackages.get(packageName);
3619            if (p != null && p.isMatch(flags)) {
3620                PackageSetting ps = (PackageSetting) p.mExtras;
3621                // TODO: Shouldn't this be checking for package installed state for userId and
3622                // return null?
3623                return ps.getPermissionsState().computeGids(userId);
3624            }
3625            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3626                final PackageSetting ps = mSettings.mPackages.get(packageName);
3627                if (ps != null && ps.isMatch(flags)) {
3628                    return ps.getPermissionsState().computeGids(userId);
3629                }
3630            }
3631        }
3632
3633        return null;
3634    }
3635
3636    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3637        if (bp.perm != null) {
3638            return PackageParser.generatePermissionInfo(bp.perm, flags);
3639        }
3640        PermissionInfo pi = new PermissionInfo();
3641        pi.name = bp.name;
3642        pi.packageName = bp.sourcePackage;
3643        pi.nonLocalizedLabel = bp.name;
3644        pi.protectionLevel = bp.protectionLevel;
3645        return pi;
3646    }
3647
3648    @Override
3649    public PermissionInfo getPermissionInfo(String name, int flags) {
3650        // reader
3651        synchronized (mPackages) {
3652            final BasePermission p = mSettings.mPermissions.get(name);
3653            if (p != null) {
3654                return generatePermissionInfo(p, flags);
3655            }
3656            return null;
3657        }
3658    }
3659
3660    @Override
3661    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3662            int flags) {
3663        // reader
3664        synchronized (mPackages) {
3665            if (group != null && !mPermissionGroups.containsKey(group)) {
3666                // This is thrown as NameNotFoundException
3667                return null;
3668            }
3669
3670            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3671            for (BasePermission p : mSettings.mPermissions.values()) {
3672                if (group == null) {
3673                    if (p.perm == null || p.perm.info.group == null) {
3674                        out.add(generatePermissionInfo(p, flags));
3675                    }
3676                } else {
3677                    if (p.perm != null && group.equals(p.perm.info.group)) {
3678                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3679                    }
3680                }
3681            }
3682            return new ParceledListSlice<>(out);
3683        }
3684    }
3685
3686    @Override
3687    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3688        // reader
3689        synchronized (mPackages) {
3690            return PackageParser.generatePermissionGroupInfo(
3691                    mPermissionGroups.get(name), flags);
3692        }
3693    }
3694
3695    @Override
3696    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3697        // reader
3698        synchronized (mPackages) {
3699            final int N = mPermissionGroups.size();
3700            ArrayList<PermissionGroupInfo> out
3701                    = new ArrayList<PermissionGroupInfo>(N);
3702            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3703                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3704            }
3705            return new ParceledListSlice<>(out);
3706        }
3707    }
3708
3709    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3710            int uid, int userId) {
3711        if (!sUserManager.exists(userId)) return null;
3712        PackageSetting ps = mSettings.mPackages.get(packageName);
3713        if (ps != null) {
3714            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3715                return null;
3716            }
3717            if (ps.pkg == null) {
3718                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3719                if (pInfo != null) {
3720                    return pInfo.applicationInfo;
3721                }
3722                return null;
3723            }
3724            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3725                    ps.readUserState(userId), userId);
3726            if (ai != null) {
3727                rebaseEnabledOverlays(ai, userId);
3728                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3729            }
3730            return ai;
3731        }
3732        return null;
3733    }
3734
3735    @Override
3736    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3737        if (!sUserManager.exists(userId)) return null;
3738        flags = updateFlagsForApplication(flags, userId, packageName);
3739        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3740                false /* requireFullPermission */, false /* checkShell */, "get application info");
3741
3742        // writer
3743        synchronized (mPackages) {
3744            // Normalize package name to handle renamed packages and static libs
3745            packageName = resolveInternalPackageNameLPr(packageName,
3746                    PackageManager.VERSION_CODE_HIGHEST);
3747
3748            PackageParser.Package p = mPackages.get(packageName);
3749            if (DEBUG_PACKAGE_INFO) Log.v(
3750                    TAG, "getApplicationInfo " + packageName
3751                    + ": " + p);
3752            if (p != null) {
3753                PackageSetting ps = mSettings.mPackages.get(packageName);
3754                if (ps == null) return null;
3755                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3756                    return null;
3757                }
3758                // Note: isEnabledLP() does not apply here - always return info
3759                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3760                        p, flags, ps.readUserState(userId), userId);
3761                if (ai != null) {
3762                    rebaseEnabledOverlays(ai, userId);
3763                    ai.packageName = resolveExternalPackageNameLPr(p);
3764                }
3765                return ai;
3766            }
3767            if ("android".equals(packageName)||"system".equals(packageName)) {
3768                return mAndroidApplication;
3769            }
3770            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3771                // Already generates the external package name
3772                return generateApplicationInfoFromSettingsLPw(packageName,
3773                        Binder.getCallingUid(), flags, userId);
3774            }
3775        }
3776        return null;
3777    }
3778
3779    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3780        List<String> paths = new ArrayList<>();
3781        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3782            mEnabledOverlayPaths.get(userId);
3783        if (userSpecificOverlays != null) {
3784            if (!"android".equals(ai.packageName)) {
3785                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3786                if (frameworkOverlays != null) {
3787                    paths.addAll(frameworkOverlays);
3788                }
3789            }
3790
3791            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3792            if (appOverlays != null) {
3793                paths.addAll(appOverlays);
3794            }
3795        }
3796        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3797    }
3798
3799    private String normalizePackageNameLPr(String packageName) {
3800        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3801        return normalizedPackageName != null ? normalizedPackageName : packageName;
3802    }
3803
3804    @Override
3805    public void deletePreloadsFileCache() {
3806        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3807            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3808        }
3809        File dir = Environment.getDataPreloadsFileCacheDirectory();
3810        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3811        FileUtils.deleteContents(dir);
3812    }
3813
3814    @Override
3815    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3816            final IPackageDataObserver observer) {
3817        mContext.enforceCallingOrSelfPermission(
3818                android.Manifest.permission.CLEAR_APP_CACHE, null);
3819        mHandler.post(() -> {
3820            boolean success = false;
3821            try {
3822                freeStorage(volumeUuid, freeStorageSize, 0);
3823                success = true;
3824            } catch (IOException e) {
3825                Slog.w(TAG, e);
3826            }
3827            if (observer != null) {
3828                try {
3829                    observer.onRemoveCompleted(null, success);
3830                } catch (RemoteException e) {
3831                    Slog.w(TAG, e);
3832                }
3833            }
3834        });
3835    }
3836
3837    @Override
3838    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3839            final IntentSender pi) {
3840        mContext.enforceCallingOrSelfPermission(
3841                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3842        mHandler.post(() -> {
3843            boolean success = false;
3844            try {
3845                freeStorage(volumeUuid, freeStorageSize, 0);
3846                success = true;
3847            } catch (IOException e) {
3848                Slog.w(TAG, e);
3849            }
3850            if (pi != null) {
3851                try {
3852                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3853                } catch (SendIntentException e) {
3854                    Slog.w(TAG, e);
3855                }
3856            }
3857        });
3858    }
3859
3860    /**
3861     * Blocking call to clear various types of cached data across the system
3862     * until the requested bytes are available.
3863     */
3864    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3865        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3866        final File file = storage.findPathForUuid(volumeUuid);
3867        if (file.getUsableSpace() >= bytes) return;
3868
3869        if (ENABLE_FREE_CACHE_V2) {
3870            final boolean aggressive = (storageFlags
3871                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3872            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
3873                    volumeUuid);
3874
3875            // 1. Pre-flight to determine if we have any chance to succeed
3876            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3877            if (internalVolume && (aggressive || SystemProperties
3878                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
3879                deletePreloadsFileCache();
3880                if (file.getUsableSpace() >= bytes) return;
3881            }
3882
3883            // 3. Consider parsed APK data (aggressive only)
3884            if (internalVolume && aggressive) {
3885                FileUtils.deleteContents(mCacheDir);
3886                if (file.getUsableSpace() >= bytes) return;
3887            }
3888
3889            // 4. Consider cached app data (above quotas)
3890            try {
3891                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3892            } catch (InstallerException ignored) {
3893            }
3894            if (file.getUsableSpace() >= bytes) return;
3895
3896            // 5. Consider shared libraries with refcount=0 and age>2h
3897            // 6. Consider dexopt output (aggressive only)
3898            // 7. Consider ephemeral apps not used in last week
3899
3900            // 8. Consider cached app data (below quotas)
3901            try {
3902                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3903                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3904            } catch (InstallerException ignored) {
3905            }
3906            if (file.getUsableSpace() >= bytes) return;
3907
3908            // 9. Consider DropBox entries
3909            // 10. Consider ephemeral cookies
3910
3911        } else {
3912            try {
3913                mInstaller.freeCache(volumeUuid, bytes, 0);
3914            } catch (InstallerException ignored) {
3915            }
3916            if (file.getUsableSpace() >= bytes) return;
3917        }
3918
3919        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3920    }
3921
3922    /**
3923     * Update given flags based on encryption status of current user.
3924     */
3925    private int updateFlags(int flags, int userId) {
3926        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3927                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3928            // Caller expressed an explicit opinion about what encryption
3929            // aware/unaware components they want to see, so fall through and
3930            // give them what they want
3931        } else {
3932            // Caller expressed no opinion, so match based on user state
3933            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3934                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3935            } else {
3936                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3937            }
3938        }
3939        return flags;
3940    }
3941
3942    private UserManagerInternal getUserManagerInternal() {
3943        if (mUserManagerInternal == null) {
3944            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3945        }
3946        return mUserManagerInternal;
3947    }
3948
3949    private DeviceIdleController.LocalService getDeviceIdleController() {
3950        if (mDeviceIdleController == null) {
3951            mDeviceIdleController =
3952                    LocalServices.getService(DeviceIdleController.LocalService.class);
3953        }
3954        return mDeviceIdleController;
3955    }
3956
3957    /**
3958     * Update given flags when being used to request {@link PackageInfo}.
3959     */
3960    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3961        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3962        boolean triaged = true;
3963        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3964                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3965            // Caller is asking for component details, so they'd better be
3966            // asking for specific encryption matching behavior, or be triaged
3967            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3968                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3969                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3970                triaged = false;
3971            }
3972        }
3973        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3974                | PackageManager.MATCH_SYSTEM_ONLY
3975                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3976            triaged = false;
3977        }
3978        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3979            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3980                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3981                    + Debug.getCallers(5));
3982        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3983                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3984            // If the caller wants all packages and has a restricted profile associated with it,
3985            // then match all users. This is to make sure that launchers that need to access work
3986            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3987            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3988            flags |= PackageManager.MATCH_ANY_USER;
3989        }
3990        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3991            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3992                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3993        }
3994        return updateFlags(flags, userId);
3995    }
3996
3997    /**
3998     * Update given flags when being used to request {@link ApplicationInfo}.
3999     */
4000    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4001        return updateFlagsForPackage(flags, userId, cookie);
4002    }
4003
4004    /**
4005     * Update given flags when being used to request {@link ComponentInfo}.
4006     */
4007    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4008        if (cookie instanceof Intent) {
4009            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4010                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4011            }
4012        }
4013
4014        boolean triaged = true;
4015        // Caller is asking for component details, so they'd better be
4016        // asking for specific encryption matching behavior, or be triaged
4017        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4018                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4019                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4020            triaged = false;
4021        }
4022        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4023            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4024                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4025        }
4026
4027        return updateFlags(flags, userId);
4028    }
4029
4030    /**
4031     * Update given intent when being used to request {@link ResolveInfo}.
4032     */
4033    private Intent updateIntentForResolve(Intent intent) {
4034        if (intent.getSelector() != null) {
4035            intent = intent.getSelector();
4036        }
4037        if (DEBUG_PREFERRED) {
4038            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4039        }
4040        return intent;
4041    }
4042
4043    /**
4044     * Update given flags when being used to request {@link ResolveInfo}.
4045     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4046     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4047     * flag set. However, this flag is only honoured in three circumstances:
4048     * <ul>
4049     * <li>when called from a system process</li>
4050     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4051     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4052     * action and a {@code android.intent.category.BROWSABLE} category</li>
4053     * </ul>
4054     */
4055    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4056            boolean includeInstantApps) {
4057        // Safe mode means we shouldn't match any third-party components
4058        if (mSafeMode) {
4059            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4060        }
4061        if (getInstantAppPackageName(callingUid) != null) {
4062            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4063            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4064            flags |= PackageManager.MATCH_INSTANT;
4065        } else {
4066            // Otherwise, prevent leaking ephemeral components
4067            final boolean isSpecialProcess =
4068                    callingUid == Process.SYSTEM_UID
4069                    || callingUid == Process.SHELL_UID
4070                    || callingUid == 0;
4071            final boolean allowMatchInstant =
4072                    (includeInstantApps
4073                            && Intent.ACTION_VIEW.equals(intent.getAction())
4074                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4075                            && hasWebURI(intent))
4076                    || isSpecialProcess
4077                    || mContext.checkCallingOrSelfPermission(
4078                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4079            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4080            if (!allowMatchInstant) {
4081                flags &= ~PackageManager.MATCH_INSTANT;
4082            }
4083        }
4084        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4085    }
4086
4087    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4088            int userId) {
4089        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4090        if (ret != null) {
4091            rebaseEnabledOverlays(ret.applicationInfo, userId);
4092        }
4093        return ret;
4094    }
4095
4096    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4097            PackageUserState state, int userId) {
4098        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4099        if (ai != null) {
4100            rebaseEnabledOverlays(ai.applicationInfo, userId);
4101        }
4102        return ai;
4103    }
4104
4105    @Override
4106    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4107        if (!sUserManager.exists(userId)) return null;
4108        flags = updateFlagsForComponent(flags, userId, component);
4109        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4110                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4111        synchronized (mPackages) {
4112            PackageParser.Activity a = mActivities.mActivities.get(component);
4113
4114            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4115            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4116                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4117                if (ps == null) return null;
4118                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4119            }
4120            if (mResolveComponentName.equals(component)) {
4121                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4122                        userId);
4123            }
4124        }
4125        return null;
4126    }
4127
4128    @Override
4129    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4130            String resolvedType) {
4131        synchronized (mPackages) {
4132            if (component.equals(mResolveComponentName)) {
4133                // The resolver supports EVERYTHING!
4134                return true;
4135            }
4136            PackageParser.Activity a = mActivities.mActivities.get(component);
4137            if (a == null) {
4138                return false;
4139            }
4140            for (int i=0; i<a.intents.size(); i++) {
4141                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4142                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4143                    return true;
4144                }
4145            }
4146            return false;
4147        }
4148    }
4149
4150    @Override
4151    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4152        if (!sUserManager.exists(userId)) return null;
4153        flags = updateFlagsForComponent(flags, userId, component);
4154        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4155                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4156        synchronized (mPackages) {
4157            PackageParser.Activity a = mReceivers.mActivities.get(component);
4158            if (DEBUG_PACKAGE_INFO) Log.v(
4159                TAG, "getReceiverInfo " + component + ": " + a);
4160            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4161                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4162                if (ps == null) return null;
4163                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4164            }
4165        }
4166        return null;
4167    }
4168
4169    @Override
4170    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4171        if (!sUserManager.exists(userId)) return null;
4172        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4173
4174        flags = updateFlagsForPackage(flags, userId, null);
4175
4176        final boolean canSeeStaticLibraries =
4177                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4178                        == PERMISSION_GRANTED
4179                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4180                        == PERMISSION_GRANTED
4181                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4182                        == PERMISSION_GRANTED
4183                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4184                        == PERMISSION_GRANTED;
4185
4186        synchronized (mPackages) {
4187            List<SharedLibraryInfo> result = null;
4188
4189            final int libCount = mSharedLibraries.size();
4190            for (int i = 0; i < libCount; i++) {
4191                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4192                if (versionedLib == null) {
4193                    continue;
4194                }
4195
4196                final int versionCount = versionedLib.size();
4197                for (int j = 0; j < versionCount; j++) {
4198                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4199                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4200                        break;
4201                    }
4202                    final long identity = Binder.clearCallingIdentity();
4203                    try {
4204                        // TODO: We will change version code to long, so in the new API it is long
4205                        PackageInfo packageInfo = getPackageInfoVersioned(
4206                                libInfo.getDeclaringPackage(), flags, userId);
4207                        if (packageInfo == null) {
4208                            continue;
4209                        }
4210                    } finally {
4211                        Binder.restoreCallingIdentity(identity);
4212                    }
4213
4214                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4215                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4216                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4217
4218                    if (result == null) {
4219                        result = new ArrayList<>();
4220                    }
4221                    result.add(resLibInfo);
4222                }
4223            }
4224
4225            return result != null ? new ParceledListSlice<>(result) : null;
4226        }
4227    }
4228
4229    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4230            SharedLibraryInfo libInfo, int flags, int userId) {
4231        List<VersionedPackage> versionedPackages = null;
4232        final int packageCount = mSettings.mPackages.size();
4233        for (int i = 0; i < packageCount; i++) {
4234            PackageSetting ps = mSettings.mPackages.valueAt(i);
4235
4236            if (ps == null) {
4237                continue;
4238            }
4239
4240            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4241                continue;
4242            }
4243
4244            final String libName = libInfo.getName();
4245            if (libInfo.isStatic()) {
4246                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4247                if (libIdx < 0) {
4248                    continue;
4249                }
4250                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4251                    continue;
4252                }
4253                if (versionedPackages == null) {
4254                    versionedPackages = new ArrayList<>();
4255                }
4256                // If the dependent is a static shared lib, use the public package name
4257                String dependentPackageName = ps.name;
4258                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4259                    dependentPackageName = ps.pkg.manifestPackageName;
4260                }
4261                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4262            } else if (ps.pkg != null) {
4263                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4264                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4265                    if (versionedPackages == null) {
4266                        versionedPackages = new ArrayList<>();
4267                    }
4268                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4269                }
4270            }
4271        }
4272
4273        return versionedPackages;
4274    }
4275
4276    @Override
4277    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4278        if (!sUserManager.exists(userId)) return null;
4279        flags = updateFlagsForComponent(flags, userId, component);
4280        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4281                false /* requireFullPermission */, false /* checkShell */, "get service info");
4282        synchronized (mPackages) {
4283            PackageParser.Service s = mServices.mServices.get(component);
4284            if (DEBUG_PACKAGE_INFO) Log.v(
4285                TAG, "getServiceInfo " + component + ": " + s);
4286            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4287                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4288                if (ps == null) return null;
4289                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4290                        ps.readUserState(userId), userId);
4291                if (si != null) {
4292                    rebaseEnabledOverlays(si.applicationInfo, userId);
4293                }
4294                return si;
4295            }
4296        }
4297        return null;
4298    }
4299
4300    @Override
4301    public ProviderInfo getProviderInfo(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 provider info");
4306        synchronized (mPackages) {
4307            PackageParser.Provider p = mProviders.mProviders.get(component);
4308            if (DEBUG_PACKAGE_INFO) Log.v(
4309                TAG, "getProviderInfo " + component + ": " + p);
4310            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4311                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4312                if (ps == null) return null;
4313                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4314                        ps.readUserState(userId), userId);
4315                if (pi != null) {
4316                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4317                }
4318                return pi;
4319            }
4320        }
4321        return null;
4322    }
4323
4324    @Override
4325    public String[] getSystemSharedLibraryNames() {
4326        synchronized (mPackages) {
4327            Set<String> libs = null;
4328            final int libCount = mSharedLibraries.size();
4329            for (int i = 0; i < libCount; i++) {
4330                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4331                if (versionedLib == null) {
4332                    continue;
4333                }
4334                final int versionCount = versionedLib.size();
4335                for (int j = 0; j < versionCount; j++) {
4336                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4337                    if (!libEntry.info.isStatic()) {
4338                        if (libs == null) {
4339                            libs = new ArraySet<>();
4340                        }
4341                        libs.add(libEntry.info.getName());
4342                        break;
4343                    }
4344                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4345                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4346                            UserHandle.getUserId(Binder.getCallingUid()))) {
4347                        if (libs == null) {
4348                            libs = new ArraySet<>();
4349                        }
4350                        libs.add(libEntry.info.getName());
4351                        break;
4352                    }
4353                }
4354            }
4355
4356            if (libs != null) {
4357                String[] libsArray = new String[libs.size()];
4358                libs.toArray(libsArray);
4359                return libsArray;
4360            }
4361
4362            return null;
4363        }
4364    }
4365
4366    @Override
4367    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4368        synchronized (mPackages) {
4369            return mServicesSystemSharedLibraryPackageName;
4370        }
4371    }
4372
4373    @Override
4374    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4375        synchronized (mPackages) {
4376            return mSharedSystemSharedLibraryPackageName;
4377        }
4378    }
4379
4380    private void updateSequenceNumberLP(String packageName, int[] userList) {
4381        for (int i = userList.length - 1; i >= 0; --i) {
4382            final int userId = userList[i];
4383            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4384            if (changedPackages == null) {
4385                changedPackages = new SparseArray<>();
4386                mChangedPackages.put(userId, changedPackages);
4387            }
4388            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4389            if (sequenceNumbers == null) {
4390                sequenceNumbers = new HashMap<>();
4391                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4392            }
4393            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4394            if (sequenceNumber != null) {
4395                changedPackages.remove(sequenceNumber);
4396            }
4397            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4398            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4399        }
4400        mChangedPackagesSequenceNumber++;
4401    }
4402
4403    @Override
4404    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4405        synchronized (mPackages) {
4406            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4407                return null;
4408            }
4409            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4410            if (changedPackages == null) {
4411                return null;
4412            }
4413            final List<String> packageNames =
4414                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4415            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4416                final String packageName = changedPackages.get(i);
4417                if (packageName != null) {
4418                    packageNames.add(packageName);
4419                }
4420            }
4421            return packageNames.isEmpty()
4422                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4423        }
4424    }
4425
4426    @Override
4427    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4428        ArrayList<FeatureInfo> res;
4429        synchronized (mAvailableFeatures) {
4430            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4431            res.addAll(mAvailableFeatures.values());
4432        }
4433        final FeatureInfo fi = new FeatureInfo();
4434        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4435                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4436        res.add(fi);
4437
4438        return new ParceledListSlice<>(res);
4439    }
4440
4441    @Override
4442    public boolean hasSystemFeature(String name, int version) {
4443        synchronized (mAvailableFeatures) {
4444            final FeatureInfo feat = mAvailableFeatures.get(name);
4445            if (feat == null) {
4446                return false;
4447            } else {
4448                return feat.version >= version;
4449            }
4450        }
4451    }
4452
4453    @Override
4454    public int checkPermission(String permName, String pkgName, int userId) {
4455        if (!sUserManager.exists(userId)) {
4456            return PackageManager.PERMISSION_DENIED;
4457        }
4458
4459        synchronized (mPackages) {
4460            final PackageParser.Package p = mPackages.get(pkgName);
4461            if (p != null && p.mExtras != null) {
4462                final PackageSetting ps = (PackageSetting) p.mExtras;
4463                final PermissionsState permissionsState = ps.getPermissionsState();
4464                if (permissionsState.hasPermission(permName, userId)) {
4465                    return PackageManager.PERMISSION_GRANTED;
4466                }
4467                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4468                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4469                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4470                    return PackageManager.PERMISSION_GRANTED;
4471                }
4472            }
4473        }
4474
4475        return PackageManager.PERMISSION_DENIED;
4476    }
4477
4478    @Override
4479    public int checkUidPermission(String permName, int uid) {
4480        final int userId = UserHandle.getUserId(uid);
4481
4482        if (!sUserManager.exists(userId)) {
4483            return PackageManager.PERMISSION_DENIED;
4484        }
4485
4486        synchronized (mPackages) {
4487            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4488            if (obj != null) {
4489                final SettingBase ps = (SettingBase) obj;
4490                final PermissionsState permissionsState = ps.getPermissionsState();
4491                if (permissionsState.hasPermission(permName, userId)) {
4492                    return PackageManager.PERMISSION_GRANTED;
4493                }
4494                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4495                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4496                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4497                    return PackageManager.PERMISSION_GRANTED;
4498                }
4499            } else {
4500                ArraySet<String> perms = mSystemPermissions.get(uid);
4501                if (perms != null) {
4502                    if (perms.contains(permName)) {
4503                        return PackageManager.PERMISSION_GRANTED;
4504                    }
4505                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4506                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4507                        return PackageManager.PERMISSION_GRANTED;
4508                    }
4509                }
4510            }
4511        }
4512
4513        return PackageManager.PERMISSION_DENIED;
4514    }
4515
4516    @Override
4517    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4518        if (UserHandle.getCallingUserId() != userId) {
4519            mContext.enforceCallingPermission(
4520                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4521                    "isPermissionRevokedByPolicy for user " + userId);
4522        }
4523
4524        if (checkPermission(permission, packageName, userId)
4525                == PackageManager.PERMISSION_GRANTED) {
4526            return false;
4527        }
4528
4529        final long identity = Binder.clearCallingIdentity();
4530        try {
4531            final int flags = getPermissionFlags(permission, packageName, userId);
4532            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4533        } finally {
4534            Binder.restoreCallingIdentity(identity);
4535        }
4536    }
4537
4538    @Override
4539    public String getPermissionControllerPackageName() {
4540        synchronized (mPackages) {
4541            return mRequiredInstallerPackage;
4542        }
4543    }
4544
4545    /**
4546     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4547     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4548     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4549     * @param message the message to log on security exception
4550     */
4551    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4552            boolean checkShell, String message) {
4553        if (userId < 0) {
4554            throw new IllegalArgumentException("Invalid userId " + userId);
4555        }
4556        if (checkShell) {
4557            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4558        }
4559        if (userId == UserHandle.getUserId(callingUid)) return;
4560        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4561            if (requireFullPermission) {
4562                mContext.enforceCallingOrSelfPermission(
4563                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4564            } else {
4565                try {
4566                    mContext.enforceCallingOrSelfPermission(
4567                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4568                } catch (SecurityException se) {
4569                    mContext.enforceCallingOrSelfPermission(
4570                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4571                }
4572            }
4573        }
4574    }
4575
4576    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4577        if (callingUid == Process.SHELL_UID) {
4578            if (userHandle >= 0
4579                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4580                throw new SecurityException("Shell does not have permission to access user "
4581                        + userHandle);
4582            } else if (userHandle < 0) {
4583                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4584                        + Debug.getCallers(3));
4585            }
4586        }
4587    }
4588
4589    private BasePermission findPermissionTreeLP(String permName) {
4590        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4591            if (permName.startsWith(bp.name) &&
4592                    permName.length() > bp.name.length() &&
4593                    permName.charAt(bp.name.length()) == '.') {
4594                return bp;
4595            }
4596        }
4597        return null;
4598    }
4599
4600    private BasePermission checkPermissionTreeLP(String permName) {
4601        if (permName != null) {
4602            BasePermission bp = findPermissionTreeLP(permName);
4603            if (bp != null) {
4604                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4605                    return bp;
4606                }
4607                throw new SecurityException("Calling uid "
4608                        + Binder.getCallingUid()
4609                        + " is not allowed to add to permission tree "
4610                        + bp.name + " owned by uid " + bp.uid);
4611            }
4612        }
4613        throw new SecurityException("No permission tree found for " + permName);
4614    }
4615
4616    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4617        if (s1 == null) {
4618            return s2 == null;
4619        }
4620        if (s2 == null) {
4621            return false;
4622        }
4623        if (s1.getClass() != s2.getClass()) {
4624            return false;
4625        }
4626        return s1.equals(s2);
4627    }
4628
4629    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4630        if (pi1.icon != pi2.icon) return false;
4631        if (pi1.logo != pi2.logo) return false;
4632        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4633        if (!compareStrings(pi1.name, pi2.name)) return false;
4634        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4635        // We'll take care of setting this one.
4636        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4637        // These are not currently stored in settings.
4638        //if (!compareStrings(pi1.group, pi2.group)) return false;
4639        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4640        //if (pi1.labelRes != pi2.labelRes) return false;
4641        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4642        return true;
4643    }
4644
4645    int permissionInfoFootprint(PermissionInfo info) {
4646        int size = info.name.length();
4647        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4648        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4649        return size;
4650    }
4651
4652    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4653        int size = 0;
4654        for (BasePermission perm : mSettings.mPermissions.values()) {
4655            if (perm.uid == tree.uid) {
4656                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4657            }
4658        }
4659        return size;
4660    }
4661
4662    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4663        // We calculate the max size of permissions defined by this uid and throw
4664        // if that plus the size of 'info' would exceed our stated maximum.
4665        if (tree.uid != Process.SYSTEM_UID) {
4666            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4667            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4668                throw new SecurityException("Permission tree size cap exceeded");
4669            }
4670        }
4671    }
4672
4673    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4674        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4675            throw new SecurityException("Label must be specified in permission");
4676        }
4677        BasePermission tree = checkPermissionTreeLP(info.name);
4678        BasePermission bp = mSettings.mPermissions.get(info.name);
4679        boolean added = bp == null;
4680        boolean changed = true;
4681        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4682        if (added) {
4683            enforcePermissionCapLocked(info, tree);
4684            bp = new BasePermission(info.name, tree.sourcePackage,
4685                    BasePermission.TYPE_DYNAMIC);
4686        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4687            throw new SecurityException(
4688                    "Not allowed to modify non-dynamic permission "
4689                    + info.name);
4690        } else {
4691            if (bp.protectionLevel == fixedLevel
4692                    && bp.perm.owner.equals(tree.perm.owner)
4693                    && bp.uid == tree.uid
4694                    && comparePermissionInfos(bp.perm.info, info)) {
4695                changed = false;
4696            }
4697        }
4698        bp.protectionLevel = fixedLevel;
4699        info = new PermissionInfo(info);
4700        info.protectionLevel = fixedLevel;
4701        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4702        bp.perm.info.packageName = tree.perm.info.packageName;
4703        bp.uid = tree.uid;
4704        if (added) {
4705            mSettings.mPermissions.put(info.name, bp);
4706        }
4707        if (changed) {
4708            if (!async) {
4709                mSettings.writeLPr();
4710            } else {
4711                scheduleWriteSettingsLocked();
4712            }
4713        }
4714        return added;
4715    }
4716
4717    @Override
4718    public boolean addPermission(PermissionInfo info) {
4719        synchronized (mPackages) {
4720            return addPermissionLocked(info, false);
4721        }
4722    }
4723
4724    @Override
4725    public boolean addPermissionAsync(PermissionInfo info) {
4726        synchronized (mPackages) {
4727            return addPermissionLocked(info, true);
4728        }
4729    }
4730
4731    @Override
4732    public void removePermission(String name) {
4733        synchronized (mPackages) {
4734            checkPermissionTreeLP(name);
4735            BasePermission bp = mSettings.mPermissions.get(name);
4736            if (bp != null) {
4737                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4738                    throw new SecurityException(
4739                            "Not allowed to modify non-dynamic permission "
4740                            + name);
4741                }
4742                mSettings.mPermissions.remove(name);
4743                mSettings.writeLPr();
4744            }
4745        }
4746    }
4747
4748    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4749            BasePermission bp) {
4750        int index = pkg.requestedPermissions.indexOf(bp.name);
4751        if (index == -1) {
4752            throw new SecurityException("Package " + pkg.packageName
4753                    + " has not requested permission " + bp.name);
4754        }
4755        if (!bp.isRuntime() && !bp.isDevelopment()) {
4756            throw new SecurityException("Permission " + bp.name
4757                    + " is not a changeable permission type");
4758        }
4759    }
4760
4761    @Override
4762    public void grantRuntimePermission(String packageName, String name, final int userId) {
4763        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4764    }
4765
4766    private void grantRuntimePermission(String packageName, String name, final int userId,
4767            boolean overridePolicy) {
4768        if (!sUserManager.exists(userId)) {
4769            Log.e(TAG, "No such user:" + userId);
4770            return;
4771        }
4772
4773        mContext.enforceCallingOrSelfPermission(
4774                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4775                "grantRuntimePermission");
4776
4777        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4778                true /* requireFullPermission */, true /* checkShell */,
4779                "grantRuntimePermission");
4780
4781        final int uid;
4782        final SettingBase sb;
4783
4784        synchronized (mPackages) {
4785            final PackageParser.Package pkg = mPackages.get(packageName);
4786            if (pkg == null) {
4787                throw new IllegalArgumentException("Unknown package: " + packageName);
4788            }
4789
4790            final BasePermission bp = mSettings.mPermissions.get(name);
4791            if (bp == null) {
4792                throw new IllegalArgumentException("Unknown permission: " + name);
4793            }
4794
4795            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4796
4797            // If a permission review is required for legacy apps we represent
4798            // their permissions as always granted runtime ones since we need
4799            // to keep the review required permission flag per user while an
4800            // install permission's state is shared across all users.
4801            if (mPermissionReviewRequired
4802                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4803                    && bp.isRuntime()) {
4804                return;
4805            }
4806
4807            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4808            sb = (SettingBase) pkg.mExtras;
4809            if (sb == null) {
4810                throw new IllegalArgumentException("Unknown package: " + packageName);
4811            }
4812
4813            final PermissionsState permissionsState = sb.getPermissionsState();
4814
4815            final int flags = permissionsState.getPermissionFlags(name, userId);
4816            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4817                throw new SecurityException("Cannot grant system fixed permission "
4818                        + name + " for package " + packageName);
4819            }
4820            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4821                throw new SecurityException("Cannot grant policy fixed permission "
4822                        + name + " for package " + packageName);
4823            }
4824
4825            if (bp.isDevelopment()) {
4826                // Development permissions must be handled specially, since they are not
4827                // normal runtime permissions.  For now they apply to all users.
4828                if (permissionsState.grantInstallPermission(bp) !=
4829                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4830                    scheduleWriteSettingsLocked();
4831                }
4832                return;
4833            }
4834
4835            final PackageSetting ps = mSettings.mPackages.get(packageName);
4836            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4837                throw new SecurityException("Cannot grant non-ephemeral permission"
4838                        + name + " for package " + packageName);
4839            }
4840
4841            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4842                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4843                return;
4844            }
4845
4846            final int result = permissionsState.grantRuntimePermission(bp, userId);
4847            switch (result) {
4848                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4849                    return;
4850                }
4851
4852                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4853                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4854                    mHandler.post(new Runnable() {
4855                        @Override
4856                        public void run() {
4857                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4858                        }
4859                    });
4860                }
4861                break;
4862            }
4863
4864            if (bp.isRuntime()) {
4865                logPermissionGranted(mContext, name, packageName);
4866            }
4867
4868            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4869
4870            // Not critical if that is lost - app has to request again.
4871            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4872        }
4873
4874        // Only need to do this if user is initialized. Otherwise it's a new user
4875        // and there are no processes running as the user yet and there's no need
4876        // to make an expensive call to remount processes for the changed permissions.
4877        if (READ_EXTERNAL_STORAGE.equals(name)
4878                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4879            final long token = Binder.clearCallingIdentity();
4880            try {
4881                if (sUserManager.isInitialized(userId)) {
4882                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4883                            StorageManagerInternal.class);
4884                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4885                }
4886            } finally {
4887                Binder.restoreCallingIdentity(token);
4888            }
4889        }
4890    }
4891
4892    @Override
4893    public void revokeRuntimePermission(String packageName, String name, int userId) {
4894        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4895    }
4896
4897    private void revokeRuntimePermission(String packageName, String name, int userId,
4898            boolean overridePolicy) {
4899        if (!sUserManager.exists(userId)) {
4900            Log.e(TAG, "No such user:" + userId);
4901            return;
4902        }
4903
4904        mContext.enforceCallingOrSelfPermission(
4905                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4906                "revokeRuntimePermission");
4907
4908        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4909                true /* requireFullPermission */, true /* checkShell */,
4910                "revokeRuntimePermission");
4911
4912        final int appId;
4913
4914        synchronized (mPackages) {
4915            final PackageParser.Package pkg = mPackages.get(packageName);
4916            if (pkg == null) {
4917                throw new IllegalArgumentException("Unknown package: " + packageName);
4918            }
4919
4920            final BasePermission bp = mSettings.mPermissions.get(name);
4921            if (bp == null) {
4922                throw new IllegalArgumentException("Unknown permission: " + name);
4923            }
4924
4925            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4926
4927            // If a permission review is required for legacy apps we represent
4928            // their permissions as always granted runtime ones since we need
4929            // to keep the review required permission flag per user while an
4930            // install permission's state is shared across all users.
4931            if (mPermissionReviewRequired
4932                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4933                    && bp.isRuntime()) {
4934                return;
4935            }
4936
4937            SettingBase sb = (SettingBase) pkg.mExtras;
4938            if (sb == null) {
4939                throw new IllegalArgumentException("Unknown package: " + packageName);
4940            }
4941
4942            final PermissionsState permissionsState = sb.getPermissionsState();
4943
4944            final int flags = permissionsState.getPermissionFlags(name, userId);
4945            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4946                throw new SecurityException("Cannot revoke system fixed permission "
4947                        + name + " for package " + packageName);
4948            }
4949            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4950                throw new SecurityException("Cannot revoke policy fixed permission "
4951                        + name + " for package " + packageName);
4952            }
4953
4954            if (bp.isDevelopment()) {
4955                // Development permissions must be handled specially, since they are not
4956                // normal runtime permissions.  For now they apply to all users.
4957                if (permissionsState.revokeInstallPermission(bp) !=
4958                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4959                    scheduleWriteSettingsLocked();
4960                }
4961                return;
4962            }
4963
4964            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4965                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4966                return;
4967            }
4968
4969            if (bp.isRuntime()) {
4970                logPermissionRevoked(mContext, name, packageName);
4971            }
4972
4973            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4974
4975            // Critical, after this call app should never have the permission.
4976            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4977
4978            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4979        }
4980
4981        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4982    }
4983
4984    /**
4985     * Get the first event id for the permission.
4986     *
4987     * <p>There are four events for each permission: <ul>
4988     *     <li>Request permission: first id + 0</li>
4989     *     <li>Grant permission: first id + 1</li>
4990     *     <li>Request for permission denied: first id + 2</li>
4991     *     <li>Revoke permission: first id + 3</li>
4992     * </ul></p>
4993     *
4994     * @param name name of the permission
4995     *
4996     * @return The first event id for the permission
4997     */
4998    private static int getBaseEventId(@NonNull String name) {
4999        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5000
5001        if (eventIdIndex == -1) {
5002            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5003                    || "user".equals(Build.TYPE)) {
5004                Log.i(TAG, "Unknown permission " + name);
5005
5006                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5007            } else {
5008                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5009                //
5010                // Also update
5011                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5012                // - metrics_constants.proto
5013                throw new IllegalStateException("Unknown permission " + name);
5014            }
5015        }
5016
5017        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5018    }
5019
5020    /**
5021     * Log that a permission was revoked.
5022     *
5023     * @param context Context of the caller
5024     * @param name name of the permission
5025     * @param packageName package permission if for
5026     */
5027    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5028            @NonNull String packageName) {
5029        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5030    }
5031
5032    /**
5033     * Log that a permission request was granted.
5034     *
5035     * @param context Context of the caller
5036     * @param name name of the permission
5037     * @param packageName package permission if for
5038     */
5039    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5040            @NonNull String packageName) {
5041        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5042    }
5043
5044    @Override
5045    public void resetRuntimePermissions() {
5046        mContext.enforceCallingOrSelfPermission(
5047                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5048                "revokeRuntimePermission");
5049
5050        int callingUid = Binder.getCallingUid();
5051        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5052            mContext.enforceCallingOrSelfPermission(
5053                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5054                    "resetRuntimePermissions");
5055        }
5056
5057        synchronized (mPackages) {
5058            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5059            for (int userId : UserManagerService.getInstance().getUserIds()) {
5060                final int packageCount = mPackages.size();
5061                for (int i = 0; i < packageCount; i++) {
5062                    PackageParser.Package pkg = mPackages.valueAt(i);
5063                    if (!(pkg.mExtras instanceof PackageSetting)) {
5064                        continue;
5065                    }
5066                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5067                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5068                }
5069            }
5070        }
5071    }
5072
5073    @Override
5074    public int getPermissionFlags(String name, String packageName, int userId) {
5075        if (!sUserManager.exists(userId)) {
5076            return 0;
5077        }
5078
5079        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5080
5081        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5082                true /* requireFullPermission */, false /* checkShell */,
5083                "getPermissionFlags");
5084
5085        synchronized (mPackages) {
5086            final PackageParser.Package pkg = mPackages.get(packageName);
5087            if (pkg == null) {
5088                return 0;
5089            }
5090
5091            final BasePermission bp = mSettings.mPermissions.get(name);
5092            if (bp == null) {
5093                return 0;
5094            }
5095
5096            SettingBase sb = (SettingBase) pkg.mExtras;
5097            if (sb == null) {
5098                return 0;
5099            }
5100
5101            PermissionsState permissionsState = sb.getPermissionsState();
5102            return permissionsState.getPermissionFlags(name, userId);
5103        }
5104    }
5105
5106    @Override
5107    public void updatePermissionFlags(String name, String packageName, int flagMask,
5108            int flagValues, int userId) {
5109        if (!sUserManager.exists(userId)) {
5110            return;
5111        }
5112
5113        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5114
5115        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5116                true /* requireFullPermission */, true /* checkShell */,
5117                "updatePermissionFlags");
5118
5119        // Only the system can change these flags and nothing else.
5120        if (getCallingUid() != Process.SYSTEM_UID) {
5121            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5122            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5123            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5124            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5125            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5126        }
5127
5128        synchronized (mPackages) {
5129            final PackageParser.Package pkg = mPackages.get(packageName);
5130            if (pkg == null) {
5131                throw new IllegalArgumentException("Unknown package: " + packageName);
5132            }
5133
5134            final BasePermission bp = mSettings.mPermissions.get(name);
5135            if (bp == null) {
5136                throw new IllegalArgumentException("Unknown permission: " + name);
5137            }
5138
5139            SettingBase sb = (SettingBase) pkg.mExtras;
5140            if (sb == null) {
5141                throw new IllegalArgumentException("Unknown package: " + packageName);
5142            }
5143
5144            PermissionsState permissionsState = sb.getPermissionsState();
5145
5146            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5147
5148            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5149                // Install and runtime permissions are stored in different places,
5150                // so figure out what permission changed and persist the change.
5151                if (permissionsState.getInstallPermissionState(name) != null) {
5152                    scheduleWriteSettingsLocked();
5153                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5154                        || hadState) {
5155                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5156                }
5157            }
5158        }
5159    }
5160
5161    /**
5162     * Update the permission flags for all packages and runtime permissions of a user in order
5163     * to allow device or profile owner to remove POLICY_FIXED.
5164     */
5165    @Override
5166    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5167        if (!sUserManager.exists(userId)) {
5168            return;
5169        }
5170
5171        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5172
5173        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5174                true /* requireFullPermission */, true /* checkShell */,
5175                "updatePermissionFlagsForAllApps");
5176
5177        // Only the system can change system fixed flags.
5178        if (getCallingUid() != Process.SYSTEM_UID) {
5179            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5180            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5181        }
5182
5183        synchronized (mPackages) {
5184            boolean changed = false;
5185            final int packageCount = mPackages.size();
5186            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5187                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5188                SettingBase sb = (SettingBase) pkg.mExtras;
5189                if (sb == null) {
5190                    continue;
5191                }
5192                PermissionsState permissionsState = sb.getPermissionsState();
5193                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5194                        userId, flagMask, flagValues);
5195            }
5196            if (changed) {
5197                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5198            }
5199        }
5200    }
5201
5202    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5203        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5204                != PackageManager.PERMISSION_GRANTED
5205            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5206                != PackageManager.PERMISSION_GRANTED) {
5207            throw new SecurityException(message + " requires "
5208                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5209                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5210        }
5211    }
5212
5213    @Override
5214    public boolean shouldShowRequestPermissionRationale(String permissionName,
5215            String packageName, int userId) {
5216        if (UserHandle.getCallingUserId() != userId) {
5217            mContext.enforceCallingPermission(
5218                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5219                    "canShowRequestPermissionRationale for user " + userId);
5220        }
5221
5222        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5223        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5224            return false;
5225        }
5226
5227        if (checkPermission(permissionName, packageName, userId)
5228                == PackageManager.PERMISSION_GRANTED) {
5229            return false;
5230        }
5231
5232        final int flags;
5233
5234        final long identity = Binder.clearCallingIdentity();
5235        try {
5236            flags = getPermissionFlags(permissionName,
5237                    packageName, userId);
5238        } finally {
5239            Binder.restoreCallingIdentity(identity);
5240        }
5241
5242        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5243                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5244                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5245
5246        if ((flags & fixedFlags) != 0) {
5247            return false;
5248        }
5249
5250        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5251    }
5252
5253    @Override
5254    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5255        mContext.enforceCallingOrSelfPermission(
5256                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5257                "addOnPermissionsChangeListener");
5258
5259        synchronized (mPackages) {
5260            mOnPermissionChangeListeners.addListenerLocked(listener);
5261        }
5262    }
5263
5264    @Override
5265    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5266        synchronized (mPackages) {
5267            mOnPermissionChangeListeners.removeListenerLocked(listener);
5268        }
5269    }
5270
5271    @Override
5272    public boolean isProtectedBroadcast(String actionName) {
5273        synchronized (mPackages) {
5274            if (mProtectedBroadcasts.contains(actionName)) {
5275                return true;
5276            } else if (actionName != null) {
5277                // TODO: remove these terrible hacks
5278                if (actionName.startsWith("android.net.netmon.lingerExpired")
5279                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5280                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5281                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5282                    return true;
5283                }
5284            }
5285        }
5286        return false;
5287    }
5288
5289    @Override
5290    public int checkSignatures(String pkg1, String pkg2) {
5291        synchronized (mPackages) {
5292            final PackageParser.Package p1 = mPackages.get(pkg1);
5293            final PackageParser.Package p2 = mPackages.get(pkg2);
5294            if (p1 == null || p1.mExtras == null
5295                    || p2 == null || p2.mExtras == null) {
5296                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5297            }
5298            return compareSignatures(p1.mSignatures, p2.mSignatures);
5299        }
5300    }
5301
5302    @Override
5303    public int checkUidSignatures(int uid1, int uid2) {
5304        // Map to base uids.
5305        uid1 = UserHandle.getAppId(uid1);
5306        uid2 = UserHandle.getAppId(uid2);
5307        // reader
5308        synchronized (mPackages) {
5309            Signature[] s1;
5310            Signature[] s2;
5311            Object obj = mSettings.getUserIdLPr(uid1);
5312            if (obj != null) {
5313                if (obj instanceof SharedUserSetting) {
5314                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5315                } else if (obj instanceof PackageSetting) {
5316                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5317                } else {
5318                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5319                }
5320            } else {
5321                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5322            }
5323            obj = mSettings.getUserIdLPr(uid2);
5324            if (obj != null) {
5325                if (obj instanceof SharedUserSetting) {
5326                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5327                } else if (obj instanceof PackageSetting) {
5328                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5329                } else {
5330                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5331                }
5332            } else {
5333                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5334            }
5335            return compareSignatures(s1, s2);
5336        }
5337    }
5338
5339    /**
5340     * This method should typically only be used when granting or revoking
5341     * permissions, since the app may immediately restart after this call.
5342     * <p>
5343     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5344     * guard your work against the app being relaunched.
5345     */
5346    private void killUid(int appId, int userId, String reason) {
5347        final long identity = Binder.clearCallingIdentity();
5348        try {
5349            IActivityManager am = ActivityManager.getService();
5350            if (am != null) {
5351                try {
5352                    am.killUid(appId, userId, reason);
5353                } catch (RemoteException e) {
5354                    /* ignore - same process */
5355                }
5356            }
5357        } finally {
5358            Binder.restoreCallingIdentity(identity);
5359        }
5360    }
5361
5362    /**
5363     * Compares two sets of signatures. Returns:
5364     * <br />
5365     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5366     * <br />
5367     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5368     * <br />
5369     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5370     * <br />
5371     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5372     * <br />
5373     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5374     */
5375    static int compareSignatures(Signature[] s1, Signature[] s2) {
5376        if (s1 == null) {
5377            return s2 == null
5378                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5379                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5380        }
5381
5382        if (s2 == null) {
5383            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5384        }
5385
5386        if (s1.length != s2.length) {
5387            return PackageManager.SIGNATURE_NO_MATCH;
5388        }
5389
5390        // Since both signature sets are of size 1, we can compare without HashSets.
5391        if (s1.length == 1) {
5392            return s1[0].equals(s2[0]) ?
5393                    PackageManager.SIGNATURE_MATCH :
5394                    PackageManager.SIGNATURE_NO_MATCH;
5395        }
5396
5397        ArraySet<Signature> set1 = new ArraySet<Signature>();
5398        for (Signature sig : s1) {
5399            set1.add(sig);
5400        }
5401        ArraySet<Signature> set2 = new ArraySet<Signature>();
5402        for (Signature sig : s2) {
5403            set2.add(sig);
5404        }
5405        // Make sure s2 contains all signatures in s1.
5406        if (set1.equals(set2)) {
5407            return PackageManager.SIGNATURE_MATCH;
5408        }
5409        return PackageManager.SIGNATURE_NO_MATCH;
5410    }
5411
5412    /**
5413     * If the database version for this type of package (internal storage or
5414     * external storage) is less than the version where package signatures
5415     * were updated, return true.
5416     */
5417    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5418        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5419        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5420    }
5421
5422    /**
5423     * Used for backward compatibility to make sure any packages with
5424     * certificate chains get upgraded to the new style. {@code existingSigs}
5425     * will be in the old format (since they were stored on disk from before the
5426     * system upgrade) and {@code scannedSigs} will be in the newer format.
5427     */
5428    private int compareSignaturesCompat(PackageSignatures existingSigs,
5429            PackageParser.Package scannedPkg) {
5430        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5431            return PackageManager.SIGNATURE_NO_MATCH;
5432        }
5433
5434        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5435        for (Signature sig : existingSigs.mSignatures) {
5436            existingSet.add(sig);
5437        }
5438        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5439        for (Signature sig : scannedPkg.mSignatures) {
5440            try {
5441                Signature[] chainSignatures = sig.getChainSignatures();
5442                for (Signature chainSig : chainSignatures) {
5443                    scannedCompatSet.add(chainSig);
5444                }
5445            } catch (CertificateEncodingException e) {
5446                scannedCompatSet.add(sig);
5447            }
5448        }
5449        /*
5450         * Make sure the expanded scanned set contains all signatures in the
5451         * existing one.
5452         */
5453        if (scannedCompatSet.equals(existingSet)) {
5454            // Migrate the old signatures to the new scheme.
5455            existingSigs.assignSignatures(scannedPkg.mSignatures);
5456            // The new KeySets will be re-added later in the scanning process.
5457            synchronized (mPackages) {
5458                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5459            }
5460            return PackageManager.SIGNATURE_MATCH;
5461        }
5462        return PackageManager.SIGNATURE_NO_MATCH;
5463    }
5464
5465    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5466        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5467        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5468    }
5469
5470    private int compareSignaturesRecover(PackageSignatures existingSigs,
5471            PackageParser.Package scannedPkg) {
5472        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5473            return PackageManager.SIGNATURE_NO_MATCH;
5474        }
5475
5476        String msg = null;
5477        try {
5478            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5479                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5480                        + scannedPkg.packageName);
5481                return PackageManager.SIGNATURE_MATCH;
5482            }
5483        } catch (CertificateException e) {
5484            msg = e.getMessage();
5485        }
5486
5487        logCriticalInfo(Log.INFO,
5488                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5489        return PackageManager.SIGNATURE_NO_MATCH;
5490    }
5491
5492    @Override
5493    public List<String> getAllPackages() {
5494        synchronized (mPackages) {
5495            return new ArrayList<String>(mPackages.keySet());
5496        }
5497    }
5498
5499    @Override
5500    public String[] getPackagesForUid(int uid) {
5501        final int userId = UserHandle.getUserId(uid);
5502        uid = UserHandle.getAppId(uid);
5503        // reader
5504        synchronized (mPackages) {
5505            Object obj = mSettings.getUserIdLPr(uid);
5506            if (obj instanceof SharedUserSetting) {
5507                final SharedUserSetting sus = (SharedUserSetting) obj;
5508                final int N = sus.packages.size();
5509                String[] res = new String[N];
5510                final Iterator<PackageSetting> it = sus.packages.iterator();
5511                int i = 0;
5512                while (it.hasNext()) {
5513                    PackageSetting ps = it.next();
5514                    if (ps.getInstalled(userId)) {
5515                        res[i++] = ps.name;
5516                    } else {
5517                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5518                    }
5519                }
5520                return res;
5521            } else if (obj instanceof PackageSetting) {
5522                final PackageSetting ps = (PackageSetting) obj;
5523                if (ps.getInstalled(userId)) {
5524                    return new String[]{ps.name};
5525                }
5526            }
5527        }
5528        return null;
5529    }
5530
5531    @Override
5532    public String getNameForUid(int uid) {
5533        // reader
5534        synchronized (mPackages) {
5535            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5536            if (obj instanceof SharedUserSetting) {
5537                final SharedUserSetting sus = (SharedUserSetting) obj;
5538                return sus.name + ":" + sus.userId;
5539            } else if (obj instanceof PackageSetting) {
5540                final PackageSetting ps = (PackageSetting) obj;
5541                return ps.name;
5542            }
5543        }
5544        return null;
5545    }
5546
5547    @Override
5548    public int getUidForSharedUser(String sharedUserName) {
5549        if(sharedUserName == null) {
5550            return -1;
5551        }
5552        // reader
5553        synchronized (mPackages) {
5554            SharedUserSetting suid;
5555            try {
5556                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5557                if (suid != null) {
5558                    return suid.userId;
5559                }
5560            } catch (PackageManagerException ignore) {
5561                // can't happen, but, still need to catch it
5562            }
5563            return -1;
5564        }
5565    }
5566
5567    @Override
5568    public int getFlagsForUid(int uid) {
5569        synchronized (mPackages) {
5570            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5571            if (obj instanceof SharedUserSetting) {
5572                final SharedUserSetting sus = (SharedUserSetting) obj;
5573                return sus.pkgFlags;
5574            } else if (obj instanceof PackageSetting) {
5575                final PackageSetting ps = (PackageSetting) obj;
5576                return ps.pkgFlags;
5577            }
5578        }
5579        return 0;
5580    }
5581
5582    @Override
5583    public int getPrivateFlagsForUid(int uid) {
5584        synchronized (mPackages) {
5585            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5586            if (obj instanceof SharedUserSetting) {
5587                final SharedUserSetting sus = (SharedUserSetting) obj;
5588                return sus.pkgPrivateFlags;
5589            } else if (obj instanceof PackageSetting) {
5590                final PackageSetting ps = (PackageSetting) obj;
5591                return ps.pkgPrivateFlags;
5592            }
5593        }
5594        return 0;
5595    }
5596
5597    @Override
5598    public boolean isUidPrivileged(int uid) {
5599        uid = UserHandle.getAppId(uid);
5600        // reader
5601        synchronized (mPackages) {
5602            Object obj = mSettings.getUserIdLPr(uid);
5603            if (obj instanceof SharedUserSetting) {
5604                final SharedUserSetting sus = (SharedUserSetting) obj;
5605                final Iterator<PackageSetting> it = sus.packages.iterator();
5606                while (it.hasNext()) {
5607                    if (it.next().isPrivileged()) {
5608                        return true;
5609                    }
5610                }
5611            } else if (obj instanceof PackageSetting) {
5612                final PackageSetting ps = (PackageSetting) obj;
5613                return ps.isPrivileged();
5614            }
5615        }
5616        return false;
5617    }
5618
5619    @Override
5620    public String[] getAppOpPermissionPackages(String permissionName) {
5621        synchronized (mPackages) {
5622            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5623            if (pkgs == null) {
5624                return null;
5625            }
5626            return pkgs.toArray(new String[pkgs.size()]);
5627        }
5628    }
5629
5630    @Override
5631    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5632            int flags, int userId) {
5633        return resolveIntentInternal(
5634                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
5635    }
5636
5637    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5638            int flags, int userId, boolean includeInstantApps) {
5639        try {
5640            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5641
5642            if (!sUserManager.exists(userId)) return null;
5643            final int callingUid = Binder.getCallingUid();
5644            flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
5645            enforceCrossUserPermission(callingUid, userId,
5646                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5647
5648            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5649            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5650                    flags, userId, includeInstantApps);
5651            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5652
5653            final ResolveInfo bestChoice =
5654                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5655            return bestChoice;
5656        } finally {
5657            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5658        }
5659    }
5660
5661    @Override
5662    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5663        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5664            throw new SecurityException(
5665                    "findPersistentPreferredActivity can only be run by the system");
5666        }
5667        if (!sUserManager.exists(userId)) {
5668            return null;
5669        }
5670        final int callingUid = Binder.getCallingUid();
5671        intent = updateIntentForResolve(intent);
5672        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5673        final int flags = updateFlagsForResolve(
5674                0, userId, intent, callingUid, false /*includeInstantApps*/);
5675        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5676                userId);
5677        synchronized (mPackages) {
5678            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5679                    userId);
5680        }
5681    }
5682
5683    @Override
5684    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5685            IntentFilter filter, int match, ComponentName activity) {
5686        final int userId = UserHandle.getCallingUserId();
5687        if (DEBUG_PREFERRED) {
5688            Log.v(TAG, "setLastChosenActivity intent=" + intent
5689                + " resolvedType=" + resolvedType
5690                + " flags=" + flags
5691                + " filter=" + filter
5692                + " match=" + match
5693                + " activity=" + activity);
5694            filter.dump(new PrintStreamPrinter(System.out), "    ");
5695        }
5696        intent.setComponent(null);
5697        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5698                userId);
5699        // Find any earlier preferred or last chosen entries and nuke them
5700        findPreferredActivity(intent, resolvedType,
5701                flags, query, 0, false, true, false, userId);
5702        // Add the new activity as the last chosen for this filter
5703        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5704                "Setting last chosen");
5705    }
5706
5707    @Override
5708    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5709        final int userId = UserHandle.getCallingUserId();
5710        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5711        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5712                userId);
5713        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5714                false, false, false, userId);
5715    }
5716
5717    /**
5718     * Returns whether or not instant apps have been disabled remotely.
5719     */
5720    private boolean isEphemeralDisabled() {
5721        return mEphemeralAppsDisabled;
5722    }
5723
5724    private boolean isEphemeralAllowed(
5725            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5726            boolean skipPackageCheck) {
5727        final int callingUser = UserHandle.getCallingUserId();
5728        if (mInstantAppResolverConnection == null) {
5729            return false;
5730        }
5731        if (mInstantAppInstallerActivity == null) {
5732            return false;
5733        }
5734        if (intent.getComponent() != null) {
5735            return false;
5736        }
5737        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5738            return false;
5739        }
5740        if (!skipPackageCheck && intent.getPackage() != null) {
5741            return false;
5742        }
5743        final boolean isWebUri = hasWebURI(intent);
5744        if (!isWebUri || intent.getData().getHost() == null) {
5745            return false;
5746        }
5747        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5748        // Or if there's already an ephemeral app installed that handles the action
5749        synchronized (mPackages) {
5750            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5751            for (int n = 0; n < count; n++) {
5752                final ResolveInfo info = resolvedActivities.get(n);
5753                final String packageName = info.activityInfo.packageName;
5754                final PackageSetting ps = mSettings.mPackages.get(packageName);
5755                if (ps != null) {
5756                    // only check domain verification status if the app is not a browser
5757                    if (!info.handleAllWebDataURI) {
5758                        // Try to get the status from User settings first
5759                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5760                        final int status = (int) (packedStatus >> 32);
5761                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5762                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5763                            if (DEBUG_EPHEMERAL) {
5764                                Slog.v(TAG, "DENY instant app;"
5765                                    + " pkg: " + packageName + ", status: " + status);
5766                            }
5767                            return false;
5768                        }
5769                    }
5770                    if (ps.getInstantApp(userId)) {
5771                        if (DEBUG_EPHEMERAL) {
5772                            Slog.v(TAG, "DENY instant app installed;"
5773                                    + " pkg: " + packageName);
5774                        }
5775                        return false;
5776                    }
5777                }
5778            }
5779        }
5780        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5781        return true;
5782    }
5783
5784    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5785            Intent origIntent, String resolvedType, String callingPackage,
5786            int userId) {
5787        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5788                new InstantAppRequest(responseObj, origIntent, resolvedType,
5789                        callingPackage, userId));
5790        mHandler.sendMessage(msg);
5791    }
5792
5793    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5794            int flags, List<ResolveInfo> query, int userId) {
5795        if (query != null) {
5796            final int N = query.size();
5797            if (N == 1) {
5798                return query.get(0);
5799            } else if (N > 1) {
5800                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5801                // If there is more than one activity with the same priority,
5802                // then let the user decide between them.
5803                ResolveInfo r0 = query.get(0);
5804                ResolveInfo r1 = query.get(1);
5805                if (DEBUG_INTENT_MATCHING || debug) {
5806                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5807                            + r1.activityInfo.name + "=" + r1.priority);
5808                }
5809                // If the first activity has a higher priority, or a different
5810                // default, then it is always desirable to pick it.
5811                if (r0.priority != r1.priority
5812                        || r0.preferredOrder != r1.preferredOrder
5813                        || r0.isDefault != r1.isDefault) {
5814                    return query.get(0);
5815                }
5816                // If we have saved a preference for a preferred activity for
5817                // this Intent, use that.
5818                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5819                        flags, query, r0.priority, true, false, debug, userId);
5820                if (ri != null) {
5821                    return ri;
5822                }
5823                // If we have an ephemeral app, use it
5824                for (int i = 0; i < N; i++) {
5825                    ri = query.get(i);
5826                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5827                        return ri;
5828                    }
5829                }
5830                ri = new ResolveInfo(mResolveInfo);
5831                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5832                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5833                // If all of the options come from the same package, show the application's
5834                // label and icon instead of the generic resolver's.
5835                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5836                // and then throw away the ResolveInfo itself, meaning that the caller loses
5837                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5838                // a fallback for this case; we only set the target package's resources on
5839                // the ResolveInfo, not the ActivityInfo.
5840                final String intentPackage = intent.getPackage();
5841                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5842                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5843                    ri.resolvePackageName = intentPackage;
5844                    if (userNeedsBadging(userId)) {
5845                        ri.noResourceId = true;
5846                    } else {
5847                        ri.icon = appi.icon;
5848                    }
5849                    ri.iconResourceId = appi.icon;
5850                    ri.labelRes = appi.labelRes;
5851                }
5852                ri.activityInfo.applicationInfo = new ApplicationInfo(
5853                        ri.activityInfo.applicationInfo);
5854                if (userId != 0) {
5855                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5856                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5857                }
5858                // Make sure that the resolver is displayable in car mode
5859                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5860                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5861                return ri;
5862            }
5863        }
5864        return null;
5865    }
5866
5867    /**
5868     * Return true if the given list is not empty and all of its contents have
5869     * an activityInfo with the given package name.
5870     */
5871    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5872        if (ArrayUtils.isEmpty(list)) {
5873            return false;
5874        }
5875        for (int i = 0, N = list.size(); i < N; i++) {
5876            final ResolveInfo ri = list.get(i);
5877            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5878            if (ai == null || !packageName.equals(ai.packageName)) {
5879                return false;
5880            }
5881        }
5882        return true;
5883    }
5884
5885    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5886            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5887        final int N = query.size();
5888        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5889                .get(userId);
5890        // Get the list of persistent preferred activities that handle the intent
5891        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5892        List<PersistentPreferredActivity> pprefs = ppir != null
5893                ? ppir.queryIntent(intent, resolvedType,
5894                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5895                        userId)
5896                : null;
5897        if (pprefs != null && pprefs.size() > 0) {
5898            final int M = pprefs.size();
5899            for (int i=0; i<M; i++) {
5900                final PersistentPreferredActivity ppa = pprefs.get(i);
5901                if (DEBUG_PREFERRED || debug) {
5902                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5903                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5904                            + "\n  component=" + ppa.mComponent);
5905                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5906                }
5907                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5908                        flags | MATCH_DISABLED_COMPONENTS, userId);
5909                if (DEBUG_PREFERRED || debug) {
5910                    Slog.v(TAG, "Found persistent preferred activity:");
5911                    if (ai != null) {
5912                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5913                    } else {
5914                        Slog.v(TAG, "  null");
5915                    }
5916                }
5917                if (ai == null) {
5918                    // This previously registered persistent preferred activity
5919                    // component is no longer known. Ignore it and do NOT remove it.
5920                    continue;
5921                }
5922                for (int j=0; j<N; j++) {
5923                    final ResolveInfo ri = query.get(j);
5924                    if (!ri.activityInfo.applicationInfo.packageName
5925                            .equals(ai.applicationInfo.packageName)) {
5926                        continue;
5927                    }
5928                    if (!ri.activityInfo.name.equals(ai.name)) {
5929                        continue;
5930                    }
5931                    //  Found a persistent preference that can handle the intent.
5932                    if (DEBUG_PREFERRED || debug) {
5933                        Slog.v(TAG, "Returning persistent preferred activity: " +
5934                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5935                    }
5936                    return ri;
5937                }
5938            }
5939        }
5940        return null;
5941    }
5942
5943    // TODO: handle preferred activities missing while user has amnesia
5944    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5945            List<ResolveInfo> query, int priority, boolean always,
5946            boolean removeMatches, boolean debug, int userId) {
5947        if (!sUserManager.exists(userId)) return null;
5948        final int callingUid = Binder.getCallingUid();
5949        flags = updateFlagsForResolve(
5950                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5951        intent = updateIntentForResolve(intent);
5952        // writer
5953        synchronized (mPackages) {
5954            // Try to find a matching persistent preferred activity.
5955            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5956                    debug, userId);
5957
5958            // If a persistent preferred activity matched, use it.
5959            if (pri != null) {
5960                return pri;
5961            }
5962
5963            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5964            // Get the list of preferred activities that handle the intent
5965            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5966            List<PreferredActivity> prefs = pir != null
5967                    ? pir.queryIntent(intent, resolvedType,
5968                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5969                            userId)
5970                    : null;
5971            if (prefs != null && prefs.size() > 0) {
5972                boolean changed = false;
5973                try {
5974                    // First figure out how good the original match set is.
5975                    // We will only allow preferred activities that came
5976                    // from the same match quality.
5977                    int match = 0;
5978
5979                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5980
5981                    final int N = query.size();
5982                    for (int j=0; j<N; j++) {
5983                        final ResolveInfo ri = query.get(j);
5984                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5985                                + ": 0x" + Integer.toHexString(match));
5986                        if (ri.match > match) {
5987                            match = ri.match;
5988                        }
5989                    }
5990
5991                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5992                            + Integer.toHexString(match));
5993
5994                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5995                    final int M = prefs.size();
5996                    for (int i=0; i<M; i++) {
5997                        final PreferredActivity pa = prefs.get(i);
5998                        if (DEBUG_PREFERRED || debug) {
5999                            Slog.v(TAG, "Checking PreferredActivity ds="
6000                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6001                                    + "\n  component=" + pa.mPref.mComponent);
6002                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6003                        }
6004                        if (pa.mPref.mMatch != match) {
6005                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6006                                    + Integer.toHexString(pa.mPref.mMatch));
6007                            continue;
6008                        }
6009                        // If it's not an "always" type preferred activity and that's what we're
6010                        // looking for, skip it.
6011                        if (always && !pa.mPref.mAlways) {
6012                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6013                            continue;
6014                        }
6015                        final ActivityInfo ai = getActivityInfo(
6016                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6017                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6018                                userId);
6019                        if (DEBUG_PREFERRED || debug) {
6020                            Slog.v(TAG, "Found preferred activity:");
6021                            if (ai != null) {
6022                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6023                            } else {
6024                                Slog.v(TAG, "  null");
6025                            }
6026                        }
6027                        if (ai == null) {
6028                            // This previously registered preferred activity
6029                            // component is no longer known.  Most likely an update
6030                            // to the app was installed and in the new version this
6031                            // component no longer exists.  Clean it up by removing
6032                            // it from the preferred activities list, and skip it.
6033                            Slog.w(TAG, "Removing dangling preferred activity: "
6034                                    + pa.mPref.mComponent);
6035                            pir.removeFilter(pa);
6036                            changed = true;
6037                            continue;
6038                        }
6039                        for (int j=0; j<N; j++) {
6040                            final ResolveInfo ri = query.get(j);
6041                            if (!ri.activityInfo.applicationInfo.packageName
6042                                    .equals(ai.applicationInfo.packageName)) {
6043                                continue;
6044                            }
6045                            if (!ri.activityInfo.name.equals(ai.name)) {
6046                                continue;
6047                            }
6048
6049                            if (removeMatches) {
6050                                pir.removeFilter(pa);
6051                                changed = true;
6052                                if (DEBUG_PREFERRED) {
6053                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6054                                }
6055                                break;
6056                            }
6057
6058                            // Okay we found a previously set preferred or last chosen app.
6059                            // If the result set is different from when this
6060                            // was created, we need to clear it and re-ask the
6061                            // user their preference, if we're looking for an "always" type entry.
6062                            if (always && !pa.mPref.sameSet(query)) {
6063                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6064                                        + intent + " type " + resolvedType);
6065                                if (DEBUG_PREFERRED) {
6066                                    Slog.v(TAG, "Removing preferred activity since set changed "
6067                                            + pa.mPref.mComponent);
6068                                }
6069                                pir.removeFilter(pa);
6070                                // Re-add the filter as a "last chosen" entry (!always)
6071                                PreferredActivity lastChosen = new PreferredActivity(
6072                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6073                                pir.addFilter(lastChosen);
6074                                changed = true;
6075                                return null;
6076                            }
6077
6078                            // Yay! Either the set matched or we're looking for the last chosen
6079                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6080                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6081                            return ri;
6082                        }
6083                    }
6084                } finally {
6085                    if (changed) {
6086                        if (DEBUG_PREFERRED) {
6087                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6088                        }
6089                        scheduleWritePackageRestrictionsLocked(userId);
6090                    }
6091                }
6092            }
6093        }
6094        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6095        return null;
6096    }
6097
6098    /*
6099     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6100     */
6101    @Override
6102    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6103            int targetUserId) {
6104        mContext.enforceCallingOrSelfPermission(
6105                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6106        List<CrossProfileIntentFilter> matches =
6107                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6108        if (matches != null) {
6109            int size = matches.size();
6110            for (int i = 0; i < size; i++) {
6111                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6112            }
6113        }
6114        if (hasWebURI(intent)) {
6115            // cross-profile app linking works only towards the parent.
6116            final int callingUid = Binder.getCallingUid();
6117            final UserInfo parent = getProfileParent(sourceUserId);
6118            synchronized(mPackages) {
6119                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6120                        false /*includeInstantApps*/);
6121                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6122                        intent, resolvedType, flags, sourceUserId, parent.id);
6123                return xpDomainInfo != null;
6124            }
6125        }
6126        return false;
6127    }
6128
6129    private UserInfo getProfileParent(int userId) {
6130        final long identity = Binder.clearCallingIdentity();
6131        try {
6132            return sUserManager.getProfileParent(userId);
6133        } finally {
6134            Binder.restoreCallingIdentity(identity);
6135        }
6136    }
6137
6138    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6139            String resolvedType, int userId) {
6140        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6141        if (resolver != null) {
6142            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6143        }
6144        return null;
6145    }
6146
6147    @Override
6148    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6149            String resolvedType, int flags, int userId) {
6150        try {
6151            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6152
6153            return new ParceledListSlice<>(
6154                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6155        } finally {
6156            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6157        }
6158    }
6159
6160    /**
6161     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6162     * instant, returns {@code null}.
6163     */
6164    private String getInstantAppPackageName(int callingUid) {
6165        // If the caller is an isolated app use the owner's uid for the lookup.
6166        if (Process.isIsolated(callingUid)) {
6167            callingUid = mIsolatedOwners.get(callingUid);
6168        }
6169        final int appId = UserHandle.getAppId(callingUid);
6170        synchronized (mPackages) {
6171            final Object obj = mSettings.getUserIdLPr(appId);
6172            if (obj instanceof PackageSetting) {
6173                final PackageSetting ps = (PackageSetting) obj;
6174                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6175                return isInstantApp ? ps.pkg.packageName : null;
6176            }
6177        }
6178        return null;
6179    }
6180
6181    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6182            String resolvedType, int flags, int userId) {
6183        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6184    }
6185
6186    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6187            String resolvedType, int flags, int userId, boolean includeInstantApps) {
6188        if (!sUserManager.exists(userId)) return Collections.emptyList();
6189        final int callingUid = Binder.getCallingUid();
6190        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6191        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
6192        enforceCrossUserPermission(callingUid, userId,
6193                false /* requireFullPermission */, false /* checkShell */,
6194                "query intent activities");
6195        ComponentName comp = intent.getComponent();
6196        if (comp == null) {
6197            if (intent.getSelector() != null) {
6198                intent = intent.getSelector();
6199                comp = intent.getComponent();
6200            }
6201        }
6202
6203        if (comp != null) {
6204            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6205            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6206            if (ai != null) {
6207                // When specifying an explicit component, we prevent the activity from being
6208                // used when either 1) the calling package is normal and the activity is within
6209                // an ephemeral application or 2) the calling package is ephemeral and the
6210                // activity is not visible to ephemeral applications.
6211                final boolean matchInstantApp =
6212                        (flags & PackageManager.MATCH_INSTANT) != 0;
6213                final boolean matchVisibleToInstantAppOnly =
6214                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6215                final boolean isCallerInstantApp =
6216                        instantAppPkgName != null;
6217                final boolean isTargetSameInstantApp =
6218                        comp.getPackageName().equals(instantAppPkgName);
6219                final boolean isTargetInstantApp =
6220                        (ai.applicationInfo.privateFlags
6221                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6222                final boolean isTargetHiddenFromInstantApp =
6223                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6224                final boolean blockResolution =
6225                        !isTargetSameInstantApp
6226                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6227                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6228                                        && isTargetHiddenFromInstantApp));
6229                if (!blockResolution) {
6230                    final ResolveInfo ri = new ResolveInfo();
6231                    ri.activityInfo = ai;
6232                    list.add(ri);
6233                }
6234            }
6235            return applyPostResolutionFilter(list, instantAppPkgName);
6236        }
6237
6238        // reader
6239        boolean sortResult = false;
6240        boolean addEphemeral = false;
6241        List<ResolveInfo> result;
6242        final String pkgName = intent.getPackage();
6243        final boolean ephemeralDisabled = isEphemeralDisabled();
6244        synchronized (mPackages) {
6245            if (pkgName == null) {
6246                List<CrossProfileIntentFilter> matchingFilters =
6247                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6248                // Check for results that need to skip the current profile.
6249                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6250                        resolvedType, flags, userId);
6251                if (xpResolveInfo != null) {
6252                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6253                    xpResult.add(xpResolveInfo);
6254                    return applyPostResolutionFilter(
6255                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6256                }
6257
6258                // Check for results in the current profile.
6259                result = filterIfNotSystemUser(mActivities.queryIntent(
6260                        intent, resolvedType, flags, userId), userId);
6261                addEphemeral = !ephemeralDisabled
6262                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6263                // Check for cross profile results.
6264                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6265                xpResolveInfo = queryCrossProfileIntents(
6266                        matchingFilters, intent, resolvedType, flags, userId,
6267                        hasNonNegativePriorityResult);
6268                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6269                    boolean isVisibleToUser = filterIfNotSystemUser(
6270                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6271                    if (isVisibleToUser) {
6272                        result.add(xpResolveInfo);
6273                        sortResult = true;
6274                    }
6275                }
6276                if (hasWebURI(intent)) {
6277                    CrossProfileDomainInfo xpDomainInfo = null;
6278                    final UserInfo parent = getProfileParent(userId);
6279                    if (parent != null) {
6280                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6281                                flags, userId, parent.id);
6282                    }
6283                    if (xpDomainInfo != null) {
6284                        if (xpResolveInfo != null) {
6285                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6286                            // in the result.
6287                            result.remove(xpResolveInfo);
6288                        }
6289                        if (result.size() == 0 && !addEphemeral) {
6290                            // No result in current profile, but found candidate in parent user.
6291                            // And we are not going to add emphemeral app, so we can return the
6292                            // result straight away.
6293                            result.add(xpDomainInfo.resolveInfo);
6294                            return applyPostResolutionFilter(result, instantAppPkgName);
6295                        }
6296                    } else if (result.size() <= 1 && !addEphemeral) {
6297                        // No result in parent user and <= 1 result in current profile, and we
6298                        // are not going to add emphemeral app, so we can return the result without
6299                        // further processing.
6300                        return applyPostResolutionFilter(result, instantAppPkgName);
6301                    }
6302                    // We have more than one candidate (combining results from current and parent
6303                    // profile), so we need filtering and sorting.
6304                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6305                            intent, flags, result, xpDomainInfo, userId);
6306                    sortResult = true;
6307                }
6308            } else {
6309                final PackageParser.Package pkg = mPackages.get(pkgName);
6310                if (pkg != null) {
6311                    return applyPostResolutionFilter(filterIfNotSystemUser(
6312                            mActivities.queryIntentForPackage(
6313                                    intent, resolvedType, flags, pkg.activities, userId),
6314                            userId), instantAppPkgName);
6315                } else {
6316                    // the caller wants to resolve for a particular package; however, there
6317                    // were no installed results, so, try to find an ephemeral result
6318                    addEphemeral = !ephemeralDisabled
6319                            && isEphemeralAllowed(
6320                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6321                    result = new ArrayList<ResolveInfo>();
6322                }
6323            }
6324        }
6325        if (addEphemeral) {
6326            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6327            final InstantAppRequest requestObject = new InstantAppRequest(
6328                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6329                    null /*callingPackage*/, userId);
6330            final AuxiliaryResolveInfo auxiliaryResponse =
6331                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6332                            mContext, mInstantAppResolverConnection, requestObject);
6333            if (auxiliaryResponse != null) {
6334                if (DEBUG_EPHEMERAL) {
6335                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6336                }
6337                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6338                final PackageSetting ps =
6339                        mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6340                if (ps != null) {
6341                    ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6342                            mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6343                    ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6344                    ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6345                    // make sure this resolver is the default
6346                    ephemeralInstaller.isDefault = true;
6347                    ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6348                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6349                    // add a non-generic filter
6350                    ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6351                    ephemeralInstaller.filter.addDataPath(
6352                            intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6353                    ephemeralInstaller.instantAppAvailable = true;
6354                    result.add(ephemeralInstaller);
6355                }
6356            }
6357            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6358        }
6359        if (sortResult) {
6360            Collections.sort(result, mResolvePrioritySorter);
6361        }
6362        return applyPostResolutionFilter(result, instantAppPkgName);
6363    }
6364
6365    private static class CrossProfileDomainInfo {
6366        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6367        ResolveInfo resolveInfo;
6368        /* Best domain verification status of the activities found in the other profile */
6369        int bestDomainVerificationStatus;
6370    }
6371
6372    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6373            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6374        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6375                sourceUserId)) {
6376            return null;
6377        }
6378        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6379                resolvedType, flags, parentUserId);
6380
6381        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6382            return null;
6383        }
6384        CrossProfileDomainInfo result = null;
6385        int size = resultTargetUser.size();
6386        for (int i = 0; i < size; i++) {
6387            ResolveInfo riTargetUser = resultTargetUser.get(i);
6388            // Intent filter verification is only for filters that specify a host. So don't return
6389            // those that handle all web uris.
6390            if (riTargetUser.handleAllWebDataURI) {
6391                continue;
6392            }
6393            String packageName = riTargetUser.activityInfo.packageName;
6394            PackageSetting ps = mSettings.mPackages.get(packageName);
6395            if (ps == null) {
6396                continue;
6397            }
6398            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6399            int status = (int)(verificationState >> 32);
6400            if (result == null) {
6401                result = new CrossProfileDomainInfo();
6402                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6403                        sourceUserId, parentUserId);
6404                result.bestDomainVerificationStatus = status;
6405            } else {
6406                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6407                        result.bestDomainVerificationStatus);
6408            }
6409        }
6410        // Don't consider matches with status NEVER across profiles.
6411        if (result != null && result.bestDomainVerificationStatus
6412                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6413            return null;
6414        }
6415        return result;
6416    }
6417
6418    /**
6419     * Verification statuses are ordered from the worse to the best, except for
6420     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6421     */
6422    private int bestDomainVerificationStatus(int status1, int status2) {
6423        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6424            return status2;
6425        }
6426        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6427            return status1;
6428        }
6429        return (int) MathUtils.max(status1, status2);
6430    }
6431
6432    private boolean isUserEnabled(int userId) {
6433        long callingId = Binder.clearCallingIdentity();
6434        try {
6435            UserInfo userInfo = sUserManager.getUserInfo(userId);
6436            return userInfo != null && userInfo.isEnabled();
6437        } finally {
6438            Binder.restoreCallingIdentity(callingId);
6439        }
6440    }
6441
6442    /**
6443     * Filter out activities with systemUserOnly flag set, when current user is not System.
6444     *
6445     * @return filtered list
6446     */
6447    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6448        if (userId == UserHandle.USER_SYSTEM) {
6449            return resolveInfos;
6450        }
6451        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6452            ResolveInfo info = resolveInfos.get(i);
6453            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6454                resolveInfos.remove(i);
6455            }
6456        }
6457        return resolveInfos;
6458    }
6459
6460    /**
6461     * Filters out ephemeral activities.
6462     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6463     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6464     *
6465     * @param resolveInfos The pre-filtered list of resolved activities
6466     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6467     *          is performed.
6468     * @return A filtered list of resolved activities.
6469     */
6470    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6471            String ephemeralPkgName) {
6472        // TODO: When adding on-demand split support for non-instant apps, remove this check
6473        // and always apply post filtering
6474        if (ephemeralPkgName == null) {
6475            return resolveInfos;
6476        }
6477        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6478            final ResolveInfo info = resolveInfos.get(i);
6479            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6480            // allow activities that are defined in the provided package
6481            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6482                if (info.activityInfo.splitName != null
6483                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6484                                info.activityInfo.splitName)) {
6485                    // requested activity is defined in a split that hasn't been installed yet.
6486                    // add the installer to the resolve list
6487                    if (DEBUG_EPHEMERAL) {
6488                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6489                    }
6490                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6491                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6492                            info.activityInfo.packageName, info.activityInfo.splitName,
6493                            info.activityInfo.applicationInfo.versionCode);
6494                    // make sure this resolver is the default
6495                    installerInfo.isDefault = true;
6496                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6497                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6498                    // add a non-generic filter
6499                    installerInfo.filter = new IntentFilter();
6500                    // load resources from the correct package
6501                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6502                    resolveInfos.set(i, installerInfo);
6503                }
6504                continue;
6505            }
6506            // allow activities that have been explicitly exposed to ephemeral apps
6507            if (!isEphemeralApp
6508                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6509                continue;
6510            }
6511            resolveInfos.remove(i);
6512        }
6513        return resolveInfos;
6514    }
6515
6516    /**
6517     * @param resolveInfos list of resolve infos in descending priority order
6518     * @return if the list contains a resolve info with non-negative priority
6519     */
6520    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6521        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6522    }
6523
6524    private static boolean hasWebURI(Intent intent) {
6525        if (intent.getData() == null) {
6526            return false;
6527        }
6528        final String scheme = intent.getScheme();
6529        if (TextUtils.isEmpty(scheme)) {
6530            return false;
6531        }
6532        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6533    }
6534
6535    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6536            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6537            int userId) {
6538        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6539
6540        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6541            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6542                    candidates.size());
6543        }
6544
6545        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6546        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6547        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6548        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6549        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6550        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6551
6552        synchronized (mPackages) {
6553            final int count = candidates.size();
6554            // First, try to use linked apps. Partition the candidates into four lists:
6555            // one for the final results, one for the "do not use ever", one for "undefined status"
6556            // and finally one for "browser app type".
6557            for (int n=0; n<count; n++) {
6558                ResolveInfo info = candidates.get(n);
6559                String packageName = info.activityInfo.packageName;
6560                PackageSetting ps = mSettings.mPackages.get(packageName);
6561                if (ps != null) {
6562                    // Add to the special match all list (Browser use case)
6563                    if (info.handleAllWebDataURI) {
6564                        matchAllList.add(info);
6565                        continue;
6566                    }
6567                    // Try to get the status from User settings first
6568                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6569                    int status = (int)(packedStatus >> 32);
6570                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6571                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6572                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6573                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6574                                    + " : linkgen=" + linkGeneration);
6575                        }
6576                        // Use link-enabled generation as preferredOrder, i.e.
6577                        // prefer newly-enabled over earlier-enabled.
6578                        info.preferredOrder = linkGeneration;
6579                        alwaysList.add(info);
6580                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6581                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6582                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6583                        }
6584                        neverList.add(info);
6585                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6586                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6587                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6588                        }
6589                        alwaysAskList.add(info);
6590                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6591                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6592                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6593                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6594                        }
6595                        undefinedList.add(info);
6596                    }
6597                }
6598            }
6599
6600            // We'll want to include browser possibilities in a few cases
6601            boolean includeBrowser = false;
6602
6603            // First try to add the "always" resolution(s) for the current user, if any
6604            if (alwaysList.size() > 0) {
6605                result.addAll(alwaysList);
6606            } else {
6607                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6608                result.addAll(undefinedList);
6609                // Maybe add one for the other profile.
6610                if (xpDomainInfo != null && (
6611                        xpDomainInfo.bestDomainVerificationStatus
6612                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6613                    result.add(xpDomainInfo.resolveInfo);
6614                }
6615                includeBrowser = true;
6616            }
6617
6618            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6619            // If there were 'always' entries their preferred order has been set, so we also
6620            // back that off to make the alternatives equivalent
6621            if (alwaysAskList.size() > 0) {
6622                for (ResolveInfo i : result) {
6623                    i.preferredOrder = 0;
6624                }
6625                result.addAll(alwaysAskList);
6626                includeBrowser = true;
6627            }
6628
6629            if (includeBrowser) {
6630                // Also add browsers (all of them or only the default one)
6631                if (DEBUG_DOMAIN_VERIFICATION) {
6632                    Slog.v(TAG, "   ...including browsers in candidate set");
6633                }
6634                if ((matchFlags & MATCH_ALL) != 0) {
6635                    result.addAll(matchAllList);
6636                } else {
6637                    // Browser/generic handling case.  If there's a default browser, go straight
6638                    // to that (but only if there is no other higher-priority match).
6639                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6640                    int maxMatchPrio = 0;
6641                    ResolveInfo defaultBrowserMatch = null;
6642                    final int numCandidates = matchAllList.size();
6643                    for (int n = 0; n < numCandidates; n++) {
6644                        ResolveInfo info = matchAllList.get(n);
6645                        // track the highest overall match priority...
6646                        if (info.priority > maxMatchPrio) {
6647                            maxMatchPrio = info.priority;
6648                        }
6649                        // ...and the highest-priority default browser match
6650                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6651                            if (defaultBrowserMatch == null
6652                                    || (defaultBrowserMatch.priority < info.priority)) {
6653                                if (debug) {
6654                                    Slog.v(TAG, "Considering default browser match " + info);
6655                                }
6656                                defaultBrowserMatch = info;
6657                            }
6658                        }
6659                    }
6660                    if (defaultBrowserMatch != null
6661                            && defaultBrowserMatch.priority >= maxMatchPrio
6662                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6663                    {
6664                        if (debug) {
6665                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6666                        }
6667                        result.add(defaultBrowserMatch);
6668                    } else {
6669                        result.addAll(matchAllList);
6670                    }
6671                }
6672
6673                // If there is nothing selected, add all candidates and remove the ones that the user
6674                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6675                if (result.size() == 0) {
6676                    result.addAll(candidates);
6677                    result.removeAll(neverList);
6678                }
6679            }
6680        }
6681        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6682            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6683                    result.size());
6684            for (ResolveInfo info : result) {
6685                Slog.v(TAG, "  + " + info.activityInfo);
6686            }
6687        }
6688        return result;
6689    }
6690
6691    // Returns a packed value as a long:
6692    //
6693    // high 'int'-sized word: link status: undefined/ask/never/always.
6694    // low 'int'-sized word: relative priority among 'always' results.
6695    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6696        long result = ps.getDomainVerificationStatusForUser(userId);
6697        // if none available, get the master status
6698        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6699            if (ps.getIntentFilterVerificationInfo() != null) {
6700                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6701            }
6702        }
6703        return result;
6704    }
6705
6706    private ResolveInfo querySkipCurrentProfileIntents(
6707            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6708            int flags, int sourceUserId) {
6709        if (matchingFilters != null) {
6710            int size = matchingFilters.size();
6711            for (int i = 0; i < size; i ++) {
6712                CrossProfileIntentFilter filter = matchingFilters.get(i);
6713                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6714                    // Checking if there are activities in the target user that can handle the
6715                    // intent.
6716                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6717                            resolvedType, flags, sourceUserId);
6718                    if (resolveInfo != null) {
6719                        return resolveInfo;
6720                    }
6721                }
6722            }
6723        }
6724        return null;
6725    }
6726
6727    // Return matching ResolveInfo in target user if any.
6728    private ResolveInfo queryCrossProfileIntents(
6729            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6730            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6731        if (matchingFilters != null) {
6732            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6733            // match the same intent. For performance reasons, it is better not to
6734            // run queryIntent twice for the same userId
6735            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6736            int size = matchingFilters.size();
6737            for (int i = 0; i < size; i++) {
6738                CrossProfileIntentFilter filter = matchingFilters.get(i);
6739                int targetUserId = filter.getTargetUserId();
6740                boolean skipCurrentProfile =
6741                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6742                boolean skipCurrentProfileIfNoMatchFound =
6743                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6744                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6745                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6746                    // Checking if there are activities in the target user that can handle the
6747                    // intent.
6748                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6749                            resolvedType, flags, sourceUserId);
6750                    if (resolveInfo != null) return resolveInfo;
6751                    alreadyTriedUserIds.put(targetUserId, true);
6752                }
6753            }
6754        }
6755        return null;
6756    }
6757
6758    /**
6759     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6760     * will forward the intent to the filter's target user.
6761     * Otherwise, returns null.
6762     */
6763    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6764            String resolvedType, int flags, int sourceUserId) {
6765        int targetUserId = filter.getTargetUserId();
6766        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6767                resolvedType, flags, targetUserId);
6768        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6769            // If all the matches in the target profile are suspended, return null.
6770            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6771                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6772                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6773                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6774                            targetUserId);
6775                }
6776            }
6777        }
6778        return null;
6779    }
6780
6781    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6782            int sourceUserId, int targetUserId) {
6783        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6784        long ident = Binder.clearCallingIdentity();
6785        boolean targetIsProfile;
6786        try {
6787            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6788        } finally {
6789            Binder.restoreCallingIdentity(ident);
6790        }
6791        String className;
6792        if (targetIsProfile) {
6793            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6794        } else {
6795            className = FORWARD_INTENT_TO_PARENT;
6796        }
6797        ComponentName forwardingActivityComponentName = new ComponentName(
6798                mAndroidApplication.packageName, className);
6799        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6800                sourceUserId);
6801        if (!targetIsProfile) {
6802            forwardingActivityInfo.showUserIcon = targetUserId;
6803            forwardingResolveInfo.noResourceId = true;
6804        }
6805        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6806        forwardingResolveInfo.priority = 0;
6807        forwardingResolveInfo.preferredOrder = 0;
6808        forwardingResolveInfo.match = 0;
6809        forwardingResolveInfo.isDefault = true;
6810        forwardingResolveInfo.filter = filter;
6811        forwardingResolveInfo.targetUserId = targetUserId;
6812        return forwardingResolveInfo;
6813    }
6814
6815    @Override
6816    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6817            Intent[] specifics, String[] specificTypes, Intent intent,
6818            String resolvedType, int flags, int userId) {
6819        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6820                specificTypes, intent, resolvedType, flags, userId));
6821    }
6822
6823    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6824            Intent[] specifics, String[] specificTypes, Intent intent,
6825            String resolvedType, int flags, int userId) {
6826        if (!sUserManager.exists(userId)) return Collections.emptyList();
6827        final int callingUid = Binder.getCallingUid();
6828        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
6829                false /*includeInstantApps*/);
6830        enforceCrossUserPermission(callingUid, userId,
6831                false /*requireFullPermission*/, false /*checkShell*/,
6832                "query intent activity options");
6833        final String resultsAction = intent.getAction();
6834
6835        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6836                | PackageManager.GET_RESOLVED_FILTER, userId);
6837
6838        if (DEBUG_INTENT_MATCHING) {
6839            Log.v(TAG, "Query " + intent + ": " + results);
6840        }
6841
6842        int specificsPos = 0;
6843        int N;
6844
6845        // todo: note that the algorithm used here is O(N^2).  This
6846        // isn't a problem in our current environment, but if we start running
6847        // into situations where we have more than 5 or 10 matches then this
6848        // should probably be changed to something smarter...
6849
6850        // First we go through and resolve each of the specific items
6851        // that were supplied, taking care of removing any corresponding
6852        // duplicate items in the generic resolve list.
6853        if (specifics != null) {
6854            for (int i=0; i<specifics.length; i++) {
6855                final Intent sintent = specifics[i];
6856                if (sintent == null) {
6857                    continue;
6858                }
6859
6860                if (DEBUG_INTENT_MATCHING) {
6861                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6862                }
6863
6864                String action = sintent.getAction();
6865                if (resultsAction != null && resultsAction.equals(action)) {
6866                    // If this action was explicitly requested, then don't
6867                    // remove things that have it.
6868                    action = null;
6869                }
6870
6871                ResolveInfo ri = null;
6872                ActivityInfo ai = null;
6873
6874                ComponentName comp = sintent.getComponent();
6875                if (comp == null) {
6876                    ri = resolveIntent(
6877                        sintent,
6878                        specificTypes != null ? specificTypes[i] : null,
6879                            flags, userId);
6880                    if (ri == null) {
6881                        continue;
6882                    }
6883                    if (ri == mResolveInfo) {
6884                        // ACK!  Must do something better with this.
6885                    }
6886                    ai = ri.activityInfo;
6887                    comp = new ComponentName(ai.applicationInfo.packageName,
6888                            ai.name);
6889                } else {
6890                    ai = getActivityInfo(comp, flags, userId);
6891                    if (ai == null) {
6892                        continue;
6893                    }
6894                }
6895
6896                // Look for any generic query activities that are duplicates
6897                // of this specific one, and remove them from the results.
6898                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6899                N = results.size();
6900                int j;
6901                for (j=specificsPos; j<N; j++) {
6902                    ResolveInfo sri = results.get(j);
6903                    if ((sri.activityInfo.name.equals(comp.getClassName())
6904                            && sri.activityInfo.applicationInfo.packageName.equals(
6905                                    comp.getPackageName()))
6906                        || (action != null && sri.filter.matchAction(action))) {
6907                        results.remove(j);
6908                        if (DEBUG_INTENT_MATCHING) Log.v(
6909                            TAG, "Removing duplicate item from " + j
6910                            + " due to specific " + specificsPos);
6911                        if (ri == null) {
6912                            ri = sri;
6913                        }
6914                        j--;
6915                        N--;
6916                    }
6917                }
6918
6919                // Add this specific item to its proper place.
6920                if (ri == null) {
6921                    ri = new ResolveInfo();
6922                    ri.activityInfo = ai;
6923                }
6924                results.add(specificsPos, ri);
6925                ri.specificIndex = i;
6926                specificsPos++;
6927            }
6928        }
6929
6930        // Now we go through the remaining generic results and remove any
6931        // duplicate actions that are found here.
6932        N = results.size();
6933        for (int i=specificsPos; i<N-1; i++) {
6934            final ResolveInfo rii = results.get(i);
6935            if (rii.filter == null) {
6936                continue;
6937            }
6938
6939            // Iterate over all of the actions of this result's intent
6940            // filter...  typically this should be just one.
6941            final Iterator<String> it = rii.filter.actionsIterator();
6942            if (it == null) {
6943                continue;
6944            }
6945            while (it.hasNext()) {
6946                final String action = it.next();
6947                if (resultsAction != null && resultsAction.equals(action)) {
6948                    // If this action was explicitly requested, then don't
6949                    // remove things that have it.
6950                    continue;
6951                }
6952                for (int j=i+1; j<N; j++) {
6953                    final ResolveInfo rij = results.get(j);
6954                    if (rij.filter != null && rij.filter.hasAction(action)) {
6955                        results.remove(j);
6956                        if (DEBUG_INTENT_MATCHING) Log.v(
6957                            TAG, "Removing duplicate item from " + j
6958                            + " due to action " + action + " at " + i);
6959                        j--;
6960                        N--;
6961                    }
6962                }
6963            }
6964
6965            // If the caller didn't request filter information, drop it now
6966            // so we don't have to marshall/unmarshall it.
6967            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6968                rii.filter = null;
6969            }
6970        }
6971
6972        // Filter out the caller activity if so requested.
6973        if (caller != null) {
6974            N = results.size();
6975            for (int i=0; i<N; i++) {
6976                ActivityInfo ainfo = results.get(i).activityInfo;
6977                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6978                        && caller.getClassName().equals(ainfo.name)) {
6979                    results.remove(i);
6980                    break;
6981                }
6982            }
6983        }
6984
6985        // If the caller didn't request filter information,
6986        // drop them now so we don't have to
6987        // marshall/unmarshall it.
6988        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6989            N = results.size();
6990            for (int i=0; i<N; i++) {
6991                results.get(i).filter = null;
6992            }
6993        }
6994
6995        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6996        return results;
6997    }
6998
6999    @Override
7000    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7001            String resolvedType, int flags, int userId) {
7002        return new ParceledListSlice<>(
7003                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7004    }
7005
7006    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7007            String resolvedType, int flags, int userId) {
7008        if (!sUserManager.exists(userId)) return Collections.emptyList();
7009        final int callingUid = Binder.getCallingUid();
7010        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7011                false /*includeInstantApps*/);
7012        ComponentName comp = intent.getComponent();
7013        if (comp == null) {
7014            if (intent.getSelector() != null) {
7015                intent = intent.getSelector();
7016                comp = intent.getComponent();
7017            }
7018        }
7019        if (comp != null) {
7020            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7021            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7022            if (ai != null) {
7023                ResolveInfo ri = new ResolveInfo();
7024                ri.activityInfo = ai;
7025                list.add(ri);
7026            }
7027            return list;
7028        }
7029
7030        // reader
7031        synchronized (mPackages) {
7032            String pkgName = intent.getPackage();
7033            if (pkgName == null) {
7034                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7035            }
7036            final PackageParser.Package pkg = mPackages.get(pkgName);
7037            if (pkg != null) {
7038                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7039                        userId);
7040            }
7041            return Collections.emptyList();
7042        }
7043    }
7044
7045    @Override
7046    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7047        final int callingUid = Binder.getCallingUid();
7048        return resolveServiceInternal(
7049                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7050    }
7051
7052    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7053            int userId, int callingUid, boolean includeInstantApps) {
7054        if (!sUserManager.exists(userId)) return null;
7055        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7056        List<ResolveInfo> query = queryIntentServicesInternal(
7057                intent, resolvedType, flags, userId, callingUid, includeInstantApps);
7058        if (query != null) {
7059            if (query.size() >= 1) {
7060                // If there is more than one service with the same priority,
7061                // just arbitrarily pick the first one.
7062                return query.get(0);
7063            }
7064        }
7065        return null;
7066    }
7067
7068    @Override
7069    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7070            String resolvedType, int flags, int userId) {
7071        final int callingUid = Binder.getCallingUid();
7072        return new ParceledListSlice<>(queryIntentServicesInternal(
7073                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7074    }
7075
7076    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7077            String resolvedType, int flags, int userId, int callingUid,
7078            boolean includeInstantApps) {
7079        if (!sUserManager.exists(userId)) return Collections.emptyList();
7080        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7081        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7082        ComponentName comp = intent.getComponent();
7083        if (comp == null) {
7084            if (intent.getSelector() != null) {
7085                intent = intent.getSelector();
7086                comp = intent.getComponent();
7087            }
7088        }
7089        if (comp != null) {
7090            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7091            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7092            if (si != null) {
7093                // When specifying an explicit component, we prevent the service from being
7094                // used when either 1) the service is in an instant application and the
7095                // caller is not the same instant application or 2) the calling package is
7096                // ephemeral and the activity is not visible to ephemeral applications.
7097                final boolean matchVisibleToInstantAppOnly =
7098                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7099                final boolean isCallerInstantApp =
7100                        instantAppPkgName != null;
7101                final boolean isTargetSameInstantApp =
7102                        comp.getPackageName().equals(instantAppPkgName);
7103                final boolean isTargetHiddenFromInstantApp =
7104                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
7105                final boolean blockResolution =
7106                        !isTargetSameInstantApp
7107                        && ((matchVisibleToInstantAppOnly && isCallerInstantApp
7108                                        && isTargetHiddenFromInstantApp));
7109                if (!blockResolution) {
7110                    final ResolveInfo ri = new ResolveInfo();
7111                    ri.serviceInfo = si;
7112                    list.add(ri);
7113                }
7114            }
7115            return list;
7116        }
7117
7118        // reader
7119        synchronized (mPackages) {
7120            String pkgName = intent.getPackage();
7121            if (pkgName == null) {
7122                return applyPostServiceResolutionFilter(
7123                        mServices.queryIntent(intent, resolvedType, flags, userId),
7124                        instantAppPkgName);
7125            }
7126            final PackageParser.Package pkg = mPackages.get(pkgName);
7127            if (pkg != null) {
7128                return applyPostServiceResolutionFilter(
7129                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7130                                userId),
7131                        instantAppPkgName);
7132            }
7133            return Collections.emptyList();
7134        }
7135    }
7136
7137    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7138            String instantAppPkgName) {
7139        // TODO: When adding on-demand split support for non-instant apps, remove this check
7140        // and always apply post filtering
7141        if (instantAppPkgName == null) {
7142            return resolveInfos;
7143        }
7144        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7145            final ResolveInfo info = resolveInfos.get(i);
7146            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7147            // allow services that are defined in the provided package
7148            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7149                if (info.serviceInfo.splitName != null
7150                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7151                                info.serviceInfo.splitName)) {
7152                    // requested service is defined in a split that hasn't been installed yet.
7153                    // add the installer to the resolve list
7154                    if (DEBUG_EPHEMERAL) {
7155                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7156                    }
7157                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7158                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7159                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7160                            info.serviceInfo.applicationInfo.versionCode);
7161                    // make sure this resolver is the default
7162                    installerInfo.isDefault = true;
7163                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7164                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7165                    // add a non-generic filter
7166                    installerInfo.filter = new IntentFilter();
7167                    // load resources from the correct package
7168                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7169                    resolveInfos.set(i, installerInfo);
7170                }
7171                continue;
7172            }
7173            // allow services that have been explicitly exposed to ephemeral apps
7174            if (!isEphemeralApp
7175                    && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
7176                continue;
7177            }
7178            resolveInfos.remove(i);
7179        }
7180        return resolveInfos;
7181    }
7182
7183    @Override
7184    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7185            String resolvedType, int flags, int userId) {
7186        return new ParceledListSlice<>(
7187                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7188    }
7189
7190    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7191            Intent intent, String resolvedType, int flags, int userId) {
7192        if (!sUserManager.exists(userId)) return Collections.emptyList();
7193        final int callingUid = Binder.getCallingUid();
7194        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7195                false /*includeInstantApps*/);
7196        ComponentName comp = intent.getComponent();
7197        if (comp == null) {
7198            if (intent.getSelector() != null) {
7199                intent = intent.getSelector();
7200                comp = intent.getComponent();
7201            }
7202        }
7203        if (comp != null) {
7204            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7205            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7206            if (pi != null) {
7207                final ResolveInfo ri = new ResolveInfo();
7208                ri.providerInfo = pi;
7209                list.add(ri);
7210            }
7211            return list;
7212        }
7213
7214        // reader
7215        synchronized (mPackages) {
7216            String pkgName = intent.getPackage();
7217            if (pkgName == null) {
7218                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7219            }
7220            final PackageParser.Package pkg = mPackages.get(pkgName);
7221            if (pkg != null) {
7222                return mProviders.queryIntentForPackage(
7223                        intent, resolvedType, flags, pkg.providers, userId);
7224            }
7225            return Collections.emptyList();
7226        }
7227    }
7228
7229    @Override
7230    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7231        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7232        flags = updateFlagsForPackage(flags, userId, null);
7233        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7234        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7235                true /* requireFullPermission */, false /* checkShell */,
7236                "get installed packages");
7237
7238        // writer
7239        synchronized (mPackages) {
7240            ArrayList<PackageInfo> list;
7241            if (listUninstalled) {
7242                list = new ArrayList<>(mSettings.mPackages.size());
7243                for (PackageSetting ps : mSettings.mPackages.values()) {
7244                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7245                        continue;
7246                    }
7247                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7248                    if (pi != null) {
7249                        list.add(pi);
7250                    }
7251                }
7252            } else {
7253                list = new ArrayList<>(mPackages.size());
7254                for (PackageParser.Package p : mPackages.values()) {
7255                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7256                            Binder.getCallingUid(), userId)) {
7257                        continue;
7258                    }
7259                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7260                            p.mExtras, flags, userId);
7261                    if (pi != null) {
7262                        list.add(pi);
7263                    }
7264                }
7265            }
7266
7267            return new ParceledListSlice<>(list);
7268        }
7269    }
7270
7271    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7272            String[] permissions, boolean[] tmp, int flags, int userId) {
7273        int numMatch = 0;
7274        final PermissionsState permissionsState = ps.getPermissionsState();
7275        for (int i=0; i<permissions.length; i++) {
7276            final String permission = permissions[i];
7277            if (permissionsState.hasPermission(permission, userId)) {
7278                tmp[i] = true;
7279                numMatch++;
7280            } else {
7281                tmp[i] = false;
7282            }
7283        }
7284        if (numMatch == 0) {
7285            return;
7286        }
7287        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7288
7289        // The above might return null in cases of uninstalled apps or install-state
7290        // skew across users/profiles.
7291        if (pi != null) {
7292            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7293                if (numMatch == permissions.length) {
7294                    pi.requestedPermissions = permissions;
7295                } else {
7296                    pi.requestedPermissions = new String[numMatch];
7297                    numMatch = 0;
7298                    for (int i=0; i<permissions.length; i++) {
7299                        if (tmp[i]) {
7300                            pi.requestedPermissions[numMatch] = permissions[i];
7301                            numMatch++;
7302                        }
7303                    }
7304                }
7305            }
7306            list.add(pi);
7307        }
7308    }
7309
7310    @Override
7311    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7312            String[] permissions, int flags, int userId) {
7313        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7314        flags = updateFlagsForPackage(flags, userId, permissions);
7315        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7316                true /* requireFullPermission */, false /* checkShell */,
7317                "get packages holding permissions");
7318        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7319
7320        // writer
7321        synchronized (mPackages) {
7322            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7323            boolean[] tmpBools = new boolean[permissions.length];
7324            if (listUninstalled) {
7325                for (PackageSetting ps : mSettings.mPackages.values()) {
7326                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7327                            userId);
7328                }
7329            } else {
7330                for (PackageParser.Package pkg : mPackages.values()) {
7331                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7332                    if (ps != null) {
7333                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7334                                userId);
7335                    }
7336                }
7337            }
7338
7339            return new ParceledListSlice<PackageInfo>(list);
7340        }
7341    }
7342
7343    @Override
7344    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7345        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7346        flags = updateFlagsForApplication(flags, userId, null);
7347        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7348
7349        // writer
7350        synchronized (mPackages) {
7351            ArrayList<ApplicationInfo> list;
7352            if (listUninstalled) {
7353                list = new ArrayList<>(mSettings.mPackages.size());
7354                for (PackageSetting ps : mSettings.mPackages.values()) {
7355                    ApplicationInfo ai;
7356                    int effectiveFlags = flags;
7357                    if (ps.isSystem()) {
7358                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7359                    }
7360                    if (ps.pkg != null) {
7361                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7362                            continue;
7363                        }
7364                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7365                                ps.readUserState(userId), userId);
7366                        if (ai != null) {
7367                            rebaseEnabledOverlays(ai, userId);
7368                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7369                        }
7370                    } else {
7371                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7372                        // and already converts to externally visible package name
7373                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7374                                Binder.getCallingUid(), effectiveFlags, userId);
7375                    }
7376                    if (ai != null) {
7377                        list.add(ai);
7378                    }
7379                }
7380            } else {
7381                list = new ArrayList<>(mPackages.size());
7382                for (PackageParser.Package p : mPackages.values()) {
7383                    if (p.mExtras != null) {
7384                        PackageSetting ps = (PackageSetting) p.mExtras;
7385                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7386                            continue;
7387                        }
7388                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7389                                ps.readUserState(userId), userId);
7390                        if (ai != null) {
7391                            rebaseEnabledOverlays(ai, userId);
7392                            ai.packageName = resolveExternalPackageNameLPr(p);
7393                            list.add(ai);
7394                        }
7395                    }
7396                }
7397            }
7398
7399            return new ParceledListSlice<>(list);
7400        }
7401    }
7402
7403    @Override
7404    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7405        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7406            return null;
7407        }
7408
7409        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7410                "getEphemeralApplications");
7411        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7412                true /* requireFullPermission */, false /* checkShell */,
7413                "getEphemeralApplications");
7414        synchronized (mPackages) {
7415            List<InstantAppInfo> instantApps = mInstantAppRegistry
7416                    .getInstantAppsLPr(userId);
7417            if (instantApps != null) {
7418                return new ParceledListSlice<>(instantApps);
7419            }
7420        }
7421        return null;
7422    }
7423
7424    @Override
7425    public boolean isInstantApp(String packageName, int userId) {
7426        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7427                true /* requireFullPermission */, false /* checkShell */,
7428                "isInstantApp");
7429        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7430            return false;
7431        }
7432        int uid = Binder.getCallingUid();
7433        if (Process.isIsolated(uid)) {
7434            uid = mIsolatedOwners.get(uid);
7435        }
7436
7437        synchronized (mPackages) {
7438            final PackageSetting ps = mSettings.mPackages.get(packageName);
7439            PackageParser.Package pkg = mPackages.get(packageName);
7440            final boolean returnAllowed =
7441                    ps != null
7442                    && (isCallerSameApp(packageName, uid)
7443                            || mContext.checkCallingOrSelfPermission(
7444                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7445                                            == PERMISSION_GRANTED
7446                            || mInstantAppRegistry.isInstantAccessGranted(
7447                                    userId, UserHandle.getAppId(uid), ps.appId));
7448            if (returnAllowed) {
7449                return ps.getInstantApp(userId);
7450            }
7451        }
7452        return false;
7453    }
7454
7455    @Override
7456    public byte[] getInstantAppCookie(String packageName, int userId) {
7457        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7458            return null;
7459        }
7460
7461        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7462                true /* requireFullPermission */, false /* checkShell */,
7463                "getInstantAppCookie");
7464        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7465            return null;
7466        }
7467        synchronized (mPackages) {
7468            return mInstantAppRegistry.getInstantAppCookieLPw(
7469                    packageName, userId);
7470        }
7471    }
7472
7473    @Override
7474    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7475        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7476            return true;
7477        }
7478
7479        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7480                true /* requireFullPermission */, true /* checkShell */,
7481                "setInstantAppCookie");
7482        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7483            return false;
7484        }
7485        synchronized (mPackages) {
7486            return mInstantAppRegistry.setInstantAppCookieLPw(
7487                    packageName, cookie, userId);
7488        }
7489    }
7490
7491    @Override
7492    public Bitmap getInstantAppIcon(String packageName, int userId) {
7493        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7494            return null;
7495        }
7496
7497        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7498                "getInstantAppIcon");
7499
7500        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7501                true /* requireFullPermission */, false /* checkShell */,
7502                "getInstantAppIcon");
7503
7504        synchronized (mPackages) {
7505            return mInstantAppRegistry.getInstantAppIconLPw(
7506                    packageName, userId);
7507        }
7508    }
7509
7510    private boolean isCallerSameApp(String packageName, int uid) {
7511        PackageParser.Package pkg = mPackages.get(packageName);
7512        return pkg != null
7513                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7514    }
7515
7516    @Override
7517    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7518        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7519    }
7520
7521    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7522        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7523
7524        // reader
7525        synchronized (mPackages) {
7526            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7527            final int userId = UserHandle.getCallingUserId();
7528            while (i.hasNext()) {
7529                final PackageParser.Package p = i.next();
7530                if (p.applicationInfo == null) continue;
7531
7532                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7533                        && !p.applicationInfo.isDirectBootAware();
7534                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7535                        && p.applicationInfo.isDirectBootAware();
7536
7537                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7538                        && (!mSafeMode || isSystemApp(p))
7539                        && (matchesUnaware || matchesAware)) {
7540                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7541                    if (ps != null) {
7542                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7543                                ps.readUserState(userId), userId);
7544                        if (ai != null) {
7545                            rebaseEnabledOverlays(ai, userId);
7546                            finalList.add(ai);
7547                        }
7548                    }
7549                }
7550            }
7551        }
7552
7553        return finalList;
7554    }
7555
7556    @Override
7557    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7558        if (!sUserManager.exists(userId)) return null;
7559        flags = updateFlagsForComponent(flags, userId, name);
7560        // reader
7561        synchronized (mPackages) {
7562            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7563            PackageSetting ps = provider != null
7564                    ? mSettings.mPackages.get(provider.owner.packageName)
7565                    : null;
7566            return ps != null
7567                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7568                    ? PackageParser.generateProviderInfo(provider, flags,
7569                            ps.readUserState(userId), userId)
7570                    : null;
7571        }
7572    }
7573
7574    /**
7575     * @deprecated
7576     */
7577    @Deprecated
7578    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7579        // reader
7580        synchronized (mPackages) {
7581            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7582                    .entrySet().iterator();
7583            final int userId = UserHandle.getCallingUserId();
7584            while (i.hasNext()) {
7585                Map.Entry<String, PackageParser.Provider> entry = i.next();
7586                PackageParser.Provider p = entry.getValue();
7587                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7588
7589                if (ps != null && p.syncable
7590                        && (!mSafeMode || (p.info.applicationInfo.flags
7591                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7592                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7593                            ps.readUserState(userId), userId);
7594                    if (info != null) {
7595                        outNames.add(entry.getKey());
7596                        outInfo.add(info);
7597                    }
7598                }
7599            }
7600        }
7601    }
7602
7603    @Override
7604    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7605            int uid, int flags, String metaDataKey) {
7606        final int userId = processName != null ? UserHandle.getUserId(uid)
7607                : UserHandle.getCallingUserId();
7608        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7609        flags = updateFlagsForComponent(flags, userId, processName);
7610
7611        ArrayList<ProviderInfo> finalList = null;
7612        // reader
7613        synchronized (mPackages) {
7614            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7615            while (i.hasNext()) {
7616                final PackageParser.Provider p = i.next();
7617                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7618                if (ps != null && p.info.authority != null
7619                        && (processName == null
7620                                || (p.info.processName.equals(processName)
7621                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7622                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7623
7624                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7625                    // parameter.
7626                    if (metaDataKey != null
7627                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7628                        continue;
7629                    }
7630
7631                    if (finalList == null) {
7632                        finalList = new ArrayList<ProviderInfo>(3);
7633                    }
7634                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7635                            ps.readUserState(userId), userId);
7636                    if (info != null) {
7637                        finalList.add(info);
7638                    }
7639                }
7640            }
7641        }
7642
7643        if (finalList != null) {
7644            Collections.sort(finalList, mProviderInitOrderSorter);
7645            return new ParceledListSlice<ProviderInfo>(finalList);
7646        }
7647
7648        return ParceledListSlice.emptyList();
7649    }
7650
7651    @Override
7652    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7653        // reader
7654        synchronized (mPackages) {
7655            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7656            return PackageParser.generateInstrumentationInfo(i, flags);
7657        }
7658    }
7659
7660    @Override
7661    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7662            String targetPackage, int flags) {
7663        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7664    }
7665
7666    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7667            int flags) {
7668        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7669
7670        // reader
7671        synchronized (mPackages) {
7672            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7673            while (i.hasNext()) {
7674                final PackageParser.Instrumentation p = i.next();
7675                if (targetPackage == null
7676                        || targetPackage.equals(p.info.targetPackage)) {
7677                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7678                            flags);
7679                    if (ii != null) {
7680                        finalList.add(ii);
7681                    }
7682                }
7683            }
7684        }
7685
7686        return finalList;
7687    }
7688
7689    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7690        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7691        try {
7692            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7693        } finally {
7694            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7695        }
7696    }
7697
7698    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7699        final File[] files = dir.listFiles();
7700        if (ArrayUtils.isEmpty(files)) {
7701            Log.d(TAG, "No files in app dir " + dir);
7702            return;
7703        }
7704
7705        if (DEBUG_PACKAGE_SCANNING) {
7706            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7707                    + " flags=0x" + Integer.toHexString(parseFlags));
7708        }
7709        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7710                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7711
7712        // Submit files for parsing in parallel
7713        int fileCount = 0;
7714        for (File file : files) {
7715            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7716                    && !PackageInstallerService.isStageName(file.getName());
7717            if (!isPackage) {
7718                // Ignore entries which are not packages
7719                continue;
7720            }
7721            parallelPackageParser.submit(file, parseFlags);
7722            fileCount++;
7723        }
7724
7725        // Process results one by one
7726        for (; fileCount > 0; fileCount--) {
7727            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7728            Throwable throwable = parseResult.throwable;
7729            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7730
7731            if (throwable == null) {
7732                // Static shared libraries have synthetic package names
7733                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7734                    renameStaticSharedLibraryPackage(parseResult.pkg);
7735                }
7736                try {
7737                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7738                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7739                                currentTime, null);
7740                    }
7741                } catch (PackageManagerException e) {
7742                    errorCode = e.error;
7743                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7744                }
7745            } else if (throwable instanceof PackageParser.PackageParserException) {
7746                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7747                        throwable;
7748                errorCode = e.error;
7749                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7750            } else {
7751                throw new IllegalStateException("Unexpected exception occurred while parsing "
7752                        + parseResult.scanFile, throwable);
7753            }
7754
7755            // Delete invalid userdata apps
7756            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7757                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7758                logCriticalInfo(Log.WARN,
7759                        "Deleting invalid package at " + parseResult.scanFile);
7760                removeCodePathLI(parseResult.scanFile);
7761            }
7762        }
7763        parallelPackageParser.close();
7764    }
7765
7766    private static File getSettingsProblemFile() {
7767        File dataDir = Environment.getDataDirectory();
7768        File systemDir = new File(dataDir, "system");
7769        File fname = new File(systemDir, "uiderrors.txt");
7770        return fname;
7771    }
7772
7773    static void reportSettingsProblem(int priority, String msg) {
7774        logCriticalInfo(priority, msg);
7775    }
7776
7777    public static void logCriticalInfo(int priority, String msg) {
7778        Slog.println(priority, TAG, msg);
7779        EventLogTags.writePmCriticalInfo(msg);
7780        try {
7781            File fname = getSettingsProblemFile();
7782            FileOutputStream out = new FileOutputStream(fname, true);
7783            PrintWriter pw = new FastPrintWriter(out);
7784            SimpleDateFormat formatter = new SimpleDateFormat();
7785            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7786            pw.println(dateString + ": " + msg);
7787            pw.close();
7788            FileUtils.setPermissions(
7789                    fname.toString(),
7790                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7791                    -1, -1);
7792        } catch (java.io.IOException e) {
7793        }
7794    }
7795
7796    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7797        if (srcFile.isDirectory()) {
7798            final File baseFile = new File(pkg.baseCodePath);
7799            long maxModifiedTime = baseFile.lastModified();
7800            if (pkg.splitCodePaths != null) {
7801                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7802                    final File splitFile = new File(pkg.splitCodePaths[i]);
7803                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7804                }
7805            }
7806            return maxModifiedTime;
7807        }
7808        return srcFile.lastModified();
7809    }
7810
7811    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7812            final int policyFlags) throws PackageManagerException {
7813        // When upgrading from pre-N MR1, verify the package time stamp using the package
7814        // directory and not the APK file.
7815        final long lastModifiedTime = mIsPreNMR1Upgrade
7816                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7817        if (ps != null
7818                && ps.codePath.equals(srcFile)
7819                && ps.timeStamp == lastModifiedTime
7820                && !isCompatSignatureUpdateNeeded(pkg)
7821                && !isRecoverSignatureUpdateNeeded(pkg)) {
7822            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7823            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7824            ArraySet<PublicKey> signingKs;
7825            synchronized (mPackages) {
7826                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7827            }
7828            if (ps.signatures.mSignatures != null
7829                    && ps.signatures.mSignatures.length != 0
7830                    && signingKs != null) {
7831                // Optimization: reuse the existing cached certificates
7832                // if the package appears to be unchanged.
7833                pkg.mSignatures = ps.signatures.mSignatures;
7834                pkg.mSigningKeys = signingKs;
7835                return;
7836            }
7837
7838            Slog.w(TAG, "PackageSetting for " + ps.name
7839                    + " is missing signatures.  Collecting certs again to recover them.");
7840        } else {
7841            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7842        }
7843
7844        try {
7845            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7846            PackageParser.collectCertificates(pkg, policyFlags);
7847        } catch (PackageParserException e) {
7848            throw PackageManagerException.from(e);
7849        } finally {
7850            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7851        }
7852    }
7853
7854    /**
7855     *  Traces a package scan.
7856     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7857     */
7858    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7859            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7860        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7861        try {
7862            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7863        } finally {
7864            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7865        }
7866    }
7867
7868    /**
7869     *  Scans a package and returns the newly parsed package.
7870     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7871     */
7872    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7873            long currentTime, UserHandle user) throws PackageManagerException {
7874        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7875        PackageParser pp = new PackageParser();
7876        pp.setSeparateProcesses(mSeparateProcesses);
7877        pp.setOnlyCoreApps(mOnlyCore);
7878        pp.setDisplayMetrics(mMetrics);
7879        pp.setCallback(mPackageParserCallback);
7880
7881        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7882            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7883        }
7884
7885        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7886        final PackageParser.Package pkg;
7887        try {
7888            pkg = pp.parsePackage(scanFile, parseFlags);
7889        } catch (PackageParserException e) {
7890            throw PackageManagerException.from(e);
7891        } finally {
7892            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7893        }
7894
7895        // Static shared libraries have synthetic package names
7896        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7897            renameStaticSharedLibraryPackage(pkg);
7898        }
7899
7900        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7901    }
7902
7903    /**
7904     *  Scans a package and returns the newly parsed package.
7905     *  @throws PackageManagerException on a parse error.
7906     */
7907    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7908            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7909            throws PackageManagerException {
7910        // If the package has children and this is the first dive in the function
7911        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7912        // packages (parent and children) would be successfully scanned before the
7913        // actual scan since scanning mutates internal state and we want to atomically
7914        // install the package and its children.
7915        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7916            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7917                scanFlags |= SCAN_CHECK_ONLY;
7918            }
7919        } else {
7920            scanFlags &= ~SCAN_CHECK_ONLY;
7921        }
7922
7923        // Scan the parent
7924        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7925                scanFlags, currentTime, user);
7926
7927        // Scan the children
7928        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7929        for (int i = 0; i < childCount; i++) {
7930            PackageParser.Package childPackage = pkg.childPackages.get(i);
7931            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7932                    currentTime, user);
7933        }
7934
7935
7936        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7937            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7938        }
7939
7940        return scannedPkg;
7941    }
7942
7943    /**
7944     *  Scans a package and returns the newly parsed package.
7945     *  @throws PackageManagerException on a parse error.
7946     */
7947    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7948            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7949            throws PackageManagerException {
7950        PackageSetting ps = null;
7951        PackageSetting updatedPkg;
7952        // reader
7953        synchronized (mPackages) {
7954            // Look to see if we already know about this package.
7955            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7956            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7957                // This package has been renamed to its original name.  Let's
7958                // use that.
7959                ps = mSettings.getPackageLPr(oldName);
7960            }
7961            // If there was no original package, see one for the real package name.
7962            if (ps == null) {
7963                ps = mSettings.getPackageLPr(pkg.packageName);
7964            }
7965            // Check to see if this package could be hiding/updating a system
7966            // package.  Must look for it either under the original or real
7967            // package name depending on our state.
7968            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7969            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7970
7971            // If this is a package we don't know about on the system partition, we
7972            // may need to remove disabled child packages on the system partition
7973            // or may need to not add child packages if the parent apk is updated
7974            // on the data partition and no longer defines this child package.
7975            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7976                // If this is a parent package for an updated system app and this system
7977                // app got an OTA update which no longer defines some of the child packages
7978                // we have to prune them from the disabled system packages.
7979                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7980                if (disabledPs != null) {
7981                    final int scannedChildCount = (pkg.childPackages != null)
7982                            ? pkg.childPackages.size() : 0;
7983                    final int disabledChildCount = disabledPs.childPackageNames != null
7984                            ? disabledPs.childPackageNames.size() : 0;
7985                    for (int i = 0; i < disabledChildCount; i++) {
7986                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7987                        boolean disabledPackageAvailable = false;
7988                        for (int j = 0; j < scannedChildCount; j++) {
7989                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7990                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7991                                disabledPackageAvailable = true;
7992                                break;
7993                            }
7994                         }
7995                         if (!disabledPackageAvailable) {
7996                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7997                         }
7998                    }
7999                }
8000            }
8001        }
8002
8003        boolean updatedPkgBetter = false;
8004        // First check if this is a system package that may involve an update
8005        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8006            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8007            // it needs to drop FLAG_PRIVILEGED.
8008            if (locationIsPrivileged(scanFile)) {
8009                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8010            } else {
8011                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8012            }
8013
8014            if (ps != null && !ps.codePath.equals(scanFile)) {
8015                // The path has changed from what was last scanned...  check the
8016                // version of the new path against what we have stored to determine
8017                // what to do.
8018                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8019                if (pkg.mVersionCode <= ps.versionCode) {
8020                    // The system package has been updated and the code path does not match
8021                    // Ignore entry. Skip it.
8022                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8023                            + " ignored: updated version " + ps.versionCode
8024                            + " better than this " + pkg.mVersionCode);
8025                    if (!updatedPkg.codePath.equals(scanFile)) {
8026                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8027                                + ps.name + " changing from " + updatedPkg.codePathString
8028                                + " to " + scanFile);
8029                        updatedPkg.codePath = scanFile;
8030                        updatedPkg.codePathString = scanFile.toString();
8031                        updatedPkg.resourcePath = scanFile;
8032                        updatedPkg.resourcePathString = scanFile.toString();
8033                    }
8034                    updatedPkg.pkg = pkg;
8035                    updatedPkg.versionCode = pkg.mVersionCode;
8036
8037                    // Update the disabled system child packages to point to the package too.
8038                    final int childCount = updatedPkg.childPackageNames != null
8039                            ? updatedPkg.childPackageNames.size() : 0;
8040                    for (int i = 0; i < childCount; i++) {
8041                        String childPackageName = updatedPkg.childPackageNames.get(i);
8042                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8043                                childPackageName);
8044                        if (updatedChildPkg != null) {
8045                            updatedChildPkg.pkg = pkg;
8046                            updatedChildPkg.versionCode = pkg.mVersionCode;
8047                        }
8048                    }
8049
8050                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8051                            + scanFile + " ignored: updated version " + ps.versionCode
8052                            + " better than this " + pkg.mVersionCode);
8053                } else {
8054                    // The current app on the system partition is better than
8055                    // what we have updated to on the data partition; switch
8056                    // back to the system partition version.
8057                    // At this point, its safely assumed that package installation for
8058                    // apps in system partition will go through. If not there won't be a working
8059                    // version of the app
8060                    // writer
8061                    synchronized (mPackages) {
8062                        // Just remove the loaded entries from package lists.
8063                        mPackages.remove(ps.name);
8064                    }
8065
8066                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8067                            + " reverting from " + ps.codePathString
8068                            + ": new version " + pkg.mVersionCode
8069                            + " better than installed " + ps.versionCode);
8070
8071                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8072                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8073                    synchronized (mInstallLock) {
8074                        args.cleanUpResourcesLI();
8075                    }
8076                    synchronized (mPackages) {
8077                        mSettings.enableSystemPackageLPw(ps.name);
8078                    }
8079                    updatedPkgBetter = true;
8080                }
8081            }
8082        }
8083
8084        if (updatedPkg != null) {
8085            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8086            // initially
8087            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8088
8089            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8090            // flag set initially
8091            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8092                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8093            }
8094        }
8095
8096        // Verify certificates against what was last scanned
8097        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8098
8099        /*
8100         * A new system app appeared, but we already had a non-system one of the
8101         * same name installed earlier.
8102         */
8103        boolean shouldHideSystemApp = false;
8104        if (updatedPkg == null && ps != null
8105                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8106            /*
8107             * Check to make sure the signatures match first. If they don't,
8108             * wipe the installed application and its data.
8109             */
8110            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8111                    != PackageManager.SIGNATURE_MATCH) {
8112                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8113                        + " signatures don't match existing userdata copy; removing");
8114                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8115                        "scanPackageInternalLI")) {
8116                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8117                }
8118                ps = null;
8119            } else {
8120                /*
8121                 * If the newly-added system app is an older version than the
8122                 * already installed version, hide it. It will be scanned later
8123                 * and re-added like an update.
8124                 */
8125                if (pkg.mVersionCode <= ps.versionCode) {
8126                    shouldHideSystemApp = true;
8127                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8128                            + " but new version " + pkg.mVersionCode + " better than installed "
8129                            + ps.versionCode + "; hiding system");
8130                } else {
8131                    /*
8132                     * The newly found system app is a newer version that the
8133                     * one previously installed. Simply remove the
8134                     * already-installed application and replace it with our own
8135                     * while keeping the application data.
8136                     */
8137                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8138                            + " reverting from " + ps.codePathString + ": new version "
8139                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8140                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8141                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8142                    synchronized (mInstallLock) {
8143                        args.cleanUpResourcesLI();
8144                    }
8145                }
8146            }
8147        }
8148
8149        // The apk is forward locked (not public) if its code and resources
8150        // are kept in different files. (except for app in either system or
8151        // vendor path).
8152        // TODO grab this value from PackageSettings
8153        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8154            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8155                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8156            }
8157        }
8158
8159        // TODO: extend to support forward-locked splits
8160        String resourcePath = null;
8161        String baseResourcePath = null;
8162        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8163            if (ps != null && ps.resourcePathString != null) {
8164                resourcePath = ps.resourcePathString;
8165                baseResourcePath = ps.resourcePathString;
8166            } else {
8167                // Should not happen at all. Just log an error.
8168                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8169            }
8170        } else {
8171            resourcePath = pkg.codePath;
8172            baseResourcePath = pkg.baseCodePath;
8173        }
8174
8175        // Set application objects path explicitly.
8176        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8177        pkg.setApplicationInfoCodePath(pkg.codePath);
8178        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8179        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8180        pkg.setApplicationInfoResourcePath(resourcePath);
8181        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8182        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8183
8184        final int userId = ((user == null) ? 0 : user.getIdentifier());
8185        if (ps != null && ps.getInstantApp(userId)) {
8186            scanFlags |= SCAN_AS_INSTANT_APP;
8187        }
8188
8189        // Note that we invoke the following method only if we are about to unpack an application
8190        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8191                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8192
8193        /*
8194         * If the system app should be overridden by a previously installed
8195         * data, hide the system app now and let the /data/app scan pick it up
8196         * again.
8197         */
8198        if (shouldHideSystemApp) {
8199            synchronized (mPackages) {
8200                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8201            }
8202        }
8203
8204        return scannedPkg;
8205    }
8206
8207    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8208        // Derive the new package synthetic package name
8209        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8210                + pkg.staticSharedLibVersion);
8211    }
8212
8213    private static String fixProcessName(String defProcessName,
8214            String processName) {
8215        if (processName == null) {
8216            return defProcessName;
8217        }
8218        return processName;
8219    }
8220
8221    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8222            throws PackageManagerException {
8223        if (pkgSetting.signatures.mSignatures != null) {
8224            // Already existing package. Make sure signatures match
8225            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8226                    == PackageManager.SIGNATURE_MATCH;
8227            if (!match) {
8228                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8229                        == PackageManager.SIGNATURE_MATCH;
8230            }
8231            if (!match) {
8232                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8233                        == PackageManager.SIGNATURE_MATCH;
8234            }
8235            if (!match) {
8236                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8237                        + pkg.packageName + " signatures do not match the "
8238                        + "previously installed version; ignoring!");
8239            }
8240        }
8241
8242        // Check for shared user signatures
8243        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8244            // Already existing package. Make sure signatures match
8245            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8246                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8247            if (!match) {
8248                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8249                        == PackageManager.SIGNATURE_MATCH;
8250            }
8251            if (!match) {
8252                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8253                        == PackageManager.SIGNATURE_MATCH;
8254            }
8255            if (!match) {
8256                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8257                        "Package " + pkg.packageName
8258                        + " has no signatures that match those in shared user "
8259                        + pkgSetting.sharedUser.name + "; ignoring!");
8260            }
8261        }
8262    }
8263
8264    /**
8265     * Enforces that only the system UID or root's UID can call a method exposed
8266     * via Binder.
8267     *
8268     * @param message used as message if SecurityException is thrown
8269     * @throws SecurityException if the caller is not system or root
8270     */
8271    private static final void enforceSystemOrRoot(String message) {
8272        final int uid = Binder.getCallingUid();
8273        if (uid != Process.SYSTEM_UID && uid != 0) {
8274            throw new SecurityException(message);
8275        }
8276    }
8277
8278    @Override
8279    public void performFstrimIfNeeded() {
8280        enforceSystemOrRoot("Only the system can request fstrim");
8281
8282        // Before everything else, see whether we need to fstrim.
8283        try {
8284            IStorageManager sm = PackageHelper.getStorageManager();
8285            if (sm != null) {
8286                boolean doTrim = false;
8287                final long interval = android.provider.Settings.Global.getLong(
8288                        mContext.getContentResolver(),
8289                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8290                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8291                if (interval > 0) {
8292                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8293                    if (timeSinceLast > interval) {
8294                        doTrim = true;
8295                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8296                                + "; running immediately");
8297                    }
8298                }
8299                if (doTrim) {
8300                    final boolean dexOptDialogShown;
8301                    synchronized (mPackages) {
8302                        dexOptDialogShown = mDexOptDialogShown;
8303                    }
8304                    if (!isFirstBoot() && dexOptDialogShown) {
8305                        try {
8306                            ActivityManager.getService().showBootMessage(
8307                                    mContext.getResources().getString(
8308                                            R.string.android_upgrading_fstrim), true);
8309                        } catch (RemoteException e) {
8310                        }
8311                    }
8312                    sm.runMaintenance();
8313                }
8314            } else {
8315                Slog.e(TAG, "storageManager service unavailable!");
8316            }
8317        } catch (RemoteException e) {
8318            // Can't happen; StorageManagerService is local
8319        }
8320    }
8321
8322    @Override
8323    public void updatePackagesIfNeeded() {
8324        enforceSystemOrRoot("Only the system can request package update");
8325
8326        // We need to re-extract after an OTA.
8327        boolean causeUpgrade = isUpgrade();
8328
8329        // First boot or factory reset.
8330        // Note: we also handle devices that are upgrading to N right now as if it is their
8331        //       first boot, as they do not have profile data.
8332        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8333
8334        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8335        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8336
8337        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8338            return;
8339        }
8340
8341        List<PackageParser.Package> pkgs;
8342        synchronized (mPackages) {
8343            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8344        }
8345
8346        final long startTime = System.nanoTime();
8347        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8348                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8349
8350        final int elapsedTimeSeconds =
8351                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8352
8353        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8354        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8355        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8356        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8357        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8358    }
8359
8360    /**
8361     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8362     * containing statistics about the invocation. The array consists of three elements,
8363     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8364     * and {@code numberOfPackagesFailed}.
8365     */
8366    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8367            String compilerFilter) {
8368
8369        int numberOfPackagesVisited = 0;
8370        int numberOfPackagesOptimized = 0;
8371        int numberOfPackagesSkipped = 0;
8372        int numberOfPackagesFailed = 0;
8373        final int numberOfPackagesToDexopt = pkgs.size();
8374
8375        for (PackageParser.Package pkg : pkgs) {
8376            numberOfPackagesVisited++;
8377
8378            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8379                if (DEBUG_DEXOPT) {
8380                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8381                }
8382                numberOfPackagesSkipped++;
8383                continue;
8384            }
8385
8386            if (DEBUG_DEXOPT) {
8387                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8388                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8389            }
8390
8391            if (showDialog) {
8392                try {
8393                    ActivityManager.getService().showBootMessage(
8394                            mContext.getResources().getString(R.string.android_upgrading_apk,
8395                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8396                } catch (RemoteException e) {
8397                }
8398                synchronized (mPackages) {
8399                    mDexOptDialogShown = true;
8400                }
8401            }
8402
8403            // If the OTA updates a system app which was previously preopted to a non-preopted state
8404            // the app might end up being verified at runtime. That's because by default the apps
8405            // are verify-profile but for preopted apps there's no profile.
8406            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8407            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8408            // filter (by default interpret-only).
8409            // Note that at this stage unused apps are already filtered.
8410            if (isSystemApp(pkg) &&
8411                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8412                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8413                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8414            }
8415
8416            // checkProfiles is false to avoid merging profiles during boot which
8417            // might interfere with background compilation (b/28612421).
8418            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8419            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8420            // trade-off worth doing to save boot time work.
8421            int dexOptStatus = performDexOptTraced(pkg.packageName,
8422                    false /* checkProfiles */,
8423                    compilerFilter,
8424                    false /* force */);
8425            switch (dexOptStatus) {
8426                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8427                    numberOfPackagesOptimized++;
8428                    break;
8429                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8430                    numberOfPackagesSkipped++;
8431                    break;
8432                case PackageDexOptimizer.DEX_OPT_FAILED:
8433                    numberOfPackagesFailed++;
8434                    break;
8435                default:
8436                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8437                    break;
8438            }
8439        }
8440
8441        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8442                numberOfPackagesFailed };
8443    }
8444
8445    @Override
8446    public void notifyPackageUse(String packageName, int reason) {
8447        synchronized (mPackages) {
8448            PackageParser.Package p = mPackages.get(packageName);
8449            if (p == null) {
8450                return;
8451            }
8452            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8453        }
8454    }
8455
8456    @Override
8457    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8458        int userId = UserHandle.getCallingUserId();
8459        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8460        if (ai == null) {
8461            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8462                + loadingPackageName + ", user=" + userId);
8463            return;
8464        }
8465        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8466    }
8467
8468    // TODO: this is not used nor needed. Delete it.
8469    @Override
8470    public boolean performDexOptIfNeeded(String packageName) {
8471        int dexOptStatus = performDexOptTraced(packageName,
8472                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8473        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8474    }
8475
8476    @Override
8477    public boolean performDexOpt(String packageName,
8478            boolean checkProfiles, int compileReason, boolean force) {
8479        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8480                getCompilerFilterForReason(compileReason), force);
8481        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8482    }
8483
8484    @Override
8485    public boolean performDexOptMode(String packageName,
8486            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8487        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8488                targetCompilerFilter, force);
8489        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8490    }
8491
8492    private int performDexOptTraced(String packageName,
8493                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8494        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8495        try {
8496            return performDexOptInternal(packageName, checkProfiles,
8497                    targetCompilerFilter, force);
8498        } finally {
8499            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8500        }
8501    }
8502
8503    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8504    // if the package can now be considered up to date for the given filter.
8505    private int performDexOptInternal(String packageName,
8506                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8507        PackageParser.Package p;
8508        synchronized (mPackages) {
8509            p = mPackages.get(packageName);
8510            if (p == null) {
8511                // Package could not be found. Report failure.
8512                return PackageDexOptimizer.DEX_OPT_FAILED;
8513            }
8514            mPackageUsage.maybeWriteAsync(mPackages);
8515            mCompilerStats.maybeWriteAsync();
8516        }
8517        long callingId = Binder.clearCallingIdentity();
8518        try {
8519            synchronized (mInstallLock) {
8520                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8521                        targetCompilerFilter, force);
8522            }
8523        } finally {
8524            Binder.restoreCallingIdentity(callingId);
8525        }
8526    }
8527
8528    public ArraySet<String> getOptimizablePackages() {
8529        ArraySet<String> pkgs = new ArraySet<String>();
8530        synchronized (mPackages) {
8531            for (PackageParser.Package p : mPackages.values()) {
8532                if (PackageDexOptimizer.canOptimizePackage(p)) {
8533                    pkgs.add(p.packageName);
8534                }
8535            }
8536        }
8537        return pkgs;
8538    }
8539
8540    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8541            boolean checkProfiles, String targetCompilerFilter,
8542            boolean force) {
8543        // Select the dex optimizer based on the force parameter.
8544        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8545        //       allocate an object here.
8546        PackageDexOptimizer pdo = force
8547                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8548                : mPackageDexOptimizer;
8549
8550        // Dexopt all dependencies first. Note: we ignore the return value and march on
8551        // on errors.
8552        // Note that we are going to call performDexOpt on those libraries as many times as
8553        // they are referenced in packages. When we do a batch of performDexOpt (for example
8554        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8555        // and the first package that uses the library will dexopt it. The
8556        // others will see that the compiled code for the library is up to date.
8557        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8558        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8559        if (!deps.isEmpty()) {
8560            for (PackageParser.Package depPackage : deps) {
8561                // TODO: Analyze and investigate if we (should) profile libraries.
8562                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8563                        false /* checkProfiles */,
8564                        targetCompilerFilter,
8565                        getOrCreateCompilerPackageStats(depPackage),
8566                        true /* isUsedByOtherApps */);
8567            }
8568        }
8569        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8570                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8571                mDexManager.isUsedByOtherApps(p.packageName));
8572    }
8573
8574    // Performs dexopt on the used secondary dex files belonging to the given package.
8575    // Returns true if all dex files were process successfully (which could mean either dexopt or
8576    // skip). Returns false if any of the files caused errors.
8577    @Override
8578    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8579            boolean force) {
8580        mDexManager.reconcileSecondaryDexFiles(packageName);
8581        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8582    }
8583
8584    public boolean performDexOptSecondary(String packageName, int compileReason,
8585            boolean force) {
8586        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8587    }
8588
8589    /**
8590     * Reconcile the information we have about the secondary dex files belonging to
8591     * {@code packagName} and the actual dex files. For all dex files that were
8592     * deleted, update the internal records and delete the generated oat files.
8593     */
8594    @Override
8595    public void reconcileSecondaryDexFiles(String packageName) {
8596        mDexManager.reconcileSecondaryDexFiles(packageName);
8597    }
8598
8599    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8600    // a reference there.
8601    /*package*/ DexManager getDexManager() {
8602        return mDexManager;
8603    }
8604
8605    /**
8606     * Execute the background dexopt job immediately.
8607     */
8608    @Override
8609    public boolean runBackgroundDexoptJob() {
8610        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8611    }
8612
8613    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8614        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8615                || p.usesStaticLibraries != null) {
8616            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8617            Set<String> collectedNames = new HashSet<>();
8618            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8619
8620            retValue.remove(p);
8621
8622            return retValue;
8623        } else {
8624            return Collections.emptyList();
8625        }
8626    }
8627
8628    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8629            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8630        if (!collectedNames.contains(p.packageName)) {
8631            collectedNames.add(p.packageName);
8632            collected.add(p);
8633
8634            if (p.usesLibraries != null) {
8635                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8636                        null, collected, collectedNames);
8637            }
8638            if (p.usesOptionalLibraries != null) {
8639                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8640                        null, collected, collectedNames);
8641            }
8642            if (p.usesStaticLibraries != null) {
8643                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8644                        p.usesStaticLibrariesVersions, collected, collectedNames);
8645            }
8646        }
8647    }
8648
8649    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8650            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8651        final int libNameCount = libs.size();
8652        for (int i = 0; i < libNameCount; i++) {
8653            String libName = libs.get(i);
8654            int version = (versions != null && versions.length == libNameCount)
8655                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8656            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8657            if (libPkg != null) {
8658                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8659            }
8660        }
8661    }
8662
8663    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8664        synchronized (mPackages) {
8665            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8666            if (libEntry != null) {
8667                return mPackages.get(libEntry.apk);
8668            }
8669            return null;
8670        }
8671    }
8672
8673    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8674        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8675        if (versionedLib == null) {
8676            return null;
8677        }
8678        return versionedLib.get(version);
8679    }
8680
8681    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8682        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8683                pkg.staticSharedLibName);
8684        if (versionedLib == null) {
8685            return null;
8686        }
8687        int previousLibVersion = -1;
8688        final int versionCount = versionedLib.size();
8689        for (int i = 0; i < versionCount; i++) {
8690            final int libVersion = versionedLib.keyAt(i);
8691            if (libVersion < pkg.staticSharedLibVersion) {
8692                previousLibVersion = Math.max(previousLibVersion, libVersion);
8693            }
8694        }
8695        if (previousLibVersion >= 0) {
8696            return versionedLib.get(previousLibVersion);
8697        }
8698        return null;
8699    }
8700
8701    public void shutdown() {
8702        mPackageUsage.writeNow(mPackages);
8703        mCompilerStats.writeNow();
8704    }
8705
8706    @Override
8707    public void dumpProfiles(String packageName) {
8708        PackageParser.Package pkg;
8709        synchronized (mPackages) {
8710            pkg = mPackages.get(packageName);
8711            if (pkg == null) {
8712                throw new IllegalArgumentException("Unknown package: " + packageName);
8713            }
8714        }
8715        /* Only the shell, root, or the app user should be able to dump profiles. */
8716        int callingUid = Binder.getCallingUid();
8717        if (callingUid != Process.SHELL_UID &&
8718            callingUid != Process.ROOT_UID &&
8719            callingUid != pkg.applicationInfo.uid) {
8720            throw new SecurityException("dumpProfiles");
8721        }
8722
8723        synchronized (mInstallLock) {
8724            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8725            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8726            try {
8727                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8728                String codePaths = TextUtils.join(";", allCodePaths);
8729                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8730            } catch (InstallerException e) {
8731                Slog.w(TAG, "Failed to dump profiles", e);
8732            }
8733            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8734        }
8735    }
8736
8737    @Override
8738    public void forceDexOpt(String packageName) {
8739        enforceSystemOrRoot("forceDexOpt");
8740
8741        PackageParser.Package pkg;
8742        synchronized (mPackages) {
8743            pkg = mPackages.get(packageName);
8744            if (pkg == null) {
8745                throw new IllegalArgumentException("Unknown package: " + packageName);
8746            }
8747        }
8748
8749        synchronized (mInstallLock) {
8750            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8751
8752            // Whoever is calling forceDexOpt wants a fully compiled package.
8753            // Don't use profiles since that may cause compilation to be skipped.
8754            final int res = performDexOptInternalWithDependenciesLI(pkg,
8755                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8756                    true /* force */);
8757
8758            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8759            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8760                throw new IllegalStateException("Failed to dexopt: " + res);
8761            }
8762        }
8763    }
8764
8765    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8766        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8767            Slog.w(TAG, "Unable to update from " + oldPkg.name
8768                    + " to " + newPkg.packageName
8769                    + ": old package not in system partition");
8770            return false;
8771        } else if (mPackages.get(oldPkg.name) != null) {
8772            Slog.w(TAG, "Unable to update from " + oldPkg.name
8773                    + " to " + newPkg.packageName
8774                    + ": old package still exists");
8775            return false;
8776        }
8777        return true;
8778    }
8779
8780    void removeCodePathLI(File codePath) {
8781        if (codePath.isDirectory()) {
8782            try {
8783                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8784            } catch (InstallerException e) {
8785                Slog.w(TAG, "Failed to remove code path", e);
8786            }
8787        } else {
8788            codePath.delete();
8789        }
8790    }
8791
8792    private int[] resolveUserIds(int userId) {
8793        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8794    }
8795
8796    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8797        if (pkg == null) {
8798            Slog.wtf(TAG, "Package was null!", new Throwable());
8799            return;
8800        }
8801        clearAppDataLeafLIF(pkg, userId, flags);
8802        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8803        for (int i = 0; i < childCount; i++) {
8804            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8805        }
8806    }
8807
8808    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8809        final PackageSetting ps;
8810        synchronized (mPackages) {
8811            ps = mSettings.mPackages.get(pkg.packageName);
8812        }
8813        for (int realUserId : resolveUserIds(userId)) {
8814            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8815            try {
8816                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8817                        ceDataInode);
8818            } catch (InstallerException e) {
8819                Slog.w(TAG, String.valueOf(e));
8820            }
8821        }
8822    }
8823
8824    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8825        if (pkg == null) {
8826            Slog.wtf(TAG, "Package was null!", new Throwable());
8827            return;
8828        }
8829        destroyAppDataLeafLIF(pkg, userId, flags);
8830        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8831        for (int i = 0; i < childCount; i++) {
8832            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8833        }
8834    }
8835
8836    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8837        final PackageSetting ps;
8838        synchronized (mPackages) {
8839            ps = mSettings.mPackages.get(pkg.packageName);
8840        }
8841        for (int realUserId : resolveUserIds(userId)) {
8842            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8843            try {
8844                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8845                        ceDataInode);
8846            } catch (InstallerException e) {
8847                Slog.w(TAG, String.valueOf(e));
8848            }
8849            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8850        }
8851    }
8852
8853    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8854        if (pkg == null) {
8855            Slog.wtf(TAG, "Package was null!", new Throwable());
8856            return;
8857        }
8858        destroyAppProfilesLeafLIF(pkg);
8859        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8860        for (int i = 0; i < childCount; i++) {
8861            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8862        }
8863    }
8864
8865    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8866        try {
8867            mInstaller.destroyAppProfiles(pkg.packageName);
8868        } catch (InstallerException e) {
8869            Slog.w(TAG, String.valueOf(e));
8870        }
8871    }
8872
8873    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8874        if (pkg == null) {
8875            Slog.wtf(TAG, "Package was null!", new Throwable());
8876            return;
8877        }
8878        clearAppProfilesLeafLIF(pkg);
8879        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8880        for (int i = 0; i < childCount; i++) {
8881            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8882        }
8883    }
8884
8885    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8886        try {
8887            mInstaller.clearAppProfiles(pkg.packageName);
8888        } catch (InstallerException e) {
8889            Slog.w(TAG, String.valueOf(e));
8890        }
8891    }
8892
8893    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8894            long lastUpdateTime) {
8895        // Set parent install/update time
8896        PackageSetting ps = (PackageSetting) pkg.mExtras;
8897        if (ps != null) {
8898            ps.firstInstallTime = firstInstallTime;
8899            ps.lastUpdateTime = lastUpdateTime;
8900        }
8901        // Set children install/update time
8902        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8903        for (int i = 0; i < childCount; i++) {
8904            PackageParser.Package childPkg = pkg.childPackages.get(i);
8905            ps = (PackageSetting) childPkg.mExtras;
8906            if (ps != null) {
8907                ps.firstInstallTime = firstInstallTime;
8908                ps.lastUpdateTime = lastUpdateTime;
8909            }
8910        }
8911    }
8912
8913    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8914            PackageParser.Package changingLib) {
8915        if (file.path != null) {
8916            usesLibraryFiles.add(file.path);
8917            return;
8918        }
8919        PackageParser.Package p = mPackages.get(file.apk);
8920        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8921            // If we are doing this while in the middle of updating a library apk,
8922            // then we need to make sure to use that new apk for determining the
8923            // dependencies here.  (We haven't yet finished committing the new apk
8924            // to the package manager state.)
8925            if (p == null || p.packageName.equals(changingLib.packageName)) {
8926                p = changingLib;
8927            }
8928        }
8929        if (p != null) {
8930            usesLibraryFiles.addAll(p.getAllCodePaths());
8931        }
8932    }
8933
8934    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8935            PackageParser.Package changingLib) throws PackageManagerException {
8936        if (pkg == null) {
8937            return;
8938        }
8939        ArraySet<String> usesLibraryFiles = null;
8940        if (pkg.usesLibraries != null) {
8941            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8942                    null, null, pkg.packageName, changingLib, true, null);
8943        }
8944        if (pkg.usesStaticLibraries != null) {
8945            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8946                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8947                    pkg.packageName, changingLib, true, usesLibraryFiles);
8948        }
8949        if (pkg.usesOptionalLibraries != null) {
8950            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8951                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8952        }
8953        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8954            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8955        } else {
8956            pkg.usesLibraryFiles = null;
8957        }
8958    }
8959
8960    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8961            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8962            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8963            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8964            throws PackageManagerException {
8965        final int libCount = requestedLibraries.size();
8966        for (int i = 0; i < libCount; i++) {
8967            final String libName = requestedLibraries.get(i);
8968            final int libVersion = requiredVersions != null ? requiredVersions[i]
8969                    : SharedLibraryInfo.VERSION_UNDEFINED;
8970            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8971            if (libEntry == null) {
8972                if (required) {
8973                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8974                            "Package " + packageName + " requires unavailable shared library "
8975                                    + libName + "; failing!");
8976                } else {
8977                    Slog.w(TAG, "Package " + packageName
8978                            + " desires unavailable shared library "
8979                            + libName + "; ignoring!");
8980                }
8981            } else {
8982                if (requiredVersions != null && requiredCertDigests != null) {
8983                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8984                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8985                            "Package " + packageName + " requires unavailable static shared"
8986                                    + " library " + libName + " version "
8987                                    + libEntry.info.getVersion() + "; failing!");
8988                    }
8989
8990                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8991                    if (libPkg == null) {
8992                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8993                                "Package " + packageName + " requires unavailable static shared"
8994                                        + " library; failing!");
8995                    }
8996
8997                    String expectedCertDigest = requiredCertDigests[i];
8998                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8999                                libPkg.mSignatures[0]);
9000                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9001                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9002                                "Package " + packageName + " requires differently signed" +
9003                                        " static shared library; failing!");
9004                    }
9005                }
9006
9007                if (outUsedLibraries == null) {
9008                    outUsedLibraries = new ArraySet<>();
9009                }
9010                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9011            }
9012        }
9013        return outUsedLibraries;
9014    }
9015
9016    private static boolean hasString(List<String> list, List<String> which) {
9017        if (list == null) {
9018            return false;
9019        }
9020        for (int i=list.size()-1; i>=0; i--) {
9021            for (int j=which.size()-1; j>=0; j--) {
9022                if (which.get(j).equals(list.get(i))) {
9023                    return true;
9024                }
9025            }
9026        }
9027        return false;
9028    }
9029
9030    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9031            PackageParser.Package changingPkg) {
9032        ArrayList<PackageParser.Package> res = null;
9033        for (PackageParser.Package pkg : mPackages.values()) {
9034            if (changingPkg != null
9035                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9036                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9037                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9038                            changingPkg.staticSharedLibName)) {
9039                return null;
9040            }
9041            if (res == null) {
9042                res = new ArrayList<>();
9043            }
9044            res.add(pkg);
9045            try {
9046                updateSharedLibrariesLPr(pkg, changingPkg);
9047            } catch (PackageManagerException e) {
9048                // If a system app update or an app and a required lib missing we
9049                // delete the package and for updated system apps keep the data as
9050                // it is better for the user to reinstall than to be in an limbo
9051                // state. Also libs disappearing under an app should never happen
9052                // - just in case.
9053                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9054                    final int flags = pkg.isUpdatedSystemApp()
9055                            ? PackageManager.DELETE_KEEP_DATA : 0;
9056                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9057                            flags , null, true, null);
9058                }
9059                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9060            }
9061        }
9062        return res;
9063    }
9064
9065    /**
9066     * Derive the value of the {@code cpuAbiOverride} based on the provided
9067     * value and an optional stored value from the package settings.
9068     */
9069    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9070        String cpuAbiOverride = null;
9071
9072        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9073            cpuAbiOverride = null;
9074        } else if (abiOverride != null) {
9075            cpuAbiOverride = abiOverride;
9076        } else if (settings != null) {
9077            cpuAbiOverride = settings.cpuAbiOverrideString;
9078        }
9079
9080        return cpuAbiOverride;
9081    }
9082
9083    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9084            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9085                    throws PackageManagerException {
9086        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9087        // If the package has children and this is the first dive in the function
9088        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9089        // whether all packages (parent and children) would be successfully scanned
9090        // before the actual scan since scanning mutates internal state and we want
9091        // to atomically install the package and its children.
9092        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9093            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9094                scanFlags |= SCAN_CHECK_ONLY;
9095            }
9096        } else {
9097            scanFlags &= ~SCAN_CHECK_ONLY;
9098        }
9099
9100        final PackageParser.Package scannedPkg;
9101        try {
9102            // Scan the parent
9103            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9104            // Scan the children
9105            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9106            for (int i = 0; i < childCount; i++) {
9107                PackageParser.Package childPkg = pkg.childPackages.get(i);
9108                scanPackageLI(childPkg, policyFlags,
9109                        scanFlags, currentTime, user);
9110            }
9111        } finally {
9112            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9113        }
9114
9115        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9116            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9117        }
9118
9119        return scannedPkg;
9120    }
9121
9122    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9123            int scanFlags, long currentTime, @Nullable UserHandle user)
9124                    throws PackageManagerException {
9125        boolean success = false;
9126        try {
9127            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9128                    currentTime, user);
9129            success = true;
9130            return res;
9131        } finally {
9132            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9133                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9134                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9135                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9136                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9137            }
9138        }
9139    }
9140
9141    /**
9142     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9143     */
9144    private static boolean apkHasCode(String fileName) {
9145        StrictJarFile jarFile = null;
9146        try {
9147            jarFile = new StrictJarFile(fileName,
9148                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9149            return jarFile.findEntry("classes.dex") != null;
9150        } catch (IOException ignore) {
9151        } finally {
9152            try {
9153                if (jarFile != null) {
9154                    jarFile.close();
9155                }
9156            } catch (IOException ignore) {}
9157        }
9158        return false;
9159    }
9160
9161    /**
9162     * Enforces code policy for the package. This ensures that if an APK has
9163     * declared hasCode="true" in its manifest that the APK actually contains
9164     * code.
9165     *
9166     * @throws PackageManagerException If bytecode could not be found when it should exist
9167     */
9168    private static void assertCodePolicy(PackageParser.Package pkg)
9169            throws PackageManagerException {
9170        final boolean shouldHaveCode =
9171                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9172        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9173            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9174                    "Package " + pkg.baseCodePath + " code is missing");
9175        }
9176
9177        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9178            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9179                final boolean splitShouldHaveCode =
9180                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9181                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9182                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9183                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9184                }
9185            }
9186        }
9187    }
9188
9189    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9190            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9191                    throws PackageManagerException {
9192        if (DEBUG_PACKAGE_SCANNING) {
9193            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9194                Log.d(TAG, "Scanning package " + pkg.packageName);
9195        }
9196
9197        applyPolicy(pkg, policyFlags);
9198
9199        assertPackageIsValid(pkg, policyFlags, scanFlags);
9200
9201        // Initialize package source and resource directories
9202        final File scanFile = new File(pkg.codePath);
9203        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9204        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9205
9206        SharedUserSetting suid = null;
9207        PackageSetting pkgSetting = null;
9208
9209        // Getting the package setting may have a side-effect, so if we
9210        // are only checking if scan would succeed, stash a copy of the
9211        // old setting to restore at the end.
9212        PackageSetting nonMutatedPs = null;
9213
9214        // We keep references to the derived CPU Abis from settings in oder to reuse
9215        // them in the case where we're not upgrading or booting for the first time.
9216        String primaryCpuAbiFromSettings = null;
9217        String secondaryCpuAbiFromSettings = null;
9218
9219        // writer
9220        synchronized (mPackages) {
9221            if (pkg.mSharedUserId != null) {
9222                // SIDE EFFECTS; may potentially allocate a new shared user
9223                suid = mSettings.getSharedUserLPw(
9224                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9225                if (DEBUG_PACKAGE_SCANNING) {
9226                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9227                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9228                                + "): packages=" + suid.packages);
9229                }
9230            }
9231
9232            // Check if we are renaming from an original package name.
9233            PackageSetting origPackage = null;
9234            String realName = null;
9235            if (pkg.mOriginalPackages != null) {
9236                // This package may need to be renamed to a previously
9237                // installed name.  Let's check on that...
9238                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9239                if (pkg.mOriginalPackages.contains(renamed)) {
9240                    // This package had originally been installed as the
9241                    // original name, and we have already taken care of
9242                    // transitioning to the new one.  Just update the new
9243                    // one to continue using the old name.
9244                    realName = pkg.mRealPackage;
9245                    if (!pkg.packageName.equals(renamed)) {
9246                        // Callers into this function may have already taken
9247                        // care of renaming the package; only do it here if
9248                        // it is not already done.
9249                        pkg.setPackageName(renamed);
9250                    }
9251                } else {
9252                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9253                        if ((origPackage = mSettings.getPackageLPr(
9254                                pkg.mOriginalPackages.get(i))) != null) {
9255                            // We do have the package already installed under its
9256                            // original name...  should we use it?
9257                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9258                                // New package is not compatible with original.
9259                                origPackage = null;
9260                                continue;
9261                            } else if (origPackage.sharedUser != null) {
9262                                // Make sure uid is compatible between packages.
9263                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9264                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9265                                            + " to " + pkg.packageName + ": old uid "
9266                                            + origPackage.sharedUser.name
9267                                            + " differs from " + pkg.mSharedUserId);
9268                                    origPackage = null;
9269                                    continue;
9270                                }
9271                                // TODO: Add case when shared user id is added [b/28144775]
9272                            } else {
9273                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9274                                        + pkg.packageName + " to old name " + origPackage.name);
9275                            }
9276                            break;
9277                        }
9278                    }
9279                }
9280            }
9281
9282            if (mTransferedPackages.contains(pkg.packageName)) {
9283                Slog.w(TAG, "Package " + pkg.packageName
9284                        + " was transferred to another, but its .apk remains");
9285            }
9286
9287            // See comments in nonMutatedPs declaration
9288            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9289                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9290                if (foundPs != null) {
9291                    nonMutatedPs = new PackageSetting(foundPs);
9292                }
9293            }
9294
9295            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9296                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9297                if (foundPs != null) {
9298                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9299                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9300                }
9301            }
9302
9303            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9304            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9305                PackageManagerService.reportSettingsProblem(Log.WARN,
9306                        "Package " + pkg.packageName + " shared user changed from "
9307                                + (pkgSetting.sharedUser != null
9308                                        ? pkgSetting.sharedUser.name : "<nothing>")
9309                                + " to "
9310                                + (suid != null ? suid.name : "<nothing>")
9311                                + "; replacing with new");
9312                pkgSetting = null;
9313            }
9314            final PackageSetting oldPkgSetting =
9315                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9316            final PackageSetting disabledPkgSetting =
9317                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9318
9319            String[] usesStaticLibraries = null;
9320            if (pkg.usesStaticLibraries != null) {
9321                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9322                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9323            }
9324
9325            if (pkgSetting == null) {
9326                final String parentPackageName = (pkg.parentPackage != null)
9327                        ? pkg.parentPackage.packageName : null;
9328                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9329                // REMOVE SharedUserSetting from method; update in a separate call
9330                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9331                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9332                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9333                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9334                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9335                        true /*allowInstall*/, instantApp, parentPackageName,
9336                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9337                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9338                // SIDE EFFECTS; updates system state; move elsewhere
9339                if (origPackage != null) {
9340                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9341                }
9342                mSettings.addUserToSettingLPw(pkgSetting);
9343            } else {
9344                // REMOVE SharedUserSetting from method; update in a separate call.
9345                //
9346                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9347                // secondaryCpuAbi are not known at this point so we always update them
9348                // to null here, only to reset them at a later point.
9349                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9350                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9351                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9352                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9353                        UserManagerService.getInstance(), usesStaticLibraries,
9354                        pkg.usesStaticLibrariesVersions);
9355            }
9356            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9357            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9358
9359            // SIDE EFFECTS; modifies system state; move elsewhere
9360            if (pkgSetting.origPackage != null) {
9361                // If we are first transitioning from an original package,
9362                // fix up the new package's name now.  We need to do this after
9363                // looking up the package under its new name, so getPackageLP
9364                // can take care of fiddling things correctly.
9365                pkg.setPackageName(origPackage.name);
9366
9367                // File a report about this.
9368                String msg = "New package " + pkgSetting.realName
9369                        + " renamed to replace old package " + pkgSetting.name;
9370                reportSettingsProblem(Log.WARN, msg);
9371
9372                // Make a note of it.
9373                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9374                    mTransferedPackages.add(origPackage.name);
9375                }
9376
9377                // No longer need to retain this.
9378                pkgSetting.origPackage = null;
9379            }
9380
9381            // SIDE EFFECTS; modifies system state; move elsewhere
9382            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9383                // Make a note of it.
9384                mTransferedPackages.add(pkg.packageName);
9385            }
9386
9387            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9388                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9389            }
9390
9391            if ((scanFlags & SCAN_BOOTING) == 0
9392                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9393                // Check all shared libraries and map to their actual file path.
9394                // We only do this here for apps not on a system dir, because those
9395                // are the only ones that can fail an install due to this.  We
9396                // will take care of the system apps by updating all of their
9397                // library paths after the scan is done. Also during the initial
9398                // scan don't update any libs as we do this wholesale after all
9399                // apps are scanned to avoid dependency based scanning.
9400                updateSharedLibrariesLPr(pkg, null);
9401            }
9402
9403            if (mFoundPolicyFile) {
9404                SELinuxMMAC.assignSeInfoValue(pkg);
9405            }
9406            pkg.applicationInfo.uid = pkgSetting.appId;
9407            pkg.mExtras = pkgSetting;
9408
9409
9410            // Static shared libs have same package with different versions where
9411            // we internally use a synthetic package name to allow multiple versions
9412            // of the same package, therefore we need to compare signatures against
9413            // the package setting for the latest library version.
9414            PackageSetting signatureCheckPs = pkgSetting;
9415            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9416                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9417                if (libraryEntry != null) {
9418                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9419                }
9420            }
9421
9422            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9423                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9424                    // We just determined the app is signed correctly, so bring
9425                    // over the latest parsed certs.
9426                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9427                } else {
9428                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9429                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9430                                "Package " + pkg.packageName + " upgrade keys do not match the "
9431                                + "previously installed version");
9432                    } else {
9433                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9434                        String msg = "System package " + pkg.packageName
9435                                + " signature changed; retaining data.";
9436                        reportSettingsProblem(Log.WARN, msg);
9437                    }
9438                }
9439            } else {
9440                try {
9441                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9442                    verifySignaturesLP(signatureCheckPs, pkg);
9443                    // We just determined the app is signed correctly, so bring
9444                    // over the latest parsed certs.
9445                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9446                } catch (PackageManagerException e) {
9447                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9448                        throw e;
9449                    }
9450                    // The signature has changed, but this package is in the system
9451                    // image...  let's recover!
9452                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9453                    // However...  if this package is part of a shared user, but it
9454                    // doesn't match the signature of the shared user, let's fail.
9455                    // What this means is that you can't change the signatures
9456                    // associated with an overall shared user, which doesn't seem all
9457                    // that unreasonable.
9458                    if (signatureCheckPs.sharedUser != null) {
9459                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9460                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9461                            throw new PackageManagerException(
9462                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9463                                    "Signature mismatch for shared user: "
9464                                            + pkgSetting.sharedUser);
9465                        }
9466                    }
9467                    // File a report about this.
9468                    String msg = "System package " + pkg.packageName
9469                            + " signature changed; retaining data.";
9470                    reportSettingsProblem(Log.WARN, msg);
9471                }
9472            }
9473
9474            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9475                // This package wants to adopt ownership of permissions from
9476                // another package.
9477                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9478                    final String origName = pkg.mAdoptPermissions.get(i);
9479                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9480                    if (orig != null) {
9481                        if (verifyPackageUpdateLPr(orig, pkg)) {
9482                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9483                                    + pkg.packageName);
9484                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9485                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9486                        }
9487                    }
9488                }
9489            }
9490        }
9491
9492        pkg.applicationInfo.processName = fixProcessName(
9493                pkg.applicationInfo.packageName,
9494                pkg.applicationInfo.processName);
9495
9496        if (pkg != mPlatformPackage) {
9497            // Get all of our default paths setup
9498            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9499        }
9500
9501        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9502
9503        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9504            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9505                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9506                derivePackageAbi(
9507                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9508                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9509
9510                // Some system apps still use directory structure for native libraries
9511                // in which case we might end up not detecting abi solely based on apk
9512                // structure. Try to detect abi based on directory structure.
9513                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9514                        pkg.applicationInfo.primaryCpuAbi == null) {
9515                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9516                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9517                }
9518            } else {
9519                // This is not a first boot or an upgrade, don't bother deriving the
9520                // ABI during the scan. Instead, trust the value that was stored in the
9521                // package setting.
9522                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9523                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9524
9525                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9526
9527                if (DEBUG_ABI_SELECTION) {
9528                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9529                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9530                        pkg.applicationInfo.secondaryCpuAbi);
9531                }
9532            }
9533        } else {
9534            if ((scanFlags & SCAN_MOVE) != 0) {
9535                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9536                // but we already have this packages package info in the PackageSetting. We just
9537                // use that and derive the native library path based on the new codepath.
9538                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9539                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9540            }
9541
9542            // Set native library paths again. For moves, the path will be updated based on the
9543            // ABIs we've determined above. For non-moves, the path will be updated based on the
9544            // ABIs we determined during compilation, but the path will depend on the final
9545            // package path (after the rename away from the stage path).
9546            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9547        }
9548
9549        // This is a special case for the "system" package, where the ABI is
9550        // dictated by the zygote configuration (and init.rc). We should keep track
9551        // of this ABI so that we can deal with "normal" applications that run under
9552        // the same UID correctly.
9553        if (mPlatformPackage == pkg) {
9554            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9555                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9556        }
9557
9558        // If there's a mismatch between the abi-override in the package setting
9559        // and the abiOverride specified for the install. Warn about this because we
9560        // would've already compiled the app without taking the package setting into
9561        // account.
9562        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9563            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9564                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9565                        " for package " + pkg.packageName);
9566            }
9567        }
9568
9569        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9570        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9571        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9572
9573        // Copy the derived override back to the parsed package, so that we can
9574        // update the package settings accordingly.
9575        pkg.cpuAbiOverride = cpuAbiOverride;
9576
9577        if (DEBUG_ABI_SELECTION) {
9578            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9579                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9580                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9581        }
9582
9583        // Push the derived path down into PackageSettings so we know what to
9584        // clean up at uninstall time.
9585        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9586
9587        if (DEBUG_ABI_SELECTION) {
9588            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9589                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9590                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9591        }
9592
9593        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9594        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9595            // We don't do this here during boot because we can do it all
9596            // at once after scanning all existing packages.
9597            //
9598            // We also do this *before* we perform dexopt on this package, so that
9599            // we can avoid redundant dexopts, and also to make sure we've got the
9600            // code and package path correct.
9601            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9602        }
9603
9604        if (mFactoryTest && pkg.requestedPermissions.contains(
9605                android.Manifest.permission.FACTORY_TEST)) {
9606            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9607        }
9608
9609        if (isSystemApp(pkg)) {
9610            pkgSetting.isOrphaned = true;
9611        }
9612
9613        // Take care of first install / last update times.
9614        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9615        if (currentTime != 0) {
9616            if (pkgSetting.firstInstallTime == 0) {
9617                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9618            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9619                pkgSetting.lastUpdateTime = currentTime;
9620            }
9621        } else if (pkgSetting.firstInstallTime == 0) {
9622            // We need *something*.  Take time time stamp of the file.
9623            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9624        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9625            if (scanFileTime != pkgSetting.timeStamp) {
9626                // A package on the system image has changed; consider this
9627                // to be an update.
9628                pkgSetting.lastUpdateTime = scanFileTime;
9629            }
9630        }
9631        pkgSetting.setTimeStamp(scanFileTime);
9632
9633        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9634            if (nonMutatedPs != null) {
9635                synchronized (mPackages) {
9636                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9637                }
9638            }
9639        } else {
9640            final int userId = user == null ? 0 : user.getIdentifier();
9641            // Modify state for the given package setting
9642            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9643                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9644            if (pkgSetting.getInstantApp(userId)) {
9645                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9646            }
9647        }
9648        return pkg;
9649    }
9650
9651    /**
9652     * Applies policy to the parsed package based upon the given policy flags.
9653     * Ensures the package is in a good state.
9654     * <p>
9655     * Implementation detail: This method must NOT have any side effect. It would
9656     * ideally be static, but, it requires locks to read system state.
9657     */
9658    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9659        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9660            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9661            if (pkg.applicationInfo.isDirectBootAware()) {
9662                // we're direct boot aware; set for all components
9663                for (PackageParser.Service s : pkg.services) {
9664                    s.info.encryptionAware = s.info.directBootAware = true;
9665                }
9666                for (PackageParser.Provider p : pkg.providers) {
9667                    p.info.encryptionAware = p.info.directBootAware = true;
9668                }
9669                for (PackageParser.Activity a : pkg.activities) {
9670                    a.info.encryptionAware = a.info.directBootAware = true;
9671                }
9672                for (PackageParser.Activity r : pkg.receivers) {
9673                    r.info.encryptionAware = r.info.directBootAware = true;
9674                }
9675            }
9676        } else {
9677            // Only allow system apps to be flagged as core apps.
9678            pkg.coreApp = false;
9679            // clear flags not applicable to regular apps
9680            pkg.applicationInfo.privateFlags &=
9681                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9682            pkg.applicationInfo.privateFlags &=
9683                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9684        }
9685        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9686
9687        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9688            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9689        }
9690
9691        if (!isSystemApp(pkg)) {
9692            // Only system apps can use these features.
9693            pkg.mOriginalPackages = null;
9694            pkg.mRealPackage = null;
9695            pkg.mAdoptPermissions = null;
9696        }
9697    }
9698
9699    /**
9700     * Asserts the parsed package is valid according to the given policy. If the
9701     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9702     * <p>
9703     * Implementation detail: This method must NOT have any side effects. It would
9704     * ideally be static, but, it requires locks to read system state.
9705     *
9706     * @throws PackageManagerException If the package fails any of the validation checks
9707     */
9708    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9709            throws PackageManagerException {
9710        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9711            assertCodePolicy(pkg);
9712        }
9713
9714        if (pkg.applicationInfo.getCodePath() == null ||
9715                pkg.applicationInfo.getResourcePath() == null) {
9716            // Bail out. The resource and code paths haven't been set.
9717            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9718                    "Code and resource paths haven't been set correctly");
9719        }
9720
9721        // Make sure we're not adding any bogus keyset info
9722        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9723        ksms.assertScannedPackageValid(pkg);
9724
9725        synchronized (mPackages) {
9726            // The special "android" package can only be defined once
9727            if (pkg.packageName.equals("android")) {
9728                if (mAndroidApplication != null) {
9729                    Slog.w(TAG, "*************************************************");
9730                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9731                    Slog.w(TAG, " codePath=" + pkg.codePath);
9732                    Slog.w(TAG, "*************************************************");
9733                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9734                            "Core android package being redefined.  Skipping.");
9735                }
9736            }
9737
9738            // A package name must be unique; don't allow duplicates
9739            if (mPackages.containsKey(pkg.packageName)) {
9740                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9741                        "Application package " + pkg.packageName
9742                        + " already installed.  Skipping duplicate.");
9743            }
9744
9745            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9746                // Static libs have a synthetic package name containing the version
9747                // but we still want the base name to be unique.
9748                if (mPackages.containsKey(pkg.manifestPackageName)) {
9749                    throw new PackageManagerException(
9750                            "Duplicate static shared lib provider package");
9751                }
9752
9753                // Static shared libraries should have at least O target SDK
9754                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9755                    throw new PackageManagerException(
9756                            "Packages declaring static-shared libs must target O SDK or higher");
9757                }
9758
9759                // Package declaring static a shared lib cannot be instant apps
9760                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9761                    throw new PackageManagerException(
9762                            "Packages declaring static-shared libs cannot be instant apps");
9763                }
9764
9765                // Package declaring static a shared lib cannot be renamed since the package
9766                // name is synthetic and apps can't code around package manager internals.
9767                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9768                    throw new PackageManagerException(
9769                            "Packages declaring static-shared libs cannot be renamed");
9770                }
9771
9772                // Package declaring static a shared lib cannot declare child packages
9773                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9774                    throw new PackageManagerException(
9775                            "Packages declaring static-shared libs cannot have child packages");
9776                }
9777
9778                // Package declaring static a shared lib cannot declare dynamic libs
9779                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9780                    throw new PackageManagerException(
9781                            "Packages declaring static-shared libs cannot declare dynamic libs");
9782                }
9783
9784                // Package declaring static a shared lib cannot declare shared users
9785                if (pkg.mSharedUserId != null) {
9786                    throw new PackageManagerException(
9787                            "Packages declaring static-shared libs cannot declare shared users");
9788                }
9789
9790                // Static shared libs cannot declare activities
9791                if (!pkg.activities.isEmpty()) {
9792                    throw new PackageManagerException(
9793                            "Static shared libs cannot declare activities");
9794                }
9795
9796                // Static shared libs cannot declare services
9797                if (!pkg.services.isEmpty()) {
9798                    throw new PackageManagerException(
9799                            "Static shared libs cannot declare services");
9800                }
9801
9802                // Static shared libs cannot declare providers
9803                if (!pkg.providers.isEmpty()) {
9804                    throw new PackageManagerException(
9805                            "Static shared libs cannot declare content providers");
9806                }
9807
9808                // Static shared libs cannot declare receivers
9809                if (!pkg.receivers.isEmpty()) {
9810                    throw new PackageManagerException(
9811                            "Static shared libs cannot declare broadcast receivers");
9812                }
9813
9814                // Static shared libs cannot declare permission groups
9815                if (!pkg.permissionGroups.isEmpty()) {
9816                    throw new PackageManagerException(
9817                            "Static shared libs cannot declare permission groups");
9818                }
9819
9820                // Static shared libs cannot declare permissions
9821                if (!pkg.permissions.isEmpty()) {
9822                    throw new PackageManagerException(
9823                            "Static shared libs cannot declare permissions");
9824                }
9825
9826                // Static shared libs cannot declare protected broadcasts
9827                if (pkg.protectedBroadcasts != null) {
9828                    throw new PackageManagerException(
9829                            "Static shared libs cannot declare protected broadcasts");
9830                }
9831
9832                // Static shared libs cannot be overlay targets
9833                if (pkg.mOverlayTarget != null) {
9834                    throw new PackageManagerException(
9835                            "Static shared libs cannot be overlay targets");
9836                }
9837
9838                // The version codes must be ordered as lib versions
9839                int minVersionCode = Integer.MIN_VALUE;
9840                int maxVersionCode = Integer.MAX_VALUE;
9841
9842                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9843                        pkg.staticSharedLibName);
9844                if (versionedLib != null) {
9845                    final int versionCount = versionedLib.size();
9846                    for (int i = 0; i < versionCount; i++) {
9847                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9848                        // TODO: We will change version code to long, so in the new API it is long
9849                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9850                                .getVersionCode();
9851                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9852                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9853                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9854                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9855                        } else {
9856                            minVersionCode = maxVersionCode = libVersionCode;
9857                            break;
9858                        }
9859                    }
9860                }
9861                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9862                    throw new PackageManagerException("Static shared"
9863                            + " lib version codes must be ordered as lib versions");
9864                }
9865            }
9866
9867            // Only privileged apps and updated privileged apps can add child packages.
9868            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9869                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9870                    throw new PackageManagerException("Only privileged apps can add child "
9871                            + "packages. Ignoring package " + pkg.packageName);
9872                }
9873                final int childCount = pkg.childPackages.size();
9874                for (int i = 0; i < childCount; i++) {
9875                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9876                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9877                            childPkg.packageName)) {
9878                        throw new PackageManagerException("Can't override child of "
9879                                + "another disabled app. Ignoring package " + pkg.packageName);
9880                    }
9881                }
9882            }
9883
9884            // If we're only installing presumed-existing packages, require that the
9885            // scanned APK is both already known and at the path previously established
9886            // for it.  Previously unknown packages we pick up normally, but if we have an
9887            // a priori expectation about this package's install presence, enforce it.
9888            // With a singular exception for new system packages. When an OTA contains
9889            // a new system package, we allow the codepath to change from a system location
9890            // to the user-installed location. If we don't allow this change, any newer,
9891            // user-installed version of the application will be ignored.
9892            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9893                if (mExpectingBetter.containsKey(pkg.packageName)) {
9894                    logCriticalInfo(Log.WARN,
9895                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9896                } else {
9897                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9898                    if (known != null) {
9899                        if (DEBUG_PACKAGE_SCANNING) {
9900                            Log.d(TAG, "Examining " + pkg.codePath
9901                                    + " and requiring known paths " + known.codePathString
9902                                    + " & " + known.resourcePathString);
9903                        }
9904                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9905                                || !pkg.applicationInfo.getResourcePath().equals(
9906                                        known.resourcePathString)) {
9907                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9908                                    "Application package " + pkg.packageName
9909                                    + " found at " + pkg.applicationInfo.getCodePath()
9910                                    + " but expected at " + known.codePathString
9911                                    + "; ignoring.");
9912                        }
9913                    }
9914                }
9915            }
9916
9917            // Verify that this new package doesn't have any content providers
9918            // that conflict with existing packages.  Only do this if the
9919            // package isn't already installed, since we don't want to break
9920            // things that are installed.
9921            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9922                final int N = pkg.providers.size();
9923                int i;
9924                for (i=0; i<N; i++) {
9925                    PackageParser.Provider p = pkg.providers.get(i);
9926                    if (p.info.authority != null) {
9927                        String names[] = p.info.authority.split(";");
9928                        for (int j = 0; j < names.length; j++) {
9929                            if (mProvidersByAuthority.containsKey(names[j])) {
9930                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9931                                final String otherPackageName =
9932                                        ((other != null && other.getComponentName() != null) ?
9933                                                other.getComponentName().getPackageName() : "?");
9934                                throw new PackageManagerException(
9935                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9936                                        "Can't install because provider name " + names[j]
9937                                                + " (in package " + pkg.applicationInfo.packageName
9938                                                + ") is already used by " + otherPackageName);
9939                            }
9940                        }
9941                    }
9942                }
9943            }
9944        }
9945    }
9946
9947    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9948            int type, String declaringPackageName, int declaringVersionCode) {
9949        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9950        if (versionedLib == null) {
9951            versionedLib = new SparseArray<>();
9952            mSharedLibraries.put(name, versionedLib);
9953            if (type == SharedLibraryInfo.TYPE_STATIC) {
9954                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9955            }
9956        } else if (versionedLib.indexOfKey(version) >= 0) {
9957            return false;
9958        }
9959        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9960                version, type, declaringPackageName, declaringVersionCode);
9961        versionedLib.put(version, libEntry);
9962        return true;
9963    }
9964
9965    private boolean removeSharedLibraryLPw(String name, int version) {
9966        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9967        if (versionedLib == null) {
9968            return false;
9969        }
9970        final int libIdx = versionedLib.indexOfKey(version);
9971        if (libIdx < 0) {
9972            return false;
9973        }
9974        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9975        versionedLib.remove(version);
9976        if (versionedLib.size() <= 0) {
9977            mSharedLibraries.remove(name);
9978            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9979                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9980                        .getPackageName());
9981            }
9982        }
9983        return true;
9984    }
9985
9986    /**
9987     * Adds a scanned package to the system. When this method is finished, the package will
9988     * be available for query, resolution, etc...
9989     */
9990    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9991            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9992        final String pkgName = pkg.packageName;
9993        if (mCustomResolverComponentName != null &&
9994                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9995            setUpCustomResolverActivity(pkg);
9996        }
9997
9998        if (pkg.packageName.equals("android")) {
9999            synchronized (mPackages) {
10000                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10001                    // Set up information for our fall-back user intent resolution activity.
10002                    mPlatformPackage = pkg;
10003                    pkg.mVersionCode = mSdkVersion;
10004                    mAndroidApplication = pkg.applicationInfo;
10005                    if (!mResolverReplaced) {
10006                        mResolveActivity.applicationInfo = mAndroidApplication;
10007                        mResolveActivity.name = ResolverActivity.class.getName();
10008                        mResolveActivity.packageName = mAndroidApplication.packageName;
10009                        mResolveActivity.processName = "system:ui";
10010                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10011                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10012                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10013                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10014                        mResolveActivity.exported = true;
10015                        mResolveActivity.enabled = true;
10016                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10017                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10018                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10019                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10020                                | ActivityInfo.CONFIG_ORIENTATION
10021                                | ActivityInfo.CONFIG_KEYBOARD
10022                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10023                        mResolveInfo.activityInfo = mResolveActivity;
10024                        mResolveInfo.priority = 0;
10025                        mResolveInfo.preferredOrder = 0;
10026                        mResolveInfo.match = 0;
10027                        mResolveComponentName = new ComponentName(
10028                                mAndroidApplication.packageName, mResolveActivity.name);
10029                    }
10030                }
10031            }
10032        }
10033
10034        ArrayList<PackageParser.Package> clientLibPkgs = null;
10035        // writer
10036        synchronized (mPackages) {
10037            boolean hasStaticSharedLibs = false;
10038
10039            // Any app can add new static shared libraries
10040            if (pkg.staticSharedLibName != null) {
10041                // Static shared libs don't allow renaming as they have synthetic package
10042                // names to allow install of multiple versions, so use name from manifest.
10043                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10044                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10045                        pkg.manifestPackageName, pkg.mVersionCode)) {
10046                    hasStaticSharedLibs = true;
10047                } else {
10048                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10049                                + pkg.staticSharedLibName + " already exists; skipping");
10050                }
10051                // Static shared libs cannot be updated once installed since they
10052                // use synthetic package name which includes the version code, so
10053                // not need to update other packages's shared lib dependencies.
10054            }
10055
10056            if (!hasStaticSharedLibs
10057                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10058                // Only system apps can add new dynamic shared libraries.
10059                if (pkg.libraryNames != null) {
10060                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10061                        String name = pkg.libraryNames.get(i);
10062                        boolean allowed = false;
10063                        if (pkg.isUpdatedSystemApp()) {
10064                            // New library entries can only be added through the
10065                            // system image.  This is important to get rid of a lot
10066                            // of nasty edge cases: for example if we allowed a non-
10067                            // system update of the app to add a library, then uninstalling
10068                            // the update would make the library go away, and assumptions
10069                            // we made such as through app install filtering would now
10070                            // have allowed apps on the device which aren't compatible
10071                            // with it.  Better to just have the restriction here, be
10072                            // conservative, and create many fewer cases that can negatively
10073                            // impact the user experience.
10074                            final PackageSetting sysPs = mSettings
10075                                    .getDisabledSystemPkgLPr(pkg.packageName);
10076                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10077                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10078                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10079                                        allowed = true;
10080                                        break;
10081                                    }
10082                                }
10083                            }
10084                        } else {
10085                            allowed = true;
10086                        }
10087                        if (allowed) {
10088                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10089                                    SharedLibraryInfo.VERSION_UNDEFINED,
10090                                    SharedLibraryInfo.TYPE_DYNAMIC,
10091                                    pkg.packageName, pkg.mVersionCode)) {
10092                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10093                                        + name + " already exists; skipping");
10094                            }
10095                        } else {
10096                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10097                                    + name + " that is not declared on system image; skipping");
10098                        }
10099                    }
10100
10101                    if ((scanFlags & SCAN_BOOTING) == 0) {
10102                        // If we are not booting, we need to update any applications
10103                        // that are clients of our shared library.  If we are booting,
10104                        // this will all be done once the scan is complete.
10105                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10106                    }
10107                }
10108            }
10109        }
10110
10111        if ((scanFlags & SCAN_BOOTING) != 0) {
10112            // No apps can run during boot scan, so they don't need to be frozen
10113        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10114            // Caller asked to not kill app, so it's probably not frozen
10115        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10116            // Caller asked us to ignore frozen check for some reason; they
10117            // probably didn't know the package name
10118        } else {
10119            // We're doing major surgery on this package, so it better be frozen
10120            // right now to keep it from launching
10121            checkPackageFrozen(pkgName);
10122        }
10123
10124        // Also need to kill any apps that are dependent on the library.
10125        if (clientLibPkgs != null) {
10126            for (int i=0; i<clientLibPkgs.size(); i++) {
10127                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10128                killApplication(clientPkg.applicationInfo.packageName,
10129                        clientPkg.applicationInfo.uid, "update lib");
10130            }
10131        }
10132
10133        // writer
10134        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10135
10136        synchronized (mPackages) {
10137            // We don't expect installation to fail beyond this point
10138
10139            // Add the new setting to mSettings
10140            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10141            // Add the new setting to mPackages
10142            mPackages.put(pkg.applicationInfo.packageName, pkg);
10143            // Make sure we don't accidentally delete its data.
10144            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10145            while (iter.hasNext()) {
10146                PackageCleanItem item = iter.next();
10147                if (pkgName.equals(item.packageName)) {
10148                    iter.remove();
10149                }
10150            }
10151
10152            // Add the package's KeySets to the global KeySetManagerService
10153            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10154            ksms.addScannedPackageLPw(pkg);
10155
10156            int N = pkg.providers.size();
10157            StringBuilder r = null;
10158            int i;
10159            for (i=0; i<N; i++) {
10160                PackageParser.Provider p = pkg.providers.get(i);
10161                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10162                        p.info.processName);
10163                mProviders.addProvider(p);
10164                p.syncable = p.info.isSyncable;
10165                if (p.info.authority != null) {
10166                    String names[] = p.info.authority.split(";");
10167                    p.info.authority = null;
10168                    for (int j = 0; j < names.length; j++) {
10169                        if (j == 1 && p.syncable) {
10170                            // We only want the first authority for a provider to possibly be
10171                            // syncable, so if we already added this provider using a different
10172                            // authority clear the syncable flag. We copy the provider before
10173                            // changing it because the mProviders object contains a reference
10174                            // to a provider that we don't want to change.
10175                            // Only do this for the second authority since the resulting provider
10176                            // object can be the same for all future authorities for this provider.
10177                            p = new PackageParser.Provider(p);
10178                            p.syncable = false;
10179                        }
10180                        if (!mProvidersByAuthority.containsKey(names[j])) {
10181                            mProvidersByAuthority.put(names[j], p);
10182                            if (p.info.authority == null) {
10183                                p.info.authority = names[j];
10184                            } else {
10185                                p.info.authority = p.info.authority + ";" + names[j];
10186                            }
10187                            if (DEBUG_PACKAGE_SCANNING) {
10188                                if (chatty)
10189                                    Log.d(TAG, "Registered content provider: " + names[j]
10190                                            + ", className = " + p.info.name + ", isSyncable = "
10191                                            + p.info.isSyncable);
10192                            }
10193                        } else {
10194                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10195                            Slog.w(TAG, "Skipping provider name " + names[j] +
10196                                    " (in package " + pkg.applicationInfo.packageName +
10197                                    "): name already used by "
10198                                    + ((other != null && other.getComponentName() != null)
10199                                            ? other.getComponentName().getPackageName() : "?"));
10200                        }
10201                    }
10202                }
10203                if (chatty) {
10204                    if (r == null) {
10205                        r = new StringBuilder(256);
10206                    } else {
10207                        r.append(' ');
10208                    }
10209                    r.append(p.info.name);
10210                }
10211            }
10212            if (r != null) {
10213                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10214            }
10215
10216            N = pkg.services.size();
10217            r = null;
10218            for (i=0; i<N; i++) {
10219                PackageParser.Service s = pkg.services.get(i);
10220                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10221                        s.info.processName);
10222                mServices.addService(s);
10223                if (chatty) {
10224                    if (r == null) {
10225                        r = new StringBuilder(256);
10226                    } else {
10227                        r.append(' ');
10228                    }
10229                    r.append(s.info.name);
10230                }
10231            }
10232            if (r != null) {
10233                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10234            }
10235
10236            N = pkg.receivers.size();
10237            r = null;
10238            for (i=0; i<N; i++) {
10239                PackageParser.Activity a = pkg.receivers.get(i);
10240                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10241                        a.info.processName);
10242                mReceivers.addActivity(a, "receiver");
10243                if (chatty) {
10244                    if (r == null) {
10245                        r = new StringBuilder(256);
10246                    } else {
10247                        r.append(' ');
10248                    }
10249                    r.append(a.info.name);
10250                }
10251            }
10252            if (r != null) {
10253                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10254            }
10255
10256            N = pkg.activities.size();
10257            r = null;
10258            for (i=0; i<N; i++) {
10259                PackageParser.Activity a = pkg.activities.get(i);
10260                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10261                        a.info.processName);
10262                mActivities.addActivity(a, "activity");
10263                if (chatty) {
10264                    if (r == null) {
10265                        r = new StringBuilder(256);
10266                    } else {
10267                        r.append(' ');
10268                    }
10269                    r.append(a.info.name);
10270                }
10271            }
10272            if (r != null) {
10273                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10274            }
10275
10276            N = pkg.permissionGroups.size();
10277            r = null;
10278            for (i=0; i<N; i++) {
10279                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10280                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10281                final String curPackageName = cur == null ? null : cur.info.packageName;
10282                // Dont allow ephemeral apps to define new permission groups.
10283                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10284                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10285                            + pg.info.packageName
10286                            + " ignored: instant apps cannot define new permission groups.");
10287                    continue;
10288                }
10289                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10290                if (cur == null || isPackageUpdate) {
10291                    mPermissionGroups.put(pg.info.name, pg);
10292                    if (chatty) {
10293                        if (r == null) {
10294                            r = new StringBuilder(256);
10295                        } else {
10296                            r.append(' ');
10297                        }
10298                        if (isPackageUpdate) {
10299                            r.append("UPD:");
10300                        }
10301                        r.append(pg.info.name);
10302                    }
10303                } else {
10304                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10305                            + pg.info.packageName + " ignored: original from "
10306                            + cur.info.packageName);
10307                    if (chatty) {
10308                        if (r == null) {
10309                            r = new StringBuilder(256);
10310                        } else {
10311                            r.append(' ');
10312                        }
10313                        r.append("DUP:");
10314                        r.append(pg.info.name);
10315                    }
10316                }
10317            }
10318            if (r != null) {
10319                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10320            }
10321
10322            N = pkg.permissions.size();
10323            r = null;
10324            for (i=0; i<N; i++) {
10325                PackageParser.Permission p = pkg.permissions.get(i);
10326
10327                // Dont allow ephemeral apps to define new permissions.
10328                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10329                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10330                            + p.info.packageName
10331                            + " ignored: instant apps cannot define new permissions.");
10332                    continue;
10333                }
10334
10335                // Assume by default that we did not install this permission into the system.
10336                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10337
10338                // Now that permission groups have a special meaning, we ignore permission
10339                // groups for legacy apps to prevent unexpected behavior. In particular,
10340                // permissions for one app being granted to someone just becase they happen
10341                // to be in a group defined by another app (before this had no implications).
10342                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10343                    p.group = mPermissionGroups.get(p.info.group);
10344                    // Warn for a permission in an unknown group.
10345                    if (p.info.group != null && p.group == null) {
10346                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10347                                + p.info.packageName + " in an unknown group " + p.info.group);
10348                    }
10349                }
10350
10351                ArrayMap<String, BasePermission> permissionMap =
10352                        p.tree ? mSettings.mPermissionTrees
10353                                : mSettings.mPermissions;
10354                BasePermission bp = permissionMap.get(p.info.name);
10355
10356                // Allow system apps to redefine non-system permissions
10357                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10358                    final boolean currentOwnerIsSystem = (bp.perm != null
10359                            && isSystemApp(bp.perm.owner));
10360                    if (isSystemApp(p.owner)) {
10361                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10362                            // It's a built-in permission and no owner, take ownership now
10363                            bp.packageSetting = pkgSetting;
10364                            bp.perm = p;
10365                            bp.uid = pkg.applicationInfo.uid;
10366                            bp.sourcePackage = p.info.packageName;
10367                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10368                        } else if (!currentOwnerIsSystem) {
10369                            String msg = "New decl " + p.owner + " of permission  "
10370                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10371                            reportSettingsProblem(Log.WARN, msg);
10372                            bp = null;
10373                        }
10374                    }
10375                }
10376
10377                if (bp == null) {
10378                    bp = new BasePermission(p.info.name, p.info.packageName,
10379                            BasePermission.TYPE_NORMAL);
10380                    permissionMap.put(p.info.name, bp);
10381                }
10382
10383                if (bp.perm == null) {
10384                    if (bp.sourcePackage == null
10385                            || bp.sourcePackage.equals(p.info.packageName)) {
10386                        BasePermission tree = findPermissionTreeLP(p.info.name);
10387                        if (tree == null
10388                                || tree.sourcePackage.equals(p.info.packageName)) {
10389                            bp.packageSetting = pkgSetting;
10390                            bp.perm = p;
10391                            bp.uid = pkg.applicationInfo.uid;
10392                            bp.sourcePackage = p.info.packageName;
10393                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10394                            if (chatty) {
10395                                if (r == null) {
10396                                    r = new StringBuilder(256);
10397                                } else {
10398                                    r.append(' ');
10399                                }
10400                                r.append(p.info.name);
10401                            }
10402                        } else {
10403                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10404                                    + p.info.packageName + " ignored: base tree "
10405                                    + tree.name + " is from package "
10406                                    + tree.sourcePackage);
10407                        }
10408                    } else {
10409                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10410                                + p.info.packageName + " ignored: original from "
10411                                + bp.sourcePackage);
10412                    }
10413                } else if (chatty) {
10414                    if (r == null) {
10415                        r = new StringBuilder(256);
10416                    } else {
10417                        r.append(' ');
10418                    }
10419                    r.append("DUP:");
10420                    r.append(p.info.name);
10421                }
10422                if (bp.perm == p) {
10423                    bp.protectionLevel = p.info.protectionLevel;
10424                }
10425            }
10426
10427            if (r != null) {
10428                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10429            }
10430
10431            N = pkg.instrumentation.size();
10432            r = null;
10433            for (i=0; i<N; i++) {
10434                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10435                a.info.packageName = pkg.applicationInfo.packageName;
10436                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10437                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10438                a.info.splitNames = pkg.splitNames;
10439                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10440                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10441                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10442                a.info.dataDir = pkg.applicationInfo.dataDir;
10443                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10444                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10445                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10446                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10447                mInstrumentation.put(a.getComponentName(), a);
10448                if (chatty) {
10449                    if (r == null) {
10450                        r = new StringBuilder(256);
10451                    } else {
10452                        r.append(' ');
10453                    }
10454                    r.append(a.info.name);
10455                }
10456            }
10457            if (r != null) {
10458                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10459            }
10460
10461            if (pkg.protectedBroadcasts != null) {
10462                N = pkg.protectedBroadcasts.size();
10463                for (i=0; i<N; i++) {
10464                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10465                }
10466            }
10467        }
10468
10469        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10470    }
10471
10472    /**
10473     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10474     * is derived purely on the basis of the contents of {@code scanFile} and
10475     * {@code cpuAbiOverride}.
10476     *
10477     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10478     */
10479    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10480                                 String cpuAbiOverride, boolean extractLibs,
10481                                 File appLib32InstallDir)
10482            throws PackageManagerException {
10483        // Give ourselves some initial paths; we'll come back for another
10484        // pass once we've determined ABI below.
10485        setNativeLibraryPaths(pkg, appLib32InstallDir);
10486
10487        // We would never need to extract libs for forward-locked and external packages,
10488        // since the container service will do it for us. We shouldn't attempt to
10489        // extract libs from system app when it was not updated.
10490        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10491                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10492            extractLibs = false;
10493        }
10494
10495        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10496        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10497
10498        NativeLibraryHelper.Handle handle = null;
10499        try {
10500            handle = NativeLibraryHelper.Handle.create(pkg);
10501            // TODO(multiArch): This can be null for apps that didn't go through the
10502            // usual installation process. We can calculate it again, like we
10503            // do during install time.
10504            //
10505            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10506            // unnecessary.
10507            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10508
10509            // Null out the abis so that they can be recalculated.
10510            pkg.applicationInfo.primaryCpuAbi = null;
10511            pkg.applicationInfo.secondaryCpuAbi = null;
10512            if (isMultiArch(pkg.applicationInfo)) {
10513                // Warn if we've set an abiOverride for multi-lib packages..
10514                // By definition, we need to copy both 32 and 64 bit libraries for
10515                // such packages.
10516                if (pkg.cpuAbiOverride != null
10517                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10518                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10519                }
10520
10521                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10522                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10523                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10524                    if (extractLibs) {
10525                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10526                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10527                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10528                                useIsaSpecificSubdirs);
10529                    } else {
10530                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10531                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10532                    }
10533                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10534                }
10535
10536                maybeThrowExceptionForMultiArchCopy(
10537                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10538
10539                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10540                    if (extractLibs) {
10541                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10542                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10543                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10544                                useIsaSpecificSubdirs);
10545                    } else {
10546                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10547                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10548                    }
10549                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10550                }
10551
10552                maybeThrowExceptionForMultiArchCopy(
10553                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10554
10555                if (abi64 >= 0) {
10556                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10557                }
10558
10559                if (abi32 >= 0) {
10560                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10561                    if (abi64 >= 0) {
10562                        if (pkg.use32bitAbi) {
10563                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10564                            pkg.applicationInfo.primaryCpuAbi = abi;
10565                        } else {
10566                            pkg.applicationInfo.secondaryCpuAbi = abi;
10567                        }
10568                    } else {
10569                        pkg.applicationInfo.primaryCpuAbi = abi;
10570                    }
10571                }
10572
10573            } else {
10574                String[] abiList = (cpuAbiOverride != null) ?
10575                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10576
10577                // Enable gross and lame hacks for apps that are built with old
10578                // SDK tools. We must scan their APKs for renderscript bitcode and
10579                // not launch them if it's present. Don't bother checking on devices
10580                // that don't have 64 bit support.
10581                boolean needsRenderScriptOverride = false;
10582                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10583                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10584                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10585                    needsRenderScriptOverride = true;
10586                }
10587
10588                final int copyRet;
10589                if (extractLibs) {
10590                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10591                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10592                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10593                } else {
10594                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10595                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10596                }
10597                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10598
10599                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10600                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10601                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10602                }
10603
10604                if (copyRet >= 0) {
10605                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10606                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10607                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10608                } else if (needsRenderScriptOverride) {
10609                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10610                }
10611            }
10612        } catch (IOException ioe) {
10613            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10614        } finally {
10615            IoUtils.closeQuietly(handle);
10616        }
10617
10618        // Now that we've calculated the ABIs and determined if it's an internal app,
10619        // we will go ahead and populate the nativeLibraryPath.
10620        setNativeLibraryPaths(pkg, appLib32InstallDir);
10621    }
10622
10623    /**
10624     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10625     * i.e, so that all packages can be run inside a single process if required.
10626     *
10627     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10628     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10629     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10630     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10631     * updating a package that belongs to a shared user.
10632     *
10633     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10634     * adds unnecessary complexity.
10635     */
10636    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10637            PackageParser.Package scannedPackage) {
10638        String requiredInstructionSet = null;
10639        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10640            requiredInstructionSet = VMRuntime.getInstructionSet(
10641                     scannedPackage.applicationInfo.primaryCpuAbi);
10642        }
10643
10644        PackageSetting requirer = null;
10645        for (PackageSetting ps : packagesForUser) {
10646            // If packagesForUser contains scannedPackage, we skip it. This will happen
10647            // when scannedPackage is an update of an existing package. Without this check,
10648            // we will never be able to change the ABI of any package belonging to a shared
10649            // user, even if it's compatible with other packages.
10650            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10651                if (ps.primaryCpuAbiString == null) {
10652                    continue;
10653                }
10654
10655                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10656                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10657                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10658                    // this but there's not much we can do.
10659                    String errorMessage = "Instruction set mismatch, "
10660                            + ((requirer == null) ? "[caller]" : requirer)
10661                            + " requires " + requiredInstructionSet + " whereas " + ps
10662                            + " requires " + instructionSet;
10663                    Slog.w(TAG, errorMessage);
10664                }
10665
10666                if (requiredInstructionSet == null) {
10667                    requiredInstructionSet = instructionSet;
10668                    requirer = ps;
10669                }
10670            }
10671        }
10672
10673        if (requiredInstructionSet != null) {
10674            String adjustedAbi;
10675            if (requirer != null) {
10676                // requirer != null implies that either scannedPackage was null or that scannedPackage
10677                // did not require an ABI, in which case we have to adjust scannedPackage to match
10678                // the ABI of the set (which is the same as requirer's ABI)
10679                adjustedAbi = requirer.primaryCpuAbiString;
10680                if (scannedPackage != null) {
10681                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10682                }
10683            } else {
10684                // requirer == null implies that we're updating all ABIs in the set to
10685                // match scannedPackage.
10686                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10687            }
10688
10689            for (PackageSetting ps : packagesForUser) {
10690                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10691                    if (ps.primaryCpuAbiString != null) {
10692                        continue;
10693                    }
10694
10695                    ps.primaryCpuAbiString = adjustedAbi;
10696                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10697                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10698                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10699                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10700                                + " (requirer="
10701                                + (requirer != null ? requirer.pkg : "null")
10702                                + ", scannedPackage="
10703                                + (scannedPackage != null ? scannedPackage : "null")
10704                                + ")");
10705                        try {
10706                            mInstaller.rmdex(ps.codePathString,
10707                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10708                        } catch (InstallerException ignored) {
10709                        }
10710                    }
10711                }
10712            }
10713        }
10714    }
10715
10716    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10717        synchronized (mPackages) {
10718            mResolverReplaced = true;
10719            // Set up information for custom user intent resolution activity.
10720            mResolveActivity.applicationInfo = pkg.applicationInfo;
10721            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10722            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10723            mResolveActivity.processName = pkg.applicationInfo.packageName;
10724            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10725            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10726                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10727            mResolveActivity.theme = 0;
10728            mResolveActivity.exported = true;
10729            mResolveActivity.enabled = true;
10730            mResolveInfo.activityInfo = mResolveActivity;
10731            mResolveInfo.priority = 0;
10732            mResolveInfo.preferredOrder = 0;
10733            mResolveInfo.match = 0;
10734            mResolveComponentName = mCustomResolverComponentName;
10735            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10736                    mResolveComponentName);
10737        }
10738    }
10739
10740    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
10741        if (installerActivity == null) {
10742            if (DEBUG_EPHEMERAL) {
10743                Slog.d(TAG, "Clear ephemeral installer activity");
10744            }
10745            mInstantAppInstallerActivity = null;
10746            return;
10747        }
10748
10749        if (DEBUG_EPHEMERAL) {
10750            Slog.d(TAG, "Set ephemeral installer activity: "
10751                    + installerActivity.getComponentName());
10752        }
10753        // Set up information for ephemeral installer activity
10754        mInstantAppInstallerActivity = installerActivity;
10755        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10756                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10757        mInstantAppInstallerActivity.exported = true;
10758        mInstantAppInstallerActivity.enabled = true;
10759        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10760        mInstantAppInstallerInfo.priority = 0;
10761        mInstantAppInstallerInfo.preferredOrder = 1;
10762        mInstantAppInstallerInfo.isDefault = true;
10763        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10764                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10765    }
10766
10767    private static String calculateBundledApkRoot(final String codePathString) {
10768        final File codePath = new File(codePathString);
10769        final File codeRoot;
10770        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10771            codeRoot = Environment.getRootDirectory();
10772        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10773            codeRoot = Environment.getOemDirectory();
10774        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10775            codeRoot = Environment.getVendorDirectory();
10776        } else {
10777            // Unrecognized code path; take its top real segment as the apk root:
10778            // e.g. /something/app/blah.apk => /something
10779            try {
10780                File f = codePath.getCanonicalFile();
10781                File parent = f.getParentFile();    // non-null because codePath is a file
10782                File tmp;
10783                while ((tmp = parent.getParentFile()) != null) {
10784                    f = parent;
10785                    parent = tmp;
10786                }
10787                codeRoot = f;
10788                Slog.w(TAG, "Unrecognized code path "
10789                        + codePath + " - using " + codeRoot);
10790            } catch (IOException e) {
10791                // Can't canonicalize the code path -- shenanigans?
10792                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10793                return Environment.getRootDirectory().getPath();
10794            }
10795        }
10796        return codeRoot.getPath();
10797    }
10798
10799    /**
10800     * Derive and set the location of native libraries for the given package,
10801     * which varies depending on where and how the package was installed.
10802     */
10803    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10804        final ApplicationInfo info = pkg.applicationInfo;
10805        final String codePath = pkg.codePath;
10806        final File codeFile = new File(codePath);
10807        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10808        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10809
10810        info.nativeLibraryRootDir = null;
10811        info.nativeLibraryRootRequiresIsa = false;
10812        info.nativeLibraryDir = null;
10813        info.secondaryNativeLibraryDir = null;
10814
10815        if (isApkFile(codeFile)) {
10816            // Monolithic install
10817            if (bundledApp) {
10818                // If "/system/lib64/apkname" exists, assume that is the per-package
10819                // native library directory to use; otherwise use "/system/lib/apkname".
10820                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10821                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10822                        getPrimaryInstructionSet(info));
10823
10824                // This is a bundled system app so choose the path based on the ABI.
10825                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10826                // is just the default path.
10827                final String apkName = deriveCodePathName(codePath);
10828                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10829                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10830                        apkName).getAbsolutePath();
10831
10832                if (info.secondaryCpuAbi != null) {
10833                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10834                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10835                            secondaryLibDir, apkName).getAbsolutePath();
10836                }
10837            } else if (asecApp) {
10838                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10839                        .getAbsolutePath();
10840            } else {
10841                final String apkName = deriveCodePathName(codePath);
10842                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10843                        .getAbsolutePath();
10844            }
10845
10846            info.nativeLibraryRootRequiresIsa = false;
10847            info.nativeLibraryDir = info.nativeLibraryRootDir;
10848        } else {
10849            // Cluster install
10850            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10851            info.nativeLibraryRootRequiresIsa = true;
10852
10853            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10854                    getPrimaryInstructionSet(info)).getAbsolutePath();
10855
10856            if (info.secondaryCpuAbi != null) {
10857                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10858                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10859            }
10860        }
10861    }
10862
10863    /**
10864     * Calculate the abis and roots for a bundled app. These can uniquely
10865     * be determined from the contents of the system partition, i.e whether
10866     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10867     * of this information, and instead assume that the system was built
10868     * sensibly.
10869     */
10870    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10871                                           PackageSetting pkgSetting) {
10872        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10873
10874        // If "/system/lib64/apkname" exists, assume that is the per-package
10875        // native library directory to use; otherwise use "/system/lib/apkname".
10876        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10877        setBundledAppAbi(pkg, apkRoot, apkName);
10878        // pkgSetting might be null during rescan following uninstall of updates
10879        // to a bundled app, so accommodate that possibility.  The settings in
10880        // that case will be established later from the parsed package.
10881        //
10882        // If the settings aren't null, sync them up with what we've just derived.
10883        // note that apkRoot isn't stored in the package settings.
10884        if (pkgSetting != null) {
10885            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10886            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10887        }
10888    }
10889
10890    /**
10891     * Deduces the ABI of a bundled app and sets the relevant fields on the
10892     * parsed pkg object.
10893     *
10894     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10895     *        under which system libraries are installed.
10896     * @param apkName the name of the installed package.
10897     */
10898    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10899        final File codeFile = new File(pkg.codePath);
10900
10901        final boolean has64BitLibs;
10902        final boolean has32BitLibs;
10903        if (isApkFile(codeFile)) {
10904            // Monolithic install
10905            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10906            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10907        } else {
10908            // Cluster install
10909            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10910            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10911                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10912                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10913                has64BitLibs = (new File(rootDir, isa)).exists();
10914            } else {
10915                has64BitLibs = false;
10916            }
10917            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10918                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10919                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10920                has32BitLibs = (new File(rootDir, isa)).exists();
10921            } else {
10922                has32BitLibs = false;
10923            }
10924        }
10925
10926        if (has64BitLibs && !has32BitLibs) {
10927            // The package has 64 bit libs, but not 32 bit libs. Its primary
10928            // ABI should be 64 bit. We can safely assume here that the bundled
10929            // native libraries correspond to the most preferred ABI in the list.
10930
10931            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10932            pkg.applicationInfo.secondaryCpuAbi = null;
10933        } else if (has32BitLibs && !has64BitLibs) {
10934            // The package has 32 bit libs but not 64 bit libs. Its primary
10935            // ABI should be 32 bit.
10936
10937            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10938            pkg.applicationInfo.secondaryCpuAbi = null;
10939        } else if (has32BitLibs && has64BitLibs) {
10940            // The application has both 64 and 32 bit bundled libraries. We check
10941            // here that the app declares multiArch support, and warn if it doesn't.
10942            //
10943            // We will be lenient here and record both ABIs. The primary will be the
10944            // ABI that's higher on the list, i.e, a device that's configured to prefer
10945            // 64 bit apps will see a 64 bit primary ABI,
10946
10947            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10948                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10949            }
10950
10951            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10952                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10953                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10954            } else {
10955                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10956                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10957            }
10958        } else {
10959            pkg.applicationInfo.primaryCpuAbi = null;
10960            pkg.applicationInfo.secondaryCpuAbi = null;
10961        }
10962    }
10963
10964    private void killApplication(String pkgName, int appId, String reason) {
10965        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10966    }
10967
10968    private void killApplication(String pkgName, int appId, int userId, String reason) {
10969        // Request the ActivityManager to kill the process(only for existing packages)
10970        // so that we do not end up in a confused state while the user is still using the older
10971        // version of the application while the new one gets installed.
10972        final long token = Binder.clearCallingIdentity();
10973        try {
10974            IActivityManager am = ActivityManager.getService();
10975            if (am != null) {
10976                try {
10977                    am.killApplication(pkgName, appId, userId, reason);
10978                } catch (RemoteException e) {
10979                }
10980            }
10981        } finally {
10982            Binder.restoreCallingIdentity(token);
10983        }
10984    }
10985
10986    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10987        // Remove the parent package setting
10988        PackageSetting ps = (PackageSetting) pkg.mExtras;
10989        if (ps != null) {
10990            removePackageLI(ps, chatty);
10991        }
10992        // Remove the child package setting
10993        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10994        for (int i = 0; i < childCount; i++) {
10995            PackageParser.Package childPkg = pkg.childPackages.get(i);
10996            ps = (PackageSetting) childPkg.mExtras;
10997            if (ps != null) {
10998                removePackageLI(ps, chatty);
10999            }
11000        }
11001    }
11002
11003    void removePackageLI(PackageSetting ps, boolean chatty) {
11004        if (DEBUG_INSTALL) {
11005            if (chatty)
11006                Log.d(TAG, "Removing package " + ps.name);
11007        }
11008
11009        // writer
11010        synchronized (mPackages) {
11011            mPackages.remove(ps.name);
11012            final PackageParser.Package pkg = ps.pkg;
11013            if (pkg != null) {
11014                cleanPackageDataStructuresLILPw(pkg, chatty);
11015            }
11016        }
11017    }
11018
11019    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11020        if (DEBUG_INSTALL) {
11021            if (chatty)
11022                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11023        }
11024
11025        // writer
11026        synchronized (mPackages) {
11027            // Remove the parent package
11028            mPackages.remove(pkg.applicationInfo.packageName);
11029            cleanPackageDataStructuresLILPw(pkg, chatty);
11030
11031            // Remove the child packages
11032            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11033            for (int i = 0; i < childCount; i++) {
11034                PackageParser.Package childPkg = pkg.childPackages.get(i);
11035                mPackages.remove(childPkg.applicationInfo.packageName);
11036                cleanPackageDataStructuresLILPw(childPkg, chatty);
11037            }
11038        }
11039    }
11040
11041    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11042        int N = pkg.providers.size();
11043        StringBuilder r = null;
11044        int i;
11045        for (i=0; i<N; i++) {
11046            PackageParser.Provider p = pkg.providers.get(i);
11047            mProviders.removeProvider(p);
11048            if (p.info.authority == null) {
11049
11050                /* There was another ContentProvider with this authority when
11051                 * this app was installed so this authority is null,
11052                 * Ignore it as we don't have to unregister the provider.
11053                 */
11054                continue;
11055            }
11056            String names[] = p.info.authority.split(";");
11057            for (int j = 0; j < names.length; j++) {
11058                if (mProvidersByAuthority.get(names[j]) == p) {
11059                    mProvidersByAuthority.remove(names[j]);
11060                    if (DEBUG_REMOVE) {
11061                        if (chatty)
11062                            Log.d(TAG, "Unregistered content provider: " + names[j]
11063                                    + ", className = " + p.info.name + ", isSyncable = "
11064                                    + p.info.isSyncable);
11065                    }
11066                }
11067            }
11068            if (DEBUG_REMOVE && chatty) {
11069                if (r == null) {
11070                    r = new StringBuilder(256);
11071                } else {
11072                    r.append(' ');
11073                }
11074                r.append(p.info.name);
11075            }
11076        }
11077        if (r != null) {
11078            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11079        }
11080
11081        N = pkg.services.size();
11082        r = null;
11083        for (i=0; i<N; i++) {
11084            PackageParser.Service s = pkg.services.get(i);
11085            mServices.removeService(s);
11086            if (chatty) {
11087                if (r == null) {
11088                    r = new StringBuilder(256);
11089                } else {
11090                    r.append(' ');
11091                }
11092                r.append(s.info.name);
11093            }
11094        }
11095        if (r != null) {
11096            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11097        }
11098
11099        N = pkg.receivers.size();
11100        r = null;
11101        for (i=0; i<N; i++) {
11102            PackageParser.Activity a = pkg.receivers.get(i);
11103            mReceivers.removeActivity(a, "receiver");
11104            if (DEBUG_REMOVE && chatty) {
11105                if (r == null) {
11106                    r = new StringBuilder(256);
11107                } else {
11108                    r.append(' ');
11109                }
11110                r.append(a.info.name);
11111            }
11112        }
11113        if (r != null) {
11114            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11115        }
11116
11117        N = pkg.activities.size();
11118        r = null;
11119        for (i=0; i<N; i++) {
11120            PackageParser.Activity a = pkg.activities.get(i);
11121            mActivities.removeActivity(a, "activity");
11122            if (DEBUG_REMOVE && chatty) {
11123                if (r == null) {
11124                    r = new StringBuilder(256);
11125                } else {
11126                    r.append(' ');
11127                }
11128                r.append(a.info.name);
11129            }
11130        }
11131        if (r != null) {
11132            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11133        }
11134
11135        N = pkg.permissions.size();
11136        r = null;
11137        for (i=0; i<N; i++) {
11138            PackageParser.Permission p = pkg.permissions.get(i);
11139            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11140            if (bp == null) {
11141                bp = mSettings.mPermissionTrees.get(p.info.name);
11142            }
11143            if (bp != null && bp.perm == p) {
11144                bp.perm = null;
11145                if (DEBUG_REMOVE && chatty) {
11146                    if (r == null) {
11147                        r = new StringBuilder(256);
11148                    } else {
11149                        r.append(' ');
11150                    }
11151                    r.append(p.info.name);
11152                }
11153            }
11154            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11155                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11156                if (appOpPkgs != null) {
11157                    appOpPkgs.remove(pkg.packageName);
11158                }
11159            }
11160        }
11161        if (r != null) {
11162            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11163        }
11164
11165        N = pkg.requestedPermissions.size();
11166        r = null;
11167        for (i=0; i<N; i++) {
11168            String perm = pkg.requestedPermissions.get(i);
11169            BasePermission bp = mSettings.mPermissions.get(perm);
11170            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11171                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11172                if (appOpPkgs != null) {
11173                    appOpPkgs.remove(pkg.packageName);
11174                    if (appOpPkgs.isEmpty()) {
11175                        mAppOpPermissionPackages.remove(perm);
11176                    }
11177                }
11178            }
11179        }
11180        if (r != null) {
11181            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11182        }
11183
11184        N = pkg.instrumentation.size();
11185        r = null;
11186        for (i=0; i<N; i++) {
11187            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11188            mInstrumentation.remove(a.getComponentName());
11189            if (DEBUG_REMOVE && chatty) {
11190                if (r == null) {
11191                    r = new StringBuilder(256);
11192                } else {
11193                    r.append(' ');
11194                }
11195                r.append(a.info.name);
11196            }
11197        }
11198        if (r != null) {
11199            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11200        }
11201
11202        r = null;
11203        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11204            // Only system apps can hold shared libraries.
11205            if (pkg.libraryNames != null) {
11206                for (i = 0; i < pkg.libraryNames.size(); i++) {
11207                    String name = pkg.libraryNames.get(i);
11208                    if (removeSharedLibraryLPw(name, 0)) {
11209                        if (DEBUG_REMOVE && chatty) {
11210                            if (r == null) {
11211                                r = new StringBuilder(256);
11212                            } else {
11213                                r.append(' ');
11214                            }
11215                            r.append(name);
11216                        }
11217                    }
11218                }
11219            }
11220        }
11221
11222        r = null;
11223
11224        // Any package can hold static shared libraries.
11225        if (pkg.staticSharedLibName != null) {
11226            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11227                if (DEBUG_REMOVE && chatty) {
11228                    if (r == null) {
11229                        r = new StringBuilder(256);
11230                    } else {
11231                        r.append(' ');
11232                    }
11233                    r.append(pkg.staticSharedLibName);
11234                }
11235            }
11236        }
11237
11238        if (r != null) {
11239            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11240        }
11241    }
11242
11243    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11244        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11245            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11246                return true;
11247            }
11248        }
11249        return false;
11250    }
11251
11252    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11253    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11254    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11255
11256    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11257        // Update the parent permissions
11258        updatePermissionsLPw(pkg.packageName, pkg, flags);
11259        // Update the child permissions
11260        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11261        for (int i = 0; i < childCount; i++) {
11262            PackageParser.Package childPkg = pkg.childPackages.get(i);
11263            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11264        }
11265    }
11266
11267    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11268            int flags) {
11269        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11270        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11271    }
11272
11273    private void updatePermissionsLPw(String changingPkg,
11274            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11275        // Make sure there are no dangling permission trees.
11276        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11277        while (it.hasNext()) {
11278            final BasePermission bp = it.next();
11279            if (bp.packageSetting == null) {
11280                // We may not yet have parsed the package, so just see if
11281                // we still know about its settings.
11282                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11283            }
11284            if (bp.packageSetting == null) {
11285                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11286                        + " from package " + bp.sourcePackage);
11287                it.remove();
11288            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11289                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11290                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11291                            + " from package " + bp.sourcePackage);
11292                    flags |= UPDATE_PERMISSIONS_ALL;
11293                    it.remove();
11294                }
11295            }
11296        }
11297
11298        // Make sure all dynamic permissions have been assigned to a package,
11299        // and make sure there are no dangling permissions.
11300        it = mSettings.mPermissions.values().iterator();
11301        while (it.hasNext()) {
11302            final BasePermission bp = it.next();
11303            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11304                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11305                        + bp.name + " pkg=" + bp.sourcePackage
11306                        + " info=" + bp.pendingInfo);
11307                if (bp.packageSetting == null && bp.pendingInfo != null) {
11308                    final BasePermission tree = findPermissionTreeLP(bp.name);
11309                    if (tree != null && tree.perm != null) {
11310                        bp.packageSetting = tree.packageSetting;
11311                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11312                                new PermissionInfo(bp.pendingInfo));
11313                        bp.perm.info.packageName = tree.perm.info.packageName;
11314                        bp.perm.info.name = bp.name;
11315                        bp.uid = tree.uid;
11316                    }
11317                }
11318            }
11319            if (bp.packageSetting == null) {
11320                // We may not yet have parsed the package, so just see if
11321                // we still know about its settings.
11322                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11323            }
11324            if (bp.packageSetting == null) {
11325                Slog.w(TAG, "Removing dangling permission: " + bp.name
11326                        + " from package " + bp.sourcePackage);
11327                it.remove();
11328            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11329                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11330                    Slog.i(TAG, "Removing old permission: " + bp.name
11331                            + " from package " + bp.sourcePackage);
11332                    flags |= UPDATE_PERMISSIONS_ALL;
11333                    it.remove();
11334                }
11335            }
11336        }
11337
11338        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11339        // Now update the permissions for all packages, in particular
11340        // replace the granted permissions of the system packages.
11341        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11342            for (PackageParser.Package pkg : mPackages.values()) {
11343                if (pkg != pkgInfo) {
11344                    // Only replace for packages on requested volume
11345                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11346                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11347                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11348                    grantPermissionsLPw(pkg, replace, changingPkg);
11349                }
11350            }
11351        }
11352
11353        if (pkgInfo != null) {
11354            // Only replace for packages on requested volume
11355            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11356            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11357                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11358            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11359        }
11360        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11361    }
11362
11363    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11364            String packageOfInterest) {
11365        // IMPORTANT: There are two types of permissions: install and runtime.
11366        // Install time permissions are granted when the app is installed to
11367        // all device users and users added in the future. Runtime permissions
11368        // are granted at runtime explicitly to specific users. Normal and signature
11369        // protected permissions are install time permissions. Dangerous permissions
11370        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11371        // otherwise they are runtime permissions. This function does not manage
11372        // runtime permissions except for the case an app targeting Lollipop MR1
11373        // being upgraded to target a newer SDK, in which case dangerous permissions
11374        // are transformed from install time to runtime ones.
11375
11376        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11377        if (ps == null) {
11378            return;
11379        }
11380
11381        PermissionsState permissionsState = ps.getPermissionsState();
11382        PermissionsState origPermissions = permissionsState;
11383
11384        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11385
11386        boolean runtimePermissionsRevoked = false;
11387        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11388
11389        boolean changedInstallPermission = false;
11390
11391        if (replace) {
11392            ps.installPermissionsFixed = false;
11393            if (!ps.isSharedUser()) {
11394                origPermissions = new PermissionsState(permissionsState);
11395                permissionsState.reset();
11396            } else {
11397                // We need to know only about runtime permission changes since the
11398                // calling code always writes the install permissions state but
11399                // the runtime ones are written only if changed. The only cases of
11400                // changed runtime permissions here are promotion of an install to
11401                // runtime and revocation of a runtime from a shared user.
11402                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11403                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11404                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11405                    runtimePermissionsRevoked = true;
11406                }
11407            }
11408        }
11409
11410        permissionsState.setGlobalGids(mGlobalGids);
11411
11412        final int N = pkg.requestedPermissions.size();
11413        for (int i=0; i<N; i++) {
11414            final String name = pkg.requestedPermissions.get(i);
11415            final BasePermission bp = mSettings.mPermissions.get(name);
11416            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11417                    >= Build.VERSION_CODES.M;
11418
11419            if (DEBUG_INSTALL) {
11420                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11421            }
11422
11423            if (bp == null || bp.packageSetting == null) {
11424                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11425                    Slog.w(TAG, "Unknown permission " + name
11426                            + " in package " + pkg.packageName);
11427                }
11428                continue;
11429            }
11430
11431
11432            // Limit ephemeral apps to ephemeral allowed permissions.
11433            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11434                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11435                        + pkg.packageName);
11436                continue;
11437            }
11438
11439            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
11440                Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
11441                        + pkg.packageName);
11442                continue;
11443            }
11444
11445            final String perm = bp.name;
11446            boolean allowedSig = false;
11447            int grant = GRANT_DENIED;
11448
11449            // Keep track of app op permissions.
11450            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11451                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11452                if (pkgs == null) {
11453                    pkgs = new ArraySet<>();
11454                    mAppOpPermissionPackages.put(bp.name, pkgs);
11455                }
11456                pkgs.add(pkg.packageName);
11457            }
11458
11459            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11460            switch (level) {
11461                case PermissionInfo.PROTECTION_NORMAL: {
11462                    // For all apps normal permissions are install time ones.
11463                    grant = GRANT_INSTALL;
11464                } break;
11465
11466                case PermissionInfo.PROTECTION_DANGEROUS: {
11467                    // If a permission review is required for legacy apps we represent
11468                    // their permissions as always granted runtime ones since we need
11469                    // to keep the review required permission flag per user while an
11470                    // install permission's state is shared across all users.
11471                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11472                        // For legacy apps dangerous permissions are install time ones.
11473                        grant = GRANT_INSTALL;
11474                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11475                        // For legacy apps that became modern, install becomes runtime.
11476                        grant = GRANT_UPGRADE;
11477                    } else if (mPromoteSystemApps
11478                            && isSystemApp(ps)
11479                            && mExistingSystemPackages.contains(ps.name)) {
11480                        // For legacy system apps, install becomes runtime.
11481                        // We cannot check hasInstallPermission() for system apps since those
11482                        // permissions were granted implicitly and not persisted pre-M.
11483                        grant = GRANT_UPGRADE;
11484                    } else {
11485                        // For modern apps keep runtime permissions unchanged.
11486                        grant = GRANT_RUNTIME;
11487                    }
11488                } break;
11489
11490                case PermissionInfo.PROTECTION_SIGNATURE: {
11491                    // For all apps signature permissions are install time ones.
11492                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11493                    if (allowedSig) {
11494                        grant = GRANT_INSTALL;
11495                    }
11496                } break;
11497            }
11498
11499            if (DEBUG_INSTALL) {
11500                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11501            }
11502
11503            if (grant != GRANT_DENIED) {
11504                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11505                    // If this is an existing, non-system package, then
11506                    // we can't add any new permissions to it.
11507                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11508                        // Except...  if this is a permission that was added
11509                        // to the platform (note: need to only do this when
11510                        // updating the platform).
11511                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11512                            grant = GRANT_DENIED;
11513                        }
11514                    }
11515                }
11516
11517                switch (grant) {
11518                    case GRANT_INSTALL: {
11519                        // Revoke this as runtime permission to handle the case of
11520                        // a runtime permission being downgraded to an install one.
11521                        // Also in permission review mode we keep dangerous permissions
11522                        // for legacy apps
11523                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11524                            if (origPermissions.getRuntimePermissionState(
11525                                    bp.name, userId) != null) {
11526                                // Revoke the runtime permission and clear the flags.
11527                                origPermissions.revokeRuntimePermission(bp, userId);
11528                                origPermissions.updatePermissionFlags(bp, userId,
11529                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11530                                // If we revoked a permission permission, we have to write.
11531                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11532                                        changedRuntimePermissionUserIds, userId);
11533                            }
11534                        }
11535                        // Grant an install permission.
11536                        if (permissionsState.grantInstallPermission(bp) !=
11537                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11538                            changedInstallPermission = true;
11539                        }
11540                    } break;
11541
11542                    case GRANT_RUNTIME: {
11543                        // Grant previously granted runtime permissions.
11544                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11545                            PermissionState permissionState = origPermissions
11546                                    .getRuntimePermissionState(bp.name, userId);
11547                            int flags = permissionState != null
11548                                    ? permissionState.getFlags() : 0;
11549                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11550                                // Don't propagate the permission in a permission review mode if
11551                                // the former was revoked, i.e. marked to not propagate on upgrade.
11552                                // Note that in a permission review mode install permissions are
11553                                // represented as constantly granted runtime ones since we need to
11554                                // keep a per user state associated with the permission. Also the
11555                                // revoke on upgrade flag is no longer applicable and is reset.
11556                                final boolean revokeOnUpgrade = (flags & PackageManager
11557                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11558                                if (revokeOnUpgrade) {
11559                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11560                                    // Since we changed the flags, we have to write.
11561                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11562                                            changedRuntimePermissionUserIds, userId);
11563                                }
11564                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11565                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11566                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11567                                        // If we cannot put the permission as it was,
11568                                        // we have to write.
11569                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11570                                                changedRuntimePermissionUserIds, userId);
11571                                    }
11572                                }
11573
11574                                // If the app supports runtime permissions no need for a review.
11575                                if (mPermissionReviewRequired
11576                                        && appSupportsRuntimePermissions
11577                                        && (flags & PackageManager
11578                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11579                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11580                                    // Since we changed the flags, we have to write.
11581                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11582                                            changedRuntimePermissionUserIds, userId);
11583                                }
11584                            } else if (mPermissionReviewRequired
11585                                    && !appSupportsRuntimePermissions) {
11586                                // For legacy apps that need a permission review, every new
11587                                // runtime permission is granted but it is pending a review.
11588                                // We also need to review only platform defined runtime
11589                                // permissions as these are the only ones the platform knows
11590                                // how to disable the API to simulate revocation as legacy
11591                                // apps don't expect to run with revoked permissions.
11592                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11593                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11594                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11595                                        // We changed the flags, hence have to write.
11596                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11597                                                changedRuntimePermissionUserIds, userId);
11598                                    }
11599                                }
11600                                if (permissionsState.grantRuntimePermission(bp, userId)
11601                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11602                                    // We changed the permission, hence have to write.
11603                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11604                                            changedRuntimePermissionUserIds, userId);
11605                                }
11606                            }
11607                            // Propagate the permission flags.
11608                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11609                        }
11610                    } break;
11611
11612                    case GRANT_UPGRADE: {
11613                        // Grant runtime permissions for a previously held install permission.
11614                        PermissionState permissionState = origPermissions
11615                                .getInstallPermissionState(bp.name);
11616                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11617
11618                        if (origPermissions.revokeInstallPermission(bp)
11619                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11620                            // We will be transferring the permission flags, so clear them.
11621                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11622                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11623                            changedInstallPermission = true;
11624                        }
11625
11626                        // If the permission is not to be promoted to runtime we ignore it and
11627                        // also its other flags as they are not applicable to install permissions.
11628                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11629                            for (int userId : currentUserIds) {
11630                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11631                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11632                                    // Transfer the permission flags.
11633                                    permissionsState.updatePermissionFlags(bp, userId,
11634                                            flags, flags);
11635                                    // If we granted the permission, we have to write.
11636                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11637                                            changedRuntimePermissionUserIds, userId);
11638                                }
11639                            }
11640                        }
11641                    } break;
11642
11643                    default: {
11644                        if (packageOfInterest == null
11645                                || packageOfInterest.equals(pkg.packageName)) {
11646                            Slog.w(TAG, "Not granting permission " + perm
11647                                    + " to package " + pkg.packageName
11648                                    + " because it was previously installed without");
11649                        }
11650                    } break;
11651                }
11652            } else {
11653                if (permissionsState.revokeInstallPermission(bp) !=
11654                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11655                    // Also drop the permission flags.
11656                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11657                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11658                    changedInstallPermission = true;
11659                    Slog.i(TAG, "Un-granting permission " + perm
11660                            + " from package " + pkg.packageName
11661                            + " (protectionLevel=" + bp.protectionLevel
11662                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11663                            + ")");
11664                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11665                    // Don't print warning for app op permissions, since it is fine for them
11666                    // not to be granted, there is a UI for the user to decide.
11667                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11668                        Slog.w(TAG, "Not granting permission " + perm
11669                                + " to package " + pkg.packageName
11670                                + " (protectionLevel=" + bp.protectionLevel
11671                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11672                                + ")");
11673                    }
11674                }
11675            }
11676        }
11677
11678        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11679                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11680            // This is the first that we have heard about this package, so the
11681            // permissions we have now selected are fixed until explicitly
11682            // changed.
11683            ps.installPermissionsFixed = true;
11684        }
11685
11686        // Persist the runtime permissions state for users with changes. If permissions
11687        // were revoked because no app in the shared user declares them we have to
11688        // write synchronously to avoid losing runtime permissions state.
11689        for (int userId : changedRuntimePermissionUserIds) {
11690            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11691        }
11692    }
11693
11694    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11695        boolean allowed = false;
11696        final int NP = PackageParser.NEW_PERMISSIONS.length;
11697        for (int ip=0; ip<NP; ip++) {
11698            final PackageParser.NewPermissionInfo npi
11699                    = PackageParser.NEW_PERMISSIONS[ip];
11700            if (npi.name.equals(perm)
11701                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11702                allowed = true;
11703                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11704                        + pkg.packageName);
11705                break;
11706            }
11707        }
11708        return allowed;
11709    }
11710
11711    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11712            BasePermission bp, PermissionsState origPermissions) {
11713        boolean privilegedPermission = (bp.protectionLevel
11714                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11715        boolean privappPermissionsDisable =
11716                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11717        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11718        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11719        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11720                && !platformPackage && platformPermission) {
11721            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11722                    .getPrivAppPermissions(pkg.packageName);
11723            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11724            if (!whitelisted) {
11725                Slog.w(TAG, "Privileged permission " + perm + " for package "
11726                        + pkg.packageName + " - not in privapp-permissions whitelist");
11727                // Only report violations for apps on system image
11728                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11729                    if (mPrivappPermissionsViolations == null) {
11730                        mPrivappPermissionsViolations = new ArraySet<>();
11731                    }
11732                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11733                }
11734                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11735                    return false;
11736                }
11737            }
11738        }
11739        boolean allowed = (compareSignatures(
11740                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11741                        == PackageManager.SIGNATURE_MATCH)
11742                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11743                        == PackageManager.SIGNATURE_MATCH);
11744        if (!allowed && privilegedPermission) {
11745            if (isSystemApp(pkg)) {
11746                // For updated system applications, a system permission
11747                // is granted only if it had been defined by the original application.
11748                if (pkg.isUpdatedSystemApp()) {
11749                    final PackageSetting sysPs = mSettings
11750                            .getDisabledSystemPkgLPr(pkg.packageName);
11751                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11752                        // If the original was granted this permission, we take
11753                        // that grant decision as read and propagate it to the
11754                        // update.
11755                        if (sysPs.isPrivileged()) {
11756                            allowed = true;
11757                        }
11758                    } else {
11759                        // The system apk may have been updated with an older
11760                        // version of the one on the data partition, but which
11761                        // granted a new system permission that it didn't have
11762                        // before.  In this case we do want to allow the app to
11763                        // now get the new permission if the ancestral apk is
11764                        // privileged to get it.
11765                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11766                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11767                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11768                                    allowed = true;
11769                                    break;
11770                                }
11771                            }
11772                        }
11773                        // Also if a privileged parent package on the system image or any of
11774                        // its children requested a privileged permission, the updated child
11775                        // packages can also get the permission.
11776                        if (pkg.parentPackage != null) {
11777                            final PackageSetting disabledSysParentPs = mSettings
11778                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11779                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11780                                    && disabledSysParentPs.isPrivileged()) {
11781                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11782                                    allowed = true;
11783                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11784                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11785                                    for (int i = 0; i < count; i++) {
11786                                        PackageParser.Package disabledSysChildPkg =
11787                                                disabledSysParentPs.pkg.childPackages.get(i);
11788                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11789                                                perm)) {
11790                                            allowed = true;
11791                                            break;
11792                                        }
11793                                    }
11794                                }
11795                            }
11796                        }
11797                    }
11798                } else {
11799                    allowed = isPrivilegedApp(pkg);
11800                }
11801            }
11802        }
11803        if (!allowed) {
11804            if (!allowed && (bp.protectionLevel
11805                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11806                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11807                // If this was a previously normal/dangerous permission that got moved
11808                // to a system permission as part of the runtime permission redesign, then
11809                // we still want to blindly grant it to old apps.
11810                allowed = true;
11811            }
11812            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11813                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11814                // If this permission is to be granted to the system installer and
11815                // this app is an installer, then it gets the permission.
11816                allowed = true;
11817            }
11818            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11819                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11820                // If this permission is to be granted to the system verifier and
11821                // this app is a verifier, then it gets the permission.
11822                allowed = true;
11823            }
11824            if (!allowed && (bp.protectionLevel
11825                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11826                    && isSystemApp(pkg)) {
11827                // Any pre-installed system app is allowed to get this permission.
11828                allowed = true;
11829            }
11830            if (!allowed && (bp.protectionLevel
11831                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11832                // For development permissions, a development permission
11833                // is granted only if it was already granted.
11834                allowed = origPermissions.hasInstallPermission(perm);
11835            }
11836            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11837                    && pkg.packageName.equals(mSetupWizardPackage)) {
11838                // If this permission is to be granted to the system setup wizard and
11839                // this app is a setup wizard, then it gets the permission.
11840                allowed = true;
11841            }
11842        }
11843        return allowed;
11844    }
11845
11846    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11847        final int permCount = pkg.requestedPermissions.size();
11848        for (int j = 0; j < permCount; j++) {
11849            String requestedPermission = pkg.requestedPermissions.get(j);
11850            if (permission.equals(requestedPermission)) {
11851                return true;
11852            }
11853        }
11854        return false;
11855    }
11856
11857    final class ActivityIntentResolver
11858            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11859        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11860                boolean defaultOnly, int userId) {
11861            if (!sUserManager.exists(userId)) return null;
11862            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11863            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11864        }
11865
11866        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11867                int userId) {
11868            if (!sUserManager.exists(userId)) return null;
11869            mFlags = flags;
11870            return super.queryIntent(intent, resolvedType,
11871                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11872                    userId);
11873        }
11874
11875        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11876                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11877            if (!sUserManager.exists(userId)) return null;
11878            if (packageActivities == null) {
11879                return null;
11880            }
11881            mFlags = flags;
11882            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11883            final int N = packageActivities.size();
11884            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11885                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11886
11887            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11888            for (int i = 0; i < N; ++i) {
11889                intentFilters = packageActivities.get(i).intents;
11890                if (intentFilters != null && intentFilters.size() > 0) {
11891                    PackageParser.ActivityIntentInfo[] array =
11892                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11893                    intentFilters.toArray(array);
11894                    listCut.add(array);
11895                }
11896            }
11897            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11898        }
11899
11900        /**
11901         * Finds a privileged activity that matches the specified activity names.
11902         */
11903        private PackageParser.Activity findMatchingActivity(
11904                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11905            for (PackageParser.Activity sysActivity : activityList) {
11906                if (sysActivity.info.name.equals(activityInfo.name)) {
11907                    return sysActivity;
11908                }
11909                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11910                    return sysActivity;
11911                }
11912                if (sysActivity.info.targetActivity != null) {
11913                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11914                        return sysActivity;
11915                    }
11916                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11917                        return sysActivity;
11918                    }
11919                }
11920            }
11921            return null;
11922        }
11923
11924        public class IterGenerator<E> {
11925            public Iterator<E> generate(ActivityIntentInfo info) {
11926                return null;
11927            }
11928        }
11929
11930        public class ActionIterGenerator extends IterGenerator<String> {
11931            @Override
11932            public Iterator<String> generate(ActivityIntentInfo info) {
11933                return info.actionsIterator();
11934            }
11935        }
11936
11937        public class CategoriesIterGenerator extends IterGenerator<String> {
11938            @Override
11939            public Iterator<String> generate(ActivityIntentInfo info) {
11940                return info.categoriesIterator();
11941            }
11942        }
11943
11944        public class SchemesIterGenerator extends IterGenerator<String> {
11945            @Override
11946            public Iterator<String> generate(ActivityIntentInfo info) {
11947                return info.schemesIterator();
11948            }
11949        }
11950
11951        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11952            @Override
11953            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11954                return info.authoritiesIterator();
11955            }
11956        }
11957
11958        /**
11959         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11960         * MODIFIED. Do not pass in a list that should not be changed.
11961         */
11962        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11963                IterGenerator<T> generator, Iterator<T> searchIterator) {
11964            // loop through the set of actions; every one must be found in the intent filter
11965            while (searchIterator.hasNext()) {
11966                // we must have at least one filter in the list to consider a match
11967                if (intentList.size() == 0) {
11968                    break;
11969                }
11970
11971                final T searchAction = searchIterator.next();
11972
11973                // loop through the set of intent filters
11974                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11975                while (intentIter.hasNext()) {
11976                    final ActivityIntentInfo intentInfo = intentIter.next();
11977                    boolean selectionFound = false;
11978
11979                    // loop through the intent filter's selection criteria; at least one
11980                    // of them must match the searched criteria
11981                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11982                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11983                        final T intentSelection = intentSelectionIter.next();
11984                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11985                            selectionFound = true;
11986                            break;
11987                        }
11988                    }
11989
11990                    // the selection criteria wasn't found in this filter's set; this filter
11991                    // is not a potential match
11992                    if (!selectionFound) {
11993                        intentIter.remove();
11994                    }
11995                }
11996            }
11997        }
11998
11999        private boolean isProtectedAction(ActivityIntentInfo filter) {
12000            final Iterator<String> actionsIter = filter.actionsIterator();
12001            while (actionsIter != null && actionsIter.hasNext()) {
12002                final String filterAction = actionsIter.next();
12003                if (PROTECTED_ACTIONS.contains(filterAction)) {
12004                    return true;
12005                }
12006            }
12007            return false;
12008        }
12009
12010        /**
12011         * Adjusts the priority of the given intent filter according to policy.
12012         * <p>
12013         * <ul>
12014         * <li>The priority for non privileged applications is capped to '0'</li>
12015         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12016         * <li>The priority for unbundled updates to privileged applications is capped to the
12017         *      priority defined on the system partition</li>
12018         * </ul>
12019         * <p>
12020         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12021         * allowed to obtain any priority on any action.
12022         */
12023        private void adjustPriority(
12024                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12025            // nothing to do; priority is fine as-is
12026            if (intent.getPriority() <= 0) {
12027                return;
12028            }
12029
12030            final ActivityInfo activityInfo = intent.activity.info;
12031            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12032
12033            final boolean privilegedApp =
12034                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12035            if (!privilegedApp) {
12036                // non-privileged applications can never define a priority >0
12037                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12038                        + " package: " + applicationInfo.packageName
12039                        + " activity: " + intent.activity.className
12040                        + " origPrio: " + intent.getPriority());
12041                intent.setPriority(0);
12042                return;
12043            }
12044
12045            if (systemActivities == null) {
12046                // the system package is not disabled; we're parsing the system partition
12047                if (isProtectedAction(intent)) {
12048                    if (mDeferProtectedFilters) {
12049                        // We can't deal with these just yet. No component should ever obtain a
12050                        // >0 priority for a protected actions, with ONE exception -- the setup
12051                        // wizard. The setup wizard, however, cannot be known until we're able to
12052                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12053                        // until all intent filters have been processed. Chicken, meet egg.
12054                        // Let the filter temporarily have a high priority and rectify the
12055                        // priorities after all system packages have been scanned.
12056                        mProtectedFilters.add(intent);
12057                        if (DEBUG_FILTERS) {
12058                            Slog.i(TAG, "Protected action; save for later;"
12059                                    + " package: " + applicationInfo.packageName
12060                                    + " activity: " + intent.activity.className
12061                                    + " origPrio: " + intent.getPriority());
12062                        }
12063                        return;
12064                    } else {
12065                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12066                            Slog.i(TAG, "No setup wizard;"
12067                                + " All protected intents capped to priority 0");
12068                        }
12069                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12070                            if (DEBUG_FILTERS) {
12071                                Slog.i(TAG, "Found setup wizard;"
12072                                    + " allow priority " + intent.getPriority() + ";"
12073                                    + " package: " + intent.activity.info.packageName
12074                                    + " activity: " + intent.activity.className
12075                                    + " priority: " + intent.getPriority());
12076                            }
12077                            // setup wizard gets whatever it wants
12078                            return;
12079                        }
12080                        Slog.w(TAG, "Protected action; cap priority to 0;"
12081                                + " package: " + intent.activity.info.packageName
12082                                + " activity: " + intent.activity.className
12083                                + " origPrio: " + intent.getPriority());
12084                        intent.setPriority(0);
12085                        return;
12086                    }
12087                }
12088                // privileged apps on the system image get whatever priority they request
12089                return;
12090            }
12091
12092            // privileged app unbundled update ... try to find the same activity
12093            final PackageParser.Activity foundActivity =
12094                    findMatchingActivity(systemActivities, activityInfo);
12095            if (foundActivity == null) {
12096                // this is a new activity; it cannot obtain >0 priority
12097                if (DEBUG_FILTERS) {
12098                    Slog.i(TAG, "New activity; cap priority to 0;"
12099                            + " package: " + applicationInfo.packageName
12100                            + " activity: " + intent.activity.className
12101                            + " origPrio: " + intent.getPriority());
12102                }
12103                intent.setPriority(0);
12104                return;
12105            }
12106
12107            // found activity, now check for filter equivalence
12108
12109            // a shallow copy is enough; we modify the list, not its contents
12110            final List<ActivityIntentInfo> intentListCopy =
12111                    new ArrayList<>(foundActivity.intents);
12112            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12113
12114            // find matching action subsets
12115            final Iterator<String> actionsIterator = intent.actionsIterator();
12116            if (actionsIterator != null) {
12117                getIntentListSubset(
12118                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12119                if (intentListCopy.size() == 0) {
12120                    // no more intents to match; we're not equivalent
12121                    if (DEBUG_FILTERS) {
12122                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12123                                + " package: " + applicationInfo.packageName
12124                                + " activity: " + intent.activity.className
12125                                + " origPrio: " + intent.getPriority());
12126                    }
12127                    intent.setPriority(0);
12128                    return;
12129                }
12130            }
12131
12132            // find matching category subsets
12133            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12134            if (categoriesIterator != null) {
12135                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12136                        categoriesIterator);
12137                if (intentListCopy.size() == 0) {
12138                    // no more intents to match; we're not equivalent
12139                    if (DEBUG_FILTERS) {
12140                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12141                                + " package: " + applicationInfo.packageName
12142                                + " activity: " + intent.activity.className
12143                                + " origPrio: " + intent.getPriority());
12144                    }
12145                    intent.setPriority(0);
12146                    return;
12147                }
12148            }
12149
12150            // find matching schemes subsets
12151            final Iterator<String> schemesIterator = intent.schemesIterator();
12152            if (schemesIterator != null) {
12153                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12154                        schemesIterator);
12155                if (intentListCopy.size() == 0) {
12156                    // no more intents to match; we're not equivalent
12157                    if (DEBUG_FILTERS) {
12158                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12159                                + " package: " + applicationInfo.packageName
12160                                + " activity: " + intent.activity.className
12161                                + " origPrio: " + intent.getPriority());
12162                    }
12163                    intent.setPriority(0);
12164                    return;
12165                }
12166            }
12167
12168            // find matching authorities subsets
12169            final Iterator<IntentFilter.AuthorityEntry>
12170                    authoritiesIterator = intent.authoritiesIterator();
12171            if (authoritiesIterator != null) {
12172                getIntentListSubset(intentListCopy,
12173                        new AuthoritiesIterGenerator(),
12174                        authoritiesIterator);
12175                if (intentListCopy.size() == 0) {
12176                    // no more intents to match; we're not equivalent
12177                    if (DEBUG_FILTERS) {
12178                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12179                                + " package: " + applicationInfo.packageName
12180                                + " activity: " + intent.activity.className
12181                                + " origPrio: " + intent.getPriority());
12182                    }
12183                    intent.setPriority(0);
12184                    return;
12185                }
12186            }
12187
12188            // we found matching filter(s); app gets the max priority of all intents
12189            int cappedPriority = 0;
12190            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12191                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12192            }
12193            if (intent.getPriority() > cappedPriority) {
12194                if (DEBUG_FILTERS) {
12195                    Slog.i(TAG, "Found matching filter(s);"
12196                            + " cap priority to " + cappedPriority + ";"
12197                            + " package: " + applicationInfo.packageName
12198                            + " activity: " + intent.activity.className
12199                            + " origPrio: " + intent.getPriority());
12200                }
12201                intent.setPriority(cappedPriority);
12202                return;
12203            }
12204            // all this for nothing; the requested priority was <= what was on the system
12205        }
12206
12207        public final void addActivity(PackageParser.Activity a, String type) {
12208            mActivities.put(a.getComponentName(), a);
12209            if (DEBUG_SHOW_INFO)
12210                Log.v(
12211                TAG, "  " + type + " " +
12212                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12213            if (DEBUG_SHOW_INFO)
12214                Log.v(TAG, "    Class=" + a.info.name);
12215            final int NI = a.intents.size();
12216            for (int j=0; j<NI; j++) {
12217                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12218                if ("activity".equals(type)) {
12219                    final PackageSetting ps =
12220                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12221                    final List<PackageParser.Activity> systemActivities =
12222                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12223                    adjustPriority(systemActivities, intent);
12224                }
12225                if (DEBUG_SHOW_INFO) {
12226                    Log.v(TAG, "    IntentFilter:");
12227                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12228                }
12229                if (!intent.debugCheck()) {
12230                    Log.w(TAG, "==> For Activity " + a.info.name);
12231                }
12232                addFilter(intent);
12233            }
12234        }
12235
12236        public final void removeActivity(PackageParser.Activity a, String type) {
12237            mActivities.remove(a.getComponentName());
12238            if (DEBUG_SHOW_INFO) {
12239                Log.v(TAG, "  " + type + " "
12240                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12241                                : a.info.name) + ":");
12242                Log.v(TAG, "    Class=" + a.info.name);
12243            }
12244            final int NI = a.intents.size();
12245            for (int j=0; j<NI; j++) {
12246                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12247                if (DEBUG_SHOW_INFO) {
12248                    Log.v(TAG, "    IntentFilter:");
12249                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12250                }
12251                removeFilter(intent);
12252            }
12253        }
12254
12255        @Override
12256        protected boolean allowFilterResult(
12257                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12258            ActivityInfo filterAi = filter.activity.info;
12259            for (int i=dest.size()-1; i>=0; i--) {
12260                ActivityInfo destAi = dest.get(i).activityInfo;
12261                if (destAi.name == filterAi.name
12262                        && destAi.packageName == filterAi.packageName) {
12263                    return false;
12264                }
12265            }
12266            return true;
12267        }
12268
12269        @Override
12270        protected ActivityIntentInfo[] newArray(int size) {
12271            return new ActivityIntentInfo[size];
12272        }
12273
12274        @Override
12275        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12276            if (!sUserManager.exists(userId)) return true;
12277            PackageParser.Package p = filter.activity.owner;
12278            if (p != null) {
12279                PackageSetting ps = (PackageSetting)p.mExtras;
12280                if (ps != null) {
12281                    // System apps are never considered stopped for purposes of
12282                    // filtering, because there may be no way for the user to
12283                    // actually re-launch them.
12284                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12285                            && ps.getStopped(userId);
12286                }
12287            }
12288            return false;
12289        }
12290
12291        @Override
12292        protected boolean isPackageForFilter(String packageName,
12293                PackageParser.ActivityIntentInfo info) {
12294            return packageName.equals(info.activity.owner.packageName);
12295        }
12296
12297        @Override
12298        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12299                int match, int userId) {
12300            if (!sUserManager.exists(userId)) return null;
12301            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12302                return null;
12303            }
12304            final PackageParser.Activity activity = info.activity;
12305            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12306            if (ps == null) {
12307                return null;
12308            }
12309            final PackageUserState userState = ps.readUserState(userId);
12310            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
12311            if (ai == null) {
12312                return null;
12313            }
12314            final boolean matchVisibleToInstantApp =
12315                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12316            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12317            // throw out filters that aren't visible to ephemeral apps
12318            if (matchVisibleToInstantApp
12319                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12320                return null;
12321            }
12322            // throw out ephemeral filters if we're not explicitly requesting them
12323            if (!isInstantApp && userState.instantApp) {
12324                return null;
12325            }
12326            // throw out instant app filters if updates are available; will trigger
12327            // instant app resolution
12328            if (userState.instantApp && ps.isUpdateAvailable()) {
12329                return null;
12330            }
12331            final ResolveInfo res = new ResolveInfo();
12332            res.activityInfo = ai;
12333            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12334                res.filter = info;
12335            }
12336            if (info != null) {
12337                res.handleAllWebDataURI = info.handleAllWebDataURI();
12338            }
12339            res.priority = info.getPriority();
12340            res.preferredOrder = activity.owner.mPreferredOrder;
12341            //System.out.println("Result: " + res.activityInfo.className +
12342            //                   " = " + res.priority);
12343            res.match = match;
12344            res.isDefault = info.hasDefault;
12345            res.labelRes = info.labelRes;
12346            res.nonLocalizedLabel = info.nonLocalizedLabel;
12347            if (userNeedsBadging(userId)) {
12348                res.noResourceId = true;
12349            } else {
12350                res.icon = info.icon;
12351            }
12352            res.iconResourceId = info.icon;
12353            res.system = res.activityInfo.applicationInfo.isSystemApp();
12354            res.instantAppAvailable = userState.instantApp;
12355            return res;
12356        }
12357
12358        @Override
12359        protected void sortResults(List<ResolveInfo> results) {
12360            Collections.sort(results, mResolvePrioritySorter);
12361        }
12362
12363        @Override
12364        protected void dumpFilter(PrintWriter out, String prefix,
12365                PackageParser.ActivityIntentInfo filter) {
12366            out.print(prefix); out.print(
12367                    Integer.toHexString(System.identityHashCode(filter.activity)));
12368                    out.print(' ');
12369                    filter.activity.printComponentShortName(out);
12370                    out.print(" filter ");
12371                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12372        }
12373
12374        @Override
12375        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12376            return filter.activity;
12377        }
12378
12379        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12380            PackageParser.Activity activity = (PackageParser.Activity)label;
12381            out.print(prefix); out.print(
12382                    Integer.toHexString(System.identityHashCode(activity)));
12383                    out.print(' ');
12384                    activity.printComponentShortName(out);
12385            if (count > 1) {
12386                out.print(" ("); out.print(count); out.print(" filters)");
12387            }
12388            out.println();
12389        }
12390
12391        // Keys are String (activity class name), values are Activity.
12392        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12393                = new ArrayMap<ComponentName, PackageParser.Activity>();
12394        private int mFlags;
12395    }
12396
12397    private final class ServiceIntentResolver
12398            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12399        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12400                boolean defaultOnly, int userId) {
12401            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12402            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12403        }
12404
12405        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12406                int userId) {
12407            if (!sUserManager.exists(userId)) return null;
12408            mFlags = flags;
12409            return super.queryIntent(intent, resolvedType,
12410                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12411                    userId);
12412        }
12413
12414        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12415                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12416            if (!sUserManager.exists(userId)) return null;
12417            if (packageServices == null) {
12418                return null;
12419            }
12420            mFlags = flags;
12421            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12422            final int N = packageServices.size();
12423            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12424                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12425
12426            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12427            for (int i = 0; i < N; ++i) {
12428                intentFilters = packageServices.get(i).intents;
12429                if (intentFilters != null && intentFilters.size() > 0) {
12430                    PackageParser.ServiceIntentInfo[] array =
12431                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12432                    intentFilters.toArray(array);
12433                    listCut.add(array);
12434                }
12435            }
12436            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12437        }
12438
12439        public final void addService(PackageParser.Service s) {
12440            mServices.put(s.getComponentName(), s);
12441            if (DEBUG_SHOW_INFO) {
12442                Log.v(TAG, "  "
12443                        + (s.info.nonLocalizedLabel != null
12444                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12445                Log.v(TAG, "    Class=" + s.info.name);
12446            }
12447            final int NI = s.intents.size();
12448            int j;
12449            for (j=0; j<NI; j++) {
12450                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12451                if (DEBUG_SHOW_INFO) {
12452                    Log.v(TAG, "    IntentFilter:");
12453                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12454                }
12455                if (!intent.debugCheck()) {
12456                    Log.w(TAG, "==> For Service " + s.info.name);
12457                }
12458                addFilter(intent);
12459            }
12460        }
12461
12462        public final void removeService(PackageParser.Service s) {
12463            mServices.remove(s.getComponentName());
12464            if (DEBUG_SHOW_INFO) {
12465                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12466                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12467                Log.v(TAG, "    Class=" + s.info.name);
12468            }
12469            final int NI = s.intents.size();
12470            int j;
12471            for (j=0; j<NI; j++) {
12472                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12473                if (DEBUG_SHOW_INFO) {
12474                    Log.v(TAG, "    IntentFilter:");
12475                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12476                }
12477                removeFilter(intent);
12478            }
12479        }
12480
12481        @Override
12482        protected boolean allowFilterResult(
12483                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12484            ServiceInfo filterSi = filter.service.info;
12485            for (int i=dest.size()-1; i>=0; i--) {
12486                ServiceInfo destAi = dest.get(i).serviceInfo;
12487                if (destAi.name == filterSi.name
12488                        && destAi.packageName == filterSi.packageName) {
12489                    return false;
12490                }
12491            }
12492            return true;
12493        }
12494
12495        @Override
12496        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12497            return new PackageParser.ServiceIntentInfo[size];
12498        }
12499
12500        @Override
12501        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12502            if (!sUserManager.exists(userId)) return true;
12503            PackageParser.Package p = filter.service.owner;
12504            if (p != null) {
12505                PackageSetting ps = (PackageSetting)p.mExtras;
12506                if (ps != null) {
12507                    // System apps are never considered stopped for purposes of
12508                    // filtering, because there may be no way for the user to
12509                    // actually re-launch them.
12510                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12511                            && ps.getStopped(userId);
12512                }
12513            }
12514            return false;
12515        }
12516
12517        @Override
12518        protected boolean isPackageForFilter(String packageName,
12519                PackageParser.ServiceIntentInfo info) {
12520            return packageName.equals(info.service.owner.packageName);
12521        }
12522
12523        @Override
12524        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12525                int match, int userId) {
12526            if (!sUserManager.exists(userId)) return null;
12527            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12528            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12529                return null;
12530            }
12531            final PackageParser.Service service = info.service;
12532            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12533            if (ps == null) {
12534                return null;
12535            }
12536            final PackageUserState userState = ps.readUserState(userId);
12537            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12538                    userState, userId);
12539            if (si == null) {
12540                return null;
12541            }
12542            final boolean matchVisibleToInstantApp =
12543                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12544            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12545            // throw out filters that aren't visible to ephemeral apps
12546            if (matchVisibleToInstantApp
12547                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12548                return null;
12549            }
12550            // throw out ephemeral filters if we're not explicitly requesting them
12551            if (!isInstantApp && userState.instantApp) {
12552                return null;
12553            }
12554            // throw out instant app filters if updates are available; will trigger
12555            // instant app resolution
12556            if (userState.instantApp && ps.isUpdateAvailable()) {
12557                return null;
12558            }
12559            final ResolveInfo res = new ResolveInfo();
12560            res.serviceInfo = si;
12561            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12562                res.filter = filter;
12563            }
12564            res.priority = info.getPriority();
12565            res.preferredOrder = service.owner.mPreferredOrder;
12566            res.match = match;
12567            res.isDefault = info.hasDefault;
12568            res.labelRes = info.labelRes;
12569            res.nonLocalizedLabel = info.nonLocalizedLabel;
12570            res.icon = info.icon;
12571            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12572            return res;
12573        }
12574
12575        @Override
12576        protected void sortResults(List<ResolveInfo> results) {
12577            Collections.sort(results, mResolvePrioritySorter);
12578        }
12579
12580        @Override
12581        protected void dumpFilter(PrintWriter out, String prefix,
12582                PackageParser.ServiceIntentInfo filter) {
12583            out.print(prefix); out.print(
12584                    Integer.toHexString(System.identityHashCode(filter.service)));
12585                    out.print(' ');
12586                    filter.service.printComponentShortName(out);
12587                    out.print(" filter ");
12588                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12589        }
12590
12591        @Override
12592        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12593            return filter.service;
12594        }
12595
12596        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12597            PackageParser.Service service = (PackageParser.Service)label;
12598            out.print(prefix); out.print(
12599                    Integer.toHexString(System.identityHashCode(service)));
12600                    out.print(' ');
12601                    service.printComponentShortName(out);
12602            if (count > 1) {
12603                out.print(" ("); out.print(count); out.print(" filters)");
12604            }
12605            out.println();
12606        }
12607
12608//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12609//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12610//            final List<ResolveInfo> retList = Lists.newArrayList();
12611//            while (i.hasNext()) {
12612//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12613//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12614//                    retList.add(resolveInfo);
12615//                }
12616//            }
12617//            return retList;
12618//        }
12619
12620        // Keys are String (activity class name), values are Activity.
12621        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12622                = new ArrayMap<ComponentName, PackageParser.Service>();
12623        private int mFlags;
12624    }
12625
12626    private final class ProviderIntentResolver
12627            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12628        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12629                boolean defaultOnly, int userId) {
12630            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12631            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12632        }
12633
12634        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12635                int userId) {
12636            if (!sUserManager.exists(userId))
12637                return null;
12638            mFlags = flags;
12639            return super.queryIntent(intent, resolvedType,
12640                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12641                    userId);
12642        }
12643
12644        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12645                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12646            if (!sUserManager.exists(userId))
12647                return null;
12648            if (packageProviders == null) {
12649                return null;
12650            }
12651            mFlags = flags;
12652            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12653            final int N = packageProviders.size();
12654            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12655                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12656
12657            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12658            for (int i = 0; i < N; ++i) {
12659                intentFilters = packageProviders.get(i).intents;
12660                if (intentFilters != null && intentFilters.size() > 0) {
12661                    PackageParser.ProviderIntentInfo[] array =
12662                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12663                    intentFilters.toArray(array);
12664                    listCut.add(array);
12665                }
12666            }
12667            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12668        }
12669
12670        public final void addProvider(PackageParser.Provider p) {
12671            if (mProviders.containsKey(p.getComponentName())) {
12672                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12673                return;
12674            }
12675
12676            mProviders.put(p.getComponentName(), p);
12677            if (DEBUG_SHOW_INFO) {
12678                Log.v(TAG, "  "
12679                        + (p.info.nonLocalizedLabel != null
12680                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12681                Log.v(TAG, "    Class=" + p.info.name);
12682            }
12683            final int NI = p.intents.size();
12684            int j;
12685            for (j = 0; j < NI; j++) {
12686                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12687                if (DEBUG_SHOW_INFO) {
12688                    Log.v(TAG, "    IntentFilter:");
12689                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12690                }
12691                if (!intent.debugCheck()) {
12692                    Log.w(TAG, "==> For Provider " + p.info.name);
12693                }
12694                addFilter(intent);
12695            }
12696        }
12697
12698        public final void removeProvider(PackageParser.Provider p) {
12699            mProviders.remove(p.getComponentName());
12700            if (DEBUG_SHOW_INFO) {
12701                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12702                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12703                Log.v(TAG, "    Class=" + p.info.name);
12704            }
12705            final int NI = p.intents.size();
12706            int j;
12707            for (j = 0; j < NI; j++) {
12708                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12709                if (DEBUG_SHOW_INFO) {
12710                    Log.v(TAG, "    IntentFilter:");
12711                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12712                }
12713                removeFilter(intent);
12714            }
12715        }
12716
12717        @Override
12718        protected boolean allowFilterResult(
12719                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12720            ProviderInfo filterPi = filter.provider.info;
12721            for (int i = dest.size() - 1; i >= 0; i--) {
12722                ProviderInfo destPi = dest.get(i).providerInfo;
12723                if (destPi.name == filterPi.name
12724                        && destPi.packageName == filterPi.packageName) {
12725                    return false;
12726                }
12727            }
12728            return true;
12729        }
12730
12731        @Override
12732        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12733            return new PackageParser.ProviderIntentInfo[size];
12734        }
12735
12736        @Override
12737        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12738            if (!sUserManager.exists(userId))
12739                return true;
12740            PackageParser.Package p = filter.provider.owner;
12741            if (p != null) {
12742                PackageSetting ps = (PackageSetting) p.mExtras;
12743                if (ps != null) {
12744                    // System apps are never considered stopped for purposes of
12745                    // filtering, because there may be no way for the user to
12746                    // actually re-launch them.
12747                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12748                            && ps.getStopped(userId);
12749                }
12750            }
12751            return false;
12752        }
12753
12754        @Override
12755        protected boolean isPackageForFilter(String packageName,
12756                PackageParser.ProviderIntentInfo info) {
12757            return packageName.equals(info.provider.owner.packageName);
12758        }
12759
12760        @Override
12761        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12762                int match, int userId) {
12763            if (!sUserManager.exists(userId))
12764                return null;
12765            final PackageParser.ProviderIntentInfo info = filter;
12766            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12767                return null;
12768            }
12769            final PackageParser.Provider provider = info.provider;
12770            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12771            if (ps == null) {
12772                return null;
12773            }
12774            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12775                    ps.readUserState(userId), userId);
12776            if (pi == null) {
12777                return null;
12778            }
12779            final ResolveInfo res = new ResolveInfo();
12780            res.providerInfo = pi;
12781            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12782                res.filter = filter;
12783            }
12784            res.priority = info.getPriority();
12785            res.preferredOrder = provider.owner.mPreferredOrder;
12786            res.match = match;
12787            res.isDefault = info.hasDefault;
12788            res.labelRes = info.labelRes;
12789            res.nonLocalizedLabel = info.nonLocalizedLabel;
12790            res.icon = info.icon;
12791            res.system = res.providerInfo.applicationInfo.isSystemApp();
12792            return res;
12793        }
12794
12795        @Override
12796        protected void sortResults(List<ResolveInfo> results) {
12797            Collections.sort(results, mResolvePrioritySorter);
12798        }
12799
12800        @Override
12801        protected void dumpFilter(PrintWriter out, String prefix,
12802                PackageParser.ProviderIntentInfo filter) {
12803            out.print(prefix);
12804            out.print(
12805                    Integer.toHexString(System.identityHashCode(filter.provider)));
12806            out.print(' ');
12807            filter.provider.printComponentShortName(out);
12808            out.print(" filter ");
12809            out.println(Integer.toHexString(System.identityHashCode(filter)));
12810        }
12811
12812        @Override
12813        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12814            return filter.provider;
12815        }
12816
12817        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12818            PackageParser.Provider provider = (PackageParser.Provider)label;
12819            out.print(prefix); out.print(
12820                    Integer.toHexString(System.identityHashCode(provider)));
12821                    out.print(' ');
12822                    provider.printComponentShortName(out);
12823            if (count > 1) {
12824                out.print(" ("); out.print(count); out.print(" filters)");
12825            }
12826            out.println();
12827        }
12828
12829        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12830                = new ArrayMap<ComponentName, PackageParser.Provider>();
12831        private int mFlags;
12832    }
12833
12834    static final class EphemeralIntentResolver
12835            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12836        /**
12837         * The result that has the highest defined order. Ordering applies on a
12838         * per-package basis. Mapping is from package name to Pair of order and
12839         * EphemeralResolveInfo.
12840         * <p>
12841         * NOTE: This is implemented as a field variable for convenience and efficiency.
12842         * By having a field variable, we're able to track filter ordering as soon as
12843         * a non-zero order is defined. Otherwise, multiple loops across the result set
12844         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12845         * this needs to be contained entirely within {@link #filterResults}.
12846         */
12847        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12848
12849        @Override
12850        protected AuxiliaryResolveInfo[] newArray(int size) {
12851            return new AuxiliaryResolveInfo[size];
12852        }
12853
12854        @Override
12855        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12856            return true;
12857        }
12858
12859        @Override
12860        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12861                int userId) {
12862            if (!sUserManager.exists(userId)) {
12863                return null;
12864            }
12865            final String packageName = responseObj.resolveInfo.getPackageName();
12866            final Integer order = responseObj.getOrder();
12867            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12868                    mOrderResult.get(packageName);
12869            // ordering is enabled and this item's order isn't high enough
12870            if (lastOrderResult != null && lastOrderResult.first >= order) {
12871                return null;
12872            }
12873            final InstantAppResolveInfo res = responseObj.resolveInfo;
12874            if (order > 0) {
12875                // non-zero order, enable ordering
12876                mOrderResult.put(packageName, new Pair<>(order, res));
12877            }
12878            return responseObj;
12879        }
12880
12881        @Override
12882        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12883            // only do work if ordering is enabled [most of the time it won't be]
12884            if (mOrderResult.size() == 0) {
12885                return;
12886            }
12887            int resultSize = results.size();
12888            for (int i = 0; i < resultSize; i++) {
12889                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12890                final String packageName = info.getPackageName();
12891                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12892                if (savedInfo == null) {
12893                    // package doesn't having ordering
12894                    continue;
12895                }
12896                if (savedInfo.second == info) {
12897                    // circled back to the highest ordered item; remove from order list
12898                    mOrderResult.remove(savedInfo);
12899                    if (mOrderResult.size() == 0) {
12900                        // no more ordered items
12901                        break;
12902                    }
12903                    continue;
12904                }
12905                // item has a worse order, remove it from the result list
12906                results.remove(i);
12907                resultSize--;
12908                i--;
12909            }
12910        }
12911    }
12912
12913    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12914            new Comparator<ResolveInfo>() {
12915        public int compare(ResolveInfo r1, ResolveInfo r2) {
12916            int v1 = r1.priority;
12917            int v2 = r2.priority;
12918            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12919            if (v1 != v2) {
12920                return (v1 > v2) ? -1 : 1;
12921            }
12922            v1 = r1.preferredOrder;
12923            v2 = r2.preferredOrder;
12924            if (v1 != v2) {
12925                return (v1 > v2) ? -1 : 1;
12926            }
12927            if (r1.isDefault != r2.isDefault) {
12928                return r1.isDefault ? -1 : 1;
12929            }
12930            v1 = r1.match;
12931            v2 = r2.match;
12932            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12933            if (v1 != v2) {
12934                return (v1 > v2) ? -1 : 1;
12935            }
12936            if (r1.system != r2.system) {
12937                return r1.system ? -1 : 1;
12938            }
12939            if (r1.activityInfo != null) {
12940                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12941            }
12942            if (r1.serviceInfo != null) {
12943                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12944            }
12945            if (r1.providerInfo != null) {
12946                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12947            }
12948            return 0;
12949        }
12950    };
12951
12952    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12953            new Comparator<ProviderInfo>() {
12954        public int compare(ProviderInfo p1, ProviderInfo p2) {
12955            final int v1 = p1.initOrder;
12956            final int v2 = p2.initOrder;
12957            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12958        }
12959    };
12960
12961    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12962            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12963            final int[] userIds) {
12964        mHandler.post(new Runnable() {
12965            @Override
12966            public void run() {
12967                try {
12968                    final IActivityManager am = ActivityManager.getService();
12969                    if (am == null) return;
12970                    final int[] resolvedUserIds;
12971                    if (userIds == null) {
12972                        resolvedUserIds = am.getRunningUserIds();
12973                    } else {
12974                        resolvedUserIds = userIds;
12975                    }
12976                    for (int id : resolvedUserIds) {
12977                        final Intent intent = new Intent(action,
12978                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12979                        if (extras != null) {
12980                            intent.putExtras(extras);
12981                        }
12982                        if (targetPkg != null) {
12983                            intent.setPackage(targetPkg);
12984                        }
12985                        // Modify the UID when posting to other users
12986                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12987                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12988                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12989                            intent.putExtra(Intent.EXTRA_UID, uid);
12990                        }
12991                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12992                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12993                        if (DEBUG_BROADCASTS) {
12994                            RuntimeException here = new RuntimeException("here");
12995                            here.fillInStackTrace();
12996                            Slog.d(TAG, "Sending to user " + id + ": "
12997                                    + intent.toShortString(false, true, false, false)
12998                                    + " " + intent.getExtras(), here);
12999                        }
13000                        am.broadcastIntent(null, intent, null, finishedReceiver,
13001                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13002                                null, finishedReceiver != null, false, id);
13003                    }
13004                } catch (RemoteException ex) {
13005                }
13006            }
13007        });
13008    }
13009
13010    /**
13011     * Check if the external storage media is available. This is true if there
13012     * is a mounted external storage medium or if the external storage is
13013     * emulated.
13014     */
13015    private boolean isExternalMediaAvailable() {
13016        return mMediaMounted || Environment.isExternalStorageEmulated();
13017    }
13018
13019    @Override
13020    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13021        // writer
13022        synchronized (mPackages) {
13023            if (!isExternalMediaAvailable()) {
13024                // If the external storage is no longer mounted at this point,
13025                // the caller may not have been able to delete all of this
13026                // packages files and can not delete any more.  Bail.
13027                return null;
13028            }
13029            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13030            if (lastPackage != null) {
13031                pkgs.remove(lastPackage);
13032            }
13033            if (pkgs.size() > 0) {
13034                return pkgs.get(0);
13035            }
13036        }
13037        return null;
13038    }
13039
13040    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13041        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13042                userId, andCode ? 1 : 0, packageName);
13043        if (mSystemReady) {
13044            msg.sendToTarget();
13045        } else {
13046            if (mPostSystemReadyMessages == null) {
13047                mPostSystemReadyMessages = new ArrayList<>();
13048            }
13049            mPostSystemReadyMessages.add(msg);
13050        }
13051    }
13052
13053    void startCleaningPackages() {
13054        // reader
13055        if (!isExternalMediaAvailable()) {
13056            return;
13057        }
13058        synchronized (mPackages) {
13059            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13060                return;
13061            }
13062        }
13063        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13064        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13065        IActivityManager am = ActivityManager.getService();
13066        if (am != null) {
13067            int dcsUid = -1;
13068            synchronized (mPackages) {
13069                if (!mDefaultContainerWhitelisted) {
13070                    mDefaultContainerWhitelisted = true;
13071                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13072                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13073                }
13074            }
13075            try {
13076                if (dcsUid > 0) {
13077                    am.backgroundWhitelistUid(dcsUid);
13078                }
13079                am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(),
13080                        UserHandle.USER_SYSTEM);
13081            } catch (RemoteException e) {
13082            }
13083        }
13084    }
13085
13086    @Override
13087    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13088            int installFlags, String installerPackageName, int userId) {
13089        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13090
13091        final int callingUid = Binder.getCallingUid();
13092        enforceCrossUserPermission(callingUid, userId,
13093                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13094
13095        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13096            try {
13097                if (observer != null) {
13098                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13099                }
13100            } catch (RemoteException re) {
13101            }
13102            return;
13103        }
13104
13105        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13106            installFlags |= PackageManager.INSTALL_FROM_ADB;
13107
13108        } else {
13109            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13110            // about installerPackageName.
13111
13112            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13113            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13114        }
13115
13116        UserHandle user;
13117        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13118            user = UserHandle.ALL;
13119        } else {
13120            user = new UserHandle(userId);
13121        }
13122
13123        // Only system components can circumvent runtime permissions when installing.
13124        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13125                && mContext.checkCallingOrSelfPermission(Manifest.permission
13126                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13127            throw new SecurityException("You need the "
13128                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13129                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13130        }
13131
13132        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13133                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13134            throw new IllegalArgumentException(
13135                    "New installs into ASEC containers no longer supported");
13136        }
13137
13138        final File originFile = new File(originPath);
13139        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13140
13141        final Message msg = mHandler.obtainMessage(INIT_COPY);
13142        final VerificationInfo verificationInfo = new VerificationInfo(
13143                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13144        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13145                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13146                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13147                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13148        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13149        msg.obj = params;
13150
13151        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13152                System.identityHashCode(msg.obj));
13153        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13154                System.identityHashCode(msg.obj));
13155
13156        mHandler.sendMessage(msg);
13157    }
13158
13159
13160    /**
13161     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13162     * it is acting on behalf on an enterprise or the user).
13163     *
13164     * Note that the ordering of the conditionals in this method is important. The checks we perform
13165     * are as follows, in this order:
13166     *
13167     * 1) If the install is being performed by a system app, we can trust the app to have set the
13168     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13169     *    what it is.
13170     * 2) If the install is being performed by a device or profile owner app, the install reason
13171     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13172     *    set the install reason correctly. If the app targets an older SDK version where install
13173     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13174     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13175     * 3) In all other cases, the install is being performed by a regular app that is neither part
13176     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13177     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13178     *    set to enterprise policy and if so, change it to unknown instead.
13179     */
13180    private int fixUpInstallReason(String installerPackageName, int installerUid,
13181            int installReason) {
13182        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13183                == PERMISSION_GRANTED) {
13184            // If the install is being performed by a system app, we trust that app to have set the
13185            // install reason correctly.
13186            return installReason;
13187        }
13188
13189        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13190            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13191        if (dpm != null) {
13192            ComponentName owner = null;
13193            try {
13194                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13195                if (owner == null) {
13196                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13197                }
13198            } catch (RemoteException e) {
13199            }
13200            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13201                // If the install is being performed by a device or profile owner, the install
13202                // reason should be enterprise policy.
13203                return PackageManager.INSTALL_REASON_POLICY;
13204            }
13205        }
13206
13207        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13208            // If the install is being performed by a regular app (i.e. neither system app nor
13209            // device or profile owner), we have no reason to believe that the app is acting on
13210            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13211            // change it to unknown instead.
13212            return PackageManager.INSTALL_REASON_UNKNOWN;
13213        }
13214
13215        // If the install is being performed by a regular app and the install reason was set to any
13216        // value but enterprise policy, leave the install reason unchanged.
13217        return installReason;
13218    }
13219
13220    void installStage(String packageName, File stagedDir, String stagedCid,
13221            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13222            String installerPackageName, int installerUid, UserHandle user,
13223            Certificate[][] certificates) {
13224        if (DEBUG_EPHEMERAL) {
13225            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13226                Slog.d(TAG, "Ephemeral install of " + packageName);
13227            }
13228        }
13229        final VerificationInfo verificationInfo = new VerificationInfo(
13230                sessionParams.originatingUri, sessionParams.referrerUri,
13231                sessionParams.originatingUid, installerUid);
13232
13233        final OriginInfo origin;
13234        if (stagedDir != null) {
13235            origin = OriginInfo.fromStagedFile(stagedDir);
13236        } else {
13237            origin = OriginInfo.fromStagedContainer(stagedCid);
13238        }
13239
13240        final Message msg = mHandler.obtainMessage(INIT_COPY);
13241        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13242                sessionParams.installReason);
13243        final InstallParams params = new InstallParams(origin, null, observer,
13244                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13245                verificationInfo, user, sessionParams.abiOverride,
13246                sessionParams.grantedRuntimePermissions, certificates, installReason);
13247        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13248        msg.obj = params;
13249
13250        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13251                System.identityHashCode(msg.obj));
13252        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13253                System.identityHashCode(msg.obj));
13254
13255        mHandler.sendMessage(msg);
13256    }
13257
13258    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13259            int userId) {
13260        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13261        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13262    }
13263
13264    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13265            int appId, int... userIds) {
13266        if (ArrayUtils.isEmpty(userIds)) {
13267            return;
13268        }
13269        Bundle extras = new Bundle(1);
13270        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13271        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13272
13273        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_ADDED, packageName,
13274                extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, userIds);
13275        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13276                extras, 0, null, null, userIds);
13277        if (isSystem) {
13278            mHandler.post(() -> {
13279                        for (int userId : userIds) {
13280                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13281                        }
13282                    }
13283            );
13284        }
13285    }
13286
13287    /**
13288     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13289     * automatically without needing an explicit launch.
13290     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13291     */
13292    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13293        // If user is not running, the app didn't miss any broadcast
13294        if (!mUserManagerInternal.isUserRunning(userId)) {
13295            return;
13296        }
13297        final IActivityManager am = ActivityManager.getService();
13298        try {
13299            // Deliver LOCKED_BOOT_COMPLETED first
13300            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13301                    .setPackage(packageName);
13302            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13303            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13304                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13305
13306            // Deliver BOOT_COMPLETED only if user is unlocked
13307            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13308                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13309                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13310                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13311            }
13312        } catch (RemoteException e) {
13313            throw e.rethrowFromSystemServer();
13314        }
13315    }
13316
13317    @Override
13318    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13319            int userId) {
13320        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13321        PackageSetting pkgSetting;
13322        final int uid = Binder.getCallingUid();
13323        enforceCrossUserPermission(uid, userId,
13324                true /* requireFullPermission */, true /* checkShell */,
13325                "setApplicationHiddenSetting for user " + userId);
13326
13327        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13328            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13329            return false;
13330        }
13331
13332        long callingId = Binder.clearCallingIdentity();
13333        try {
13334            boolean sendAdded = false;
13335            boolean sendRemoved = false;
13336            // writer
13337            synchronized (mPackages) {
13338                pkgSetting = mSettings.mPackages.get(packageName);
13339                if (pkgSetting == null) {
13340                    return false;
13341                }
13342                // Do not allow "android" is being disabled
13343                if ("android".equals(packageName)) {
13344                    Slog.w(TAG, "Cannot hide package: android");
13345                    return false;
13346                }
13347                // Cannot hide static shared libs as they are considered
13348                // a part of the using app (emulating static linking). Also
13349                // static libs are installed always on internal storage.
13350                PackageParser.Package pkg = mPackages.get(packageName);
13351                if (pkg != null && pkg.staticSharedLibName != null) {
13352                    Slog.w(TAG, "Cannot hide package: " + packageName
13353                            + " providing static shared library: "
13354                            + pkg.staticSharedLibName);
13355                    return false;
13356                }
13357                // Only allow protected packages to hide themselves.
13358                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13359                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13360                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13361                    return false;
13362                }
13363
13364                if (pkgSetting.getHidden(userId) != hidden) {
13365                    pkgSetting.setHidden(hidden, userId);
13366                    mSettings.writePackageRestrictionsLPr(userId);
13367                    if (hidden) {
13368                        sendRemoved = true;
13369                    } else {
13370                        sendAdded = true;
13371                    }
13372                }
13373            }
13374            if (sendAdded) {
13375                sendPackageAddedForUser(packageName, pkgSetting, userId);
13376                return true;
13377            }
13378            if (sendRemoved) {
13379                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13380                        "hiding pkg");
13381                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13382                return true;
13383            }
13384        } finally {
13385            Binder.restoreCallingIdentity(callingId);
13386        }
13387        return false;
13388    }
13389
13390    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13391            int userId) {
13392        final PackageRemovedInfo info = new PackageRemovedInfo();
13393        info.removedPackage = packageName;
13394        info.removedUsers = new int[] {userId};
13395        info.broadcastUsers = new int[] {userId};
13396        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13397        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13398    }
13399
13400    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13401        if (pkgList.length > 0) {
13402            Bundle extras = new Bundle(1);
13403            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13404
13405            sendPackageBroadcast(
13406                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13407                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13408                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13409                    new int[] {userId});
13410        }
13411    }
13412
13413    /**
13414     * Returns true if application is not found or there was an error. Otherwise it returns
13415     * the hidden state of the package for the given user.
13416     */
13417    @Override
13418    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13419        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13420        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13421                true /* requireFullPermission */, false /* checkShell */,
13422                "getApplicationHidden for user " + userId);
13423        PackageSetting pkgSetting;
13424        long callingId = Binder.clearCallingIdentity();
13425        try {
13426            // writer
13427            synchronized (mPackages) {
13428                pkgSetting = mSettings.mPackages.get(packageName);
13429                if (pkgSetting == null) {
13430                    return true;
13431                }
13432                return pkgSetting.getHidden(userId);
13433            }
13434        } finally {
13435            Binder.restoreCallingIdentity(callingId);
13436        }
13437    }
13438
13439    /**
13440     * @hide
13441     */
13442    @Override
13443    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13444            int installReason) {
13445        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13446                null);
13447        PackageSetting pkgSetting;
13448        final int uid = Binder.getCallingUid();
13449        enforceCrossUserPermission(uid, userId,
13450                true /* requireFullPermission */, true /* checkShell */,
13451                "installExistingPackage for user " + userId);
13452        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13453            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13454        }
13455
13456        long callingId = Binder.clearCallingIdentity();
13457        try {
13458            boolean installed = false;
13459            final boolean instantApp =
13460                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13461            final boolean fullApp =
13462                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13463
13464            // writer
13465            synchronized (mPackages) {
13466                pkgSetting = mSettings.mPackages.get(packageName);
13467                if (pkgSetting == null) {
13468                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13469                }
13470                if (!pkgSetting.getInstalled(userId)) {
13471                    pkgSetting.setInstalled(true, userId);
13472                    pkgSetting.setHidden(false, userId);
13473                    pkgSetting.setInstallReason(installReason, userId);
13474                    mSettings.writePackageRestrictionsLPr(userId);
13475                    mSettings.writeKernelMappingLPr(pkgSetting);
13476                    installed = true;
13477                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13478                    // upgrade app from instant to full; we don't allow app downgrade
13479                    installed = true;
13480                }
13481                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13482            }
13483
13484            if (installed) {
13485                if (pkgSetting.pkg != null) {
13486                    synchronized (mInstallLock) {
13487                        // We don't need to freeze for a brand new install
13488                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13489                    }
13490                }
13491                sendPackageAddedForUser(packageName, pkgSetting, userId);
13492                synchronized (mPackages) {
13493                    updateSequenceNumberLP(packageName, new int[]{ userId });
13494                }
13495            }
13496        } finally {
13497            Binder.restoreCallingIdentity(callingId);
13498        }
13499
13500        return PackageManager.INSTALL_SUCCEEDED;
13501    }
13502
13503    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13504            boolean instantApp, boolean fullApp) {
13505        // no state specified; do nothing
13506        if (!instantApp && !fullApp) {
13507            return;
13508        }
13509        if (userId != UserHandle.USER_ALL) {
13510            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13511                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13512            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13513                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13514            }
13515        } else {
13516            for (int currentUserId : sUserManager.getUserIds()) {
13517                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13518                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13519                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13520                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13521                }
13522            }
13523        }
13524    }
13525
13526    boolean isUserRestricted(int userId, String restrictionKey) {
13527        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13528        if (restrictions.getBoolean(restrictionKey, false)) {
13529            Log.w(TAG, "User is restricted: " + restrictionKey);
13530            return true;
13531        }
13532        return false;
13533    }
13534
13535    @Override
13536    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13537            int userId) {
13538        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13539        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13540                true /* requireFullPermission */, true /* checkShell */,
13541                "setPackagesSuspended for user " + userId);
13542
13543        if (ArrayUtils.isEmpty(packageNames)) {
13544            return packageNames;
13545        }
13546
13547        // List of package names for whom the suspended state has changed.
13548        List<String> changedPackages = new ArrayList<>(packageNames.length);
13549        // List of package names for whom the suspended state is not set as requested in this
13550        // method.
13551        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13552        long callingId = Binder.clearCallingIdentity();
13553        try {
13554            for (int i = 0; i < packageNames.length; i++) {
13555                String packageName = packageNames[i];
13556                boolean changed = false;
13557                final int appId;
13558                synchronized (mPackages) {
13559                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13560                    if (pkgSetting == null) {
13561                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13562                                + "\". Skipping suspending/un-suspending.");
13563                        unactionedPackages.add(packageName);
13564                        continue;
13565                    }
13566                    appId = pkgSetting.appId;
13567                    if (pkgSetting.getSuspended(userId) != suspended) {
13568                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13569                            unactionedPackages.add(packageName);
13570                            continue;
13571                        }
13572                        pkgSetting.setSuspended(suspended, userId);
13573                        mSettings.writePackageRestrictionsLPr(userId);
13574                        changed = true;
13575                        changedPackages.add(packageName);
13576                    }
13577                }
13578
13579                if (changed && suspended) {
13580                    killApplication(packageName, UserHandle.getUid(userId, appId),
13581                            "suspending package");
13582                }
13583            }
13584        } finally {
13585            Binder.restoreCallingIdentity(callingId);
13586        }
13587
13588        if (!changedPackages.isEmpty()) {
13589            sendPackagesSuspendedForUser(changedPackages.toArray(
13590                    new String[changedPackages.size()]), userId, suspended);
13591        }
13592
13593        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13594    }
13595
13596    @Override
13597    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13598        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13599                true /* requireFullPermission */, false /* checkShell */,
13600                "isPackageSuspendedForUser for user " + userId);
13601        synchronized (mPackages) {
13602            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13603            if (pkgSetting == null) {
13604                throw new IllegalArgumentException("Unknown target package: " + packageName);
13605            }
13606            return pkgSetting.getSuspended(userId);
13607        }
13608    }
13609
13610    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13611        if (isPackageDeviceAdmin(packageName, userId)) {
13612            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13613                    + "\": has an active device admin");
13614            return false;
13615        }
13616
13617        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13618        if (packageName.equals(activeLauncherPackageName)) {
13619            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13620                    + "\": contains the active launcher");
13621            return false;
13622        }
13623
13624        if (packageName.equals(mRequiredInstallerPackage)) {
13625            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13626                    + "\": required for package installation");
13627            return false;
13628        }
13629
13630        if (packageName.equals(mRequiredUninstallerPackage)) {
13631            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13632                    + "\": required for package uninstallation");
13633            return false;
13634        }
13635
13636        if (packageName.equals(mRequiredVerifierPackage)) {
13637            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13638                    + "\": required for package verification");
13639            return false;
13640        }
13641
13642        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13643            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13644                    + "\": is the default dialer");
13645            return false;
13646        }
13647
13648        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13649            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13650                    + "\": protected package");
13651            return false;
13652        }
13653
13654        // Cannot suspend static shared libs as they are considered
13655        // a part of the using app (emulating static linking). Also
13656        // static libs are installed always on internal storage.
13657        PackageParser.Package pkg = mPackages.get(packageName);
13658        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13659            Slog.w(TAG, "Cannot suspend package: " + packageName
13660                    + " providing static shared library: "
13661                    + pkg.staticSharedLibName);
13662            return false;
13663        }
13664
13665        return true;
13666    }
13667
13668    private String getActiveLauncherPackageName(int userId) {
13669        Intent intent = new Intent(Intent.ACTION_MAIN);
13670        intent.addCategory(Intent.CATEGORY_HOME);
13671        ResolveInfo resolveInfo = resolveIntent(
13672                intent,
13673                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13674                PackageManager.MATCH_DEFAULT_ONLY,
13675                userId);
13676
13677        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13678    }
13679
13680    private String getDefaultDialerPackageName(int userId) {
13681        synchronized (mPackages) {
13682            return mSettings.getDefaultDialerPackageNameLPw(userId);
13683        }
13684    }
13685
13686    @Override
13687    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13688        mContext.enforceCallingOrSelfPermission(
13689                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13690                "Only package verification agents can verify applications");
13691
13692        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13693        final PackageVerificationResponse response = new PackageVerificationResponse(
13694                verificationCode, Binder.getCallingUid());
13695        msg.arg1 = id;
13696        msg.obj = response;
13697        mHandler.sendMessage(msg);
13698    }
13699
13700    @Override
13701    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13702            long millisecondsToDelay) {
13703        mContext.enforceCallingOrSelfPermission(
13704                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13705                "Only package verification agents can extend verification timeouts");
13706
13707        final PackageVerificationState state = mPendingVerification.get(id);
13708        final PackageVerificationResponse response = new PackageVerificationResponse(
13709                verificationCodeAtTimeout, Binder.getCallingUid());
13710
13711        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13712            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13713        }
13714        if (millisecondsToDelay < 0) {
13715            millisecondsToDelay = 0;
13716        }
13717        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13718                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13719            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13720        }
13721
13722        if ((state != null) && !state.timeoutExtended()) {
13723            state.extendTimeout();
13724
13725            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13726            msg.arg1 = id;
13727            msg.obj = response;
13728            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13729        }
13730    }
13731
13732    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13733            int verificationCode, UserHandle user) {
13734        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13735        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13736        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13737        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13738        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13739
13740        mContext.sendBroadcastAsUser(intent, user,
13741                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13742    }
13743
13744    private ComponentName matchComponentForVerifier(String packageName,
13745            List<ResolveInfo> receivers) {
13746        ActivityInfo targetReceiver = null;
13747
13748        final int NR = receivers.size();
13749        for (int i = 0; i < NR; i++) {
13750            final ResolveInfo info = receivers.get(i);
13751            if (info.activityInfo == null) {
13752                continue;
13753            }
13754
13755            if (packageName.equals(info.activityInfo.packageName)) {
13756                targetReceiver = info.activityInfo;
13757                break;
13758            }
13759        }
13760
13761        if (targetReceiver == null) {
13762            return null;
13763        }
13764
13765        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13766    }
13767
13768    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13769            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13770        if (pkgInfo.verifiers.length == 0) {
13771            return null;
13772        }
13773
13774        final int N = pkgInfo.verifiers.length;
13775        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13776        for (int i = 0; i < N; i++) {
13777            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13778
13779            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13780                    receivers);
13781            if (comp == null) {
13782                continue;
13783            }
13784
13785            final int verifierUid = getUidForVerifier(verifierInfo);
13786            if (verifierUid == -1) {
13787                continue;
13788            }
13789
13790            if (DEBUG_VERIFY) {
13791                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13792                        + " with the correct signature");
13793            }
13794            sufficientVerifiers.add(comp);
13795            verificationState.addSufficientVerifier(verifierUid);
13796        }
13797
13798        return sufficientVerifiers;
13799    }
13800
13801    private int getUidForVerifier(VerifierInfo verifierInfo) {
13802        synchronized (mPackages) {
13803            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13804            if (pkg == null) {
13805                return -1;
13806            } else if (pkg.mSignatures.length != 1) {
13807                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13808                        + " has more than one signature; ignoring");
13809                return -1;
13810            }
13811
13812            /*
13813             * If the public key of the package's signature does not match
13814             * our expected public key, then this is a different package and
13815             * we should skip.
13816             */
13817
13818            final byte[] expectedPublicKey;
13819            try {
13820                final Signature verifierSig = pkg.mSignatures[0];
13821                final PublicKey publicKey = verifierSig.getPublicKey();
13822                expectedPublicKey = publicKey.getEncoded();
13823            } catch (CertificateException e) {
13824                return -1;
13825            }
13826
13827            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13828
13829            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13830                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13831                        + " does not have the expected public key; ignoring");
13832                return -1;
13833            }
13834
13835            return pkg.applicationInfo.uid;
13836        }
13837    }
13838
13839    @Override
13840    public void finishPackageInstall(int token, boolean didLaunch) {
13841        enforceSystemOrRoot("Only the system is allowed to finish installs");
13842
13843        if (DEBUG_INSTALL) {
13844            Slog.v(TAG, "BM finishing package install for " + token);
13845        }
13846        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13847
13848        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13849        mHandler.sendMessage(msg);
13850    }
13851
13852    /**
13853     * Get the verification agent timeout.
13854     *
13855     * @return verification timeout in milliseconds
13856     */
13857    private long getVerificationTimeout() {
13858        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13859                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13860                DEFAULT_VERIFICATION_TIMEOUT);
13861    }
13862
13863    /**
13864     * Get the default verification agent response code.
13865     *
13866     * @return default verification response code
13867     */
13868    private int getDefaultVerificationResponse() {
13869        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13870                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13871                DEFAULT_VERIFICATION_RESPONSE);
13872    }
13873
13874    /**
13875     * Check whether or not package verification has been enabled.
13876     *
13877     * @return true if verification should be performed
13878     */
13879    private boolean isVerificationEnabled(int userId, int installFlags) {
13880        if (!DEFAULT_VERIFY_ENABLE) {
13881            return false;
13882        }
13883
13884        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13885
13886        // Check if installing from ADB
13887        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13888            // Do not run verification in a test harness environment
13889            if (ActivityManager.isRunningInTestHarness()) {
13890                return false;
13891            }
13892            if (ensureVerifyAppsEnabled) {
13893                return true;
13894            }
13895            // Check if the developer does not want package verification for ADB installs
13896            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13897                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13898                return false;
13899            }
13900        }
13901
13902        if (ensureVerifyAppsEnabled) {
13903            return true;
13904        }
13905
13906        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13907                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13908    }
13909
13910    @Override
13911    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13912            throws RemoteException {
13913        mContext.enforceCallingOrSelfPermission(
13914                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13915                "Only intentfilter verification agents can verify applications");
13916
13917        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13918        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13919                Binder.getCallingUid(), verificationCode, failedDomains);
13920        msg.arg1 = id;
13921        msg.obj = response;
13922        mHandler.sendMessage(msg);
13923    }
13924
13925    @Override
13926    public int getIntentVerificationStatus(String packageName, int userId) {
13927        synchronized (mPackages) {
13928            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13929        }
13930    }
13931
13932    @Override
13933    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13934        mContext.enforceCallingOrSelfPermission(
13935                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13936
13937        boolean result = false;
13938        synchronized (mPackages) {
13939            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13940        }
13941        if (result) {
13942            scheduleWritePackageRestrictionsLocked(userId);
13943        }
13944        return result;
13945    }
13946
13947    @Override
13948    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13949            String packageName) {
13950        synchronized (mPackages) {
13951            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13952        }
13953    }
13954
13955    @Override
13956    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13957        if (TextUtils.isEmpty(packageName)) {
13958            return ParceledListSlice.emptyList();
13959        }
13960        synchronized (mPackages) {
13961            PackageParser.Package pkg = mPackages.get(packageName);
13962            if (pkg == null || pkg.activities == null) {
13963                return ParceledListSlice.emptyList();
13964            }
13965            final int count = pkg.activities.size();
13966            ArrayList<IntentFilter> result = new ArrayList<>();
13967            for (int n=0; n<count; n++) {
13968                PackageParser.Activity activity = pkg.activities.get(n);
13969                if (activity.intents != null && activity.intents.size() > 0) {
13970                    result.addAll(activity.intents);
13971                }
13972            }
13973            return new ParceledListSlice<>(result);
13974        }
13975    }
13976
13977    @Override
13978    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13979        mContext.enforceCallingOrSelfPermission(
13980                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13981
13982        synchronized (mPackages) {
13983            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13984            if (packageName != null) {
13985                result |= updateIntentVerificationStatus(packageName,
13986                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13987                        userId);
13988                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13989                        packageName, userId);
13990            }
13991            return result;
13992        }
13993    }
13994
13995    @Override
13996    public String getDefaultBrowserPackageName(int userId) {
13997        synchronized (mPackages) {
13998            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13999        }
14000    }
14001
14002    /**
14003     * Get the "allow unknown sources" setting.
14004     *
14005     * @return the current "allow unknown sources" setting
14006     */
14007    private int getUnknownSourcesSettings() {
14008        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14009                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14010                -1);
14011    }
14012
14013    @Override
14014    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14015        final int uid = Binder.getCallingUid();
14016        // writer
14017        synchronized (mPackages) {
14018            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14019            if (targetPackageSetting == null) {
14020                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14021            }
14022
14023            PackageSetting installerPackageSetting;
14024            if (installerPackageName != null) {
14025                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14026                if (installerPackageSetting == null) {
14027                    throw new IllegalArgumentException("Unknown installer package: "
14028                            + installerPackageName);
14029                }
14030            } else {
14031                installerPackageSetting = null;
14032            }
14033
14034            Signature[] callerSignature;
14035            Object obj = mSettings.getUserIdLPr(uid);
14036            if (obj != null) {
14037                if (obj instanceof SharedUserSetting) {
14038                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14039                } else if (obj instanceof PackageSetting) {
14040                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14041                } else {
14042                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14043                }
14044            } else {
14045                throw new SecurityException("Unknown calling UID: " + uid);
14046            }
14047
14048            // Verify: can't set installerPackageName to a package that is
14049            // not signed with the same cert as the caller.
14050            if (installerPackageSetting != null) {
14051                if (compareSignatures(callerSignature,
14052                        installerPackageSetting.signatures.mSignatures)
14053                        != PackageManager.SIGNATURE_MATCH) {
14054                    throw new SecurityException(
14055                            "Caller does not have same cert as new installer package "
14056                            + installerPackageName);
14057                }
14058            }
14059
14060            // Verify: if target already has an installer package, it must
14061            // be signed with the same cert as the caller.
14062            if (targetPackageSetting.installerPackageName != null) {
14063                PackageSetting setting = mSettings.mPackages.get(
14064                        targetPackageSetting.installerPackageName);
14065                // If the currently set package isn't valid, then it's always
14066                // okay to change it.
14067                if (setting != null) {
14068                    if (compareSignatures(callerSignature,
14069                            setting.signatures.mSignatures)
14070                            != PackageManager.SIGNATURE_MATCH) {
14071                        throw new SecurityException(
14072                                "Caller does not have same cert as old installer package "
14073                                + targetPackageSetting.installerPackageName);
14074                    }
14075                }
14076            }
14077
14078            // Okay!
14079            targetPackageSetting.installerPackageName = installerPackageName;
14080            if (installerPackageName != null) {
14081                mSettings.mInstallerPackages.add(installerPackageName);
14082            }
14083            scheduleWriteSettingsLocked();
14084        }
14085    }
14086
14087    @Override
14088    public void setApplicationCategoryHint(String packageName, int categoryHint,
14089            String callerPackageName) {
14090        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14091                callerPackageName);
14092        synchronized (mPackages) {
14093            PackageSetting ps = mSettings.mPackages.get(packageName);
14094            if (ps == null) {
14095                throw new IllegalArgumentException("Unknown target package " + packageName);
14096            }
14097
14098            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14099                throw new IllegalArgumentException("Calling package " + callerPackageName
14100                        + " is not installer for " + packageName);
14101            }
14102
14103            if (ps.categoryHint != categoryHint) {
14104                ps.categoryHint = categoryHint;
14105                scheduleWriteSettingsLocked();
14106            }
14107        }
14108    }
14109
14110    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14111        // Queue up an async operation since the package installation may take a little while.
14112        mHandler.post(new Runnable() {
14113            public void run() {
14114                mHandler.removeCallbacks(this);
14115                 // Result object to be returned
14116                PackageInstalledInfo res = new PackageInstalledInfo();
14117                res.setReturnCode(currentStatus);
14118                res.uid = -1;
14119                res.pkg = null;
14120                res.removedInfo = null;
14121                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14122                    args.doPreInstall(res.returnCode);
14123                    synchronized (mInstallLock) {
14124                        installPackageTracedLI(args, res);
14125                    }
14126                    args.doPostInstall(res.returnCode, res.uid);
14127                }
14128
14129                // A restore should be performed at this point if (a) the install
14130                // succeeded, (b) the operation is not an update, and (c) the new
14131                // package has not opted out of backup participation.
14132                final boolean update = res.removedInfo != null
14133                        && res.removedInfo.removedPackage != null;
14134                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14135                boolean doRestore = !update
14136                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14137
14138                // Set up the post-install work request bookkeeping.  This will be used
14139                // and cleaned up by the post-install event handling regardless of whether
14140                // there's a restore pass performed.  Token values are >= 1.
14141                int token;
14142                if (mNextInstallToken < 0) mNextInstallToken = 1;
14143                token = mNextInstallToken++;
14144
14145                PostInstallData data = new PostInstallData(args, res);
14146                mRunningInstalls.put(token, data);
14147                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14148
14149                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14150                    // Pass responsibility to the Backup Manager.  It will perform a
14151                    // restore if appropriate, then pass responsibility back to the
14152                    // Package Manager to run the post-install observer callbacks
14153                    // and broadcasts.
14154                    IBackupManager bm = IBackupManager.Stub.asInterface(
14155                            ServiceManager.getService(Context.BACKUP_SERVICE));
14156                    if (bm != null) {
14157                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14158                                + " to BM for possible restore");
14159                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14160                        try {
14161                            // TODO: http://b/22388012
14162                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14163                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14164                            } else {
14165                                doRestore = false;
14166                            }
14167                        } catch (RemoteException e) {
14168                            // can't happen; the backup manager is local
14169                        } catch (Exception e) {
14170                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14171                            doRestore = false;
14172                        }
14173                    } else {
14174                        Slog.e(TAG, "Backup Manager not found!");
14175                        doRestore = false;
14176                    }
14177                }
14178
14179                if (!doRestore) {
14180                    // No restore possible, or the Backup Manager was mysteriously not
14181                    // available -- just fire the post-install work request directly.
14182                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14183
14184                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14185
14186                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14187                    mHandler.sendMessage(msg);
14188                }
14189            }
14190        });
14191    }
14192
14193    /**
14194     * Callback from PackageSettings whenever an app is first transitioned out of the
14195     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14196     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14197     * here whether the app is the target of an ongoing install, and only send the
14198     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14199     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14200     * handling.
14201     */
14202    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14203        // Serialize this with the rest of the install-process message chain.  In the
14204        // restore-at-install case, this Runnable will necessarily run before the
14205        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14206        // are coherent.  In the non-restore case, the app has already completed install
14207        // and been launched through some other means, so it is not in a problematic
14208        // state for observers to see the FIRST_LAUNCH signal.
14209        mHandler.post(new Runnable() {
14210            @Override
14211            public void run() {
14212                for (int i = 0; i < mRunningInstalls.size(); i++) {
14213                    final PostInstallData data = mRunningInstalls.valueAt(i);
14214                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14215                        continue;
14216                    }
14217                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14218                        // right package; but is it for the right user?
14219                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14220                            if (userId == data.res.newUsers[uIndex]) {
14221                                if (DEBUG_BACKUP) {
14222                                    Slog.i(TAG, "Package " + pkgName
14223                                            + " being restored so deferring FIRST_LAUNCH");
14224                                }
14225                                return;
14226                            }
14227                        }
14228                    }
14229                }
14230                // didn't find it, so not being restored
14231                if (DEBUG_BACKUP) {
14232                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14233                }
14234                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14235            }
14236        });
14237    }
14238
14239    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14240        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14241                installerPkg, null, userIds);
14242    }
14243
14244    private abstract class HandlerParams {
14245        private static final int MAX_RETRIES = 4;
14246
14247        /**
14248         * Number of times startCopy() has been attempted and had a non-fatal
14249         * error.
14250         */
14251        private int mRetries = 0;
14252
14253        /** User handle for the user requesting the information or installation. */
14254        private final UserHandle mUser;
14255        String traceMethod;
14256        int traceCookie;
14257
14258        HandlerParams(UserHandle user) {
14259            mUser = user;
14260        }
14261
14262        UserHandle getUser() {
14263            return mUser;
14264        }
14265
14266        HandlerParams setTraceMethod(String traceMethod) {
14267            this.traceMethod = traceMethod;
14268            return this;
14269        }
14270
14271        HandlerParams setTraceCookie(int traceCookie) {
14272            this.traceCookie = traceCookie;
14273            return this;
14274        }
14275
14276        final boolean startCopy() {
14277            boolean res;
14278            try {
14279                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14280
14281                if (++mRetries > MAX_RETRIES) {
14282                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14283                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14284                    handleServiceError();
14285                    return false;
14286                } else {
14287                    handleStartCopy();
14288                    res = true;
14289                }
14290            } catch (RemoteException e) {
14291                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14292                mHandler.sendEmptyMessage(MCS_RECONNECT);
14293                res = false;
14294            }
14295            handleReturnCode();
14296            return res;
14297        }
14298
14299        final void serviceError() {
14300            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14301            handleServiceError();
14302            handleReturnCode();
14303        }
14304
14305        abstract void handleStartCopy() throws RemoteException;
14306        abstract void handleServiceError();
14307        abstract void handleReturnCode();
14308    }
14309
14310    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14311        for (File path : paths) {
14312            try {
14313                mcs.clearDirectory(path.getAbsolutePath());
14314            } catch (RemoteException e) {
14315            }
14316        }
14317    }
14318
14319    static class OriginInfo {
14320        /**
14321         * Location where install is coming from, before it has been
14322         * copied/renamed into place. This could be a single monolithic APK
14323         * file, or a cluster directory. This location may be untrusted.
14324         */
14325        final File file;
14326        final String cid;
14327
14328        /**
14329         * Flag indicating that {@link #file} or {@link #cid} has already been
14330         * staged, meaning downstream users don't need to defensively copy the
14331         * contents.
14332         */
14333        final boolean staged;
14334
14335        /**
14336         * Flag indicating that {@link #file} or {@link #cid} is an already
14337         * installed app that is being moved.
14338         */
14339        final boolean existing;
14340
14341        final String resolvedPath;
14342        final File resolvedFile;
14343
14344        static OriginInfo fromNothing() {
14345            return new OriginInfo(null, null, false, false);
14346        }
14347
14348        static OriginInfo fromUntrustedFile(File file) {
14349            return new OriginInfo(file, null, false, false);
14350        }
14351
14352        static OriginInfo fromExistingFile(File file) {
14353            return new OriginInfo(file, null, false, true);
14354        }
14355
14356        static OriginInfo fromStagedFile(File file) {
14357            return new OriginInfo(file, null, true, false);
14358        }
14359
14360        static OriginInfo fromStagedContainer(String cid) {
14361            return new OriginInfo(null, cid, true, false);
14362        }
14363
14364        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14365            this.file = file;
14366            this.cid = cid;
14367            this.staged = staged;
14368            this.existing = existing;
14369
14370            if (cid != null) {
14371                resolvedPath = PackageHelper.getSdDir(cid);
14372                resolvedFile = new File(resolvedPath);
14373            } else if (file != null) {
14374                resolvedPath = file.getAbsolutePath();
14375                resolvedFile = file;
14376            } else {
14377                resolvedPath = null;
14378                resolvedFile = null;
14379            }
14380        }
14381    }
14382
14383    static class MoveInfo {
14384        final int moveId;
14385        final String fromUuid;
14386        final String toUuid;
14387        final String packageName;
14388        final String dataAppName;
14389        final int appId;
14390        final String seinfo;
14391        final int targetSdkVersion;
14392
14393        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14394                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14395            this.moveId = moveId;
14396            this.fromUuid = fromUuid;
14397            this.toUuid = toUuid;
14398            this.packageName = packageName;
14399            this.dataAppName = dataAppName;
14400            this.appId = appId;
14401            this.seinfo = seinfo;
14402            this.targetSdkVersion = targetSdkVersion;
14403        }
14404    }
14405
14406    static class VerificationInfo {
14407        /** A constant used to indicate that a uid value is not present. */
14408        public static final int NO_UID = -1;
14409
14410        /** URI referencing where the package was downloaded from. */
14411        final Uri originatingUri;
14412
14413        /** HTTP referrer URI associated with the originatingURI. */
14414        final Uri referrer;
14415
14416        /** UID of the application that the install request originated from. */
14417        final int originatingUid;
14418
14419        /** UID of application requesting the install */
14420        final int installerUid;
14421
14422        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14423            this.originatingUri = originatingUri;
14424            this.referrer = referrer;
14425            this.originatingUid = originatingUid;
14426            this.installerUid = installerUid;
14427        }
14428    }
14429
14430    class InstallParams extends HandlerParams {
14431        final OriginInfo origin;
14432        final MoveInfo move;
14433        final IPackageInstallObserver2 observer;
14434        int installFlags;
14435        final String installerPackageName;
14436        final String volumeUuid;
14437        private InstallArgs mArgs;
14438        private int mRet;
14439        final String packageAbiOverride;
14440        final String[] grantedRuntimePermissions;
14441        final VerificationInfo verificationInfo;
14442        final Certificate[][] certificates;
14443        final int installReason;
14444
14445        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14446                int installFlags, String installerPackageName, String volumeUuid,
14447                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14448                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14449            super(user);
14450            this.origin = origin;
14451            this.move = move;
14452            this.observer = observer;
14453            this.installFlags = installFlags;
14454            this.installerPackageName = installerPackageName;
14455            this.volumeUuid = volumeUuid;
14456            this.verificationInfo = verificationInfo;
14457            this.packageAbiOverride = packageAbiOverride;
14458            this.grantedRuntimePermissions = grantedPermissions;
14459            this.certificates = certificates;
14460            this.installReason = installReason;
14461        }
14462
14463        @Override
14464        public String toString() {
14465            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14466                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14467        }
14468
14469        private int installLocationPolicy(PackageInfoLite pkgLite) {
14470            String packageName = pkgLite.packageName;
14471            int installLocation = pkgLite.installLocation;
14472            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14473            // reader
14474            synchronized (mPackages) {
14475                // Currently installed package which the new package is attempting to replace or
14476                // null if no such package is installed.
14477                PackageParser.Package installedPkg = mPackages.get(packageName);
14478                // Package which currently owns the data which the new package will own if installed.
14479                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14480                // will be null whereas dataOwnerPkg will contain information about the package
14481                // which was uninstalled while keeping its data.
14482                PackageParser.Package dataOwnerPkg = installedPkg;
14483                if (dataOwnerPkg  == null) {
14484                    PackageSetting ps = mSettings.mPackages.get(packageName);
14485                    if (ps != null) {
14486                        dataOwnerPkg = ps.pkg;
14487                    }
14488                }
14489
14490                if (dataOwnerPkg != null) {
14491                    // If installed, the package will get access to data left on the device by its
14492                    // predecessor. As a security measure, this is permited only if this is not a
14493                    // version downgrade or if the predecessor package is marked as debuggable and
14494                    // a downgrade is explicitly requested.
14495                    //
14496                    // On debuggable platform builds, downgrades are permitted even for
14497                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14498                    // not offer security guarantees and thus it's OK to disable some security
14499                    // mechanisms to make debugging/testing easier on those builds. However, even on
14500                    // debuggable builds downgrades of packages are permitted only if requested via
14501                    // installFlags. This is because we aim to keep the behavior of debuggable
14502                    // platform builds as close as possible to the behavior of non-debuggable
14503                    // platform builds.
14504                    final boolean downgradeRequested =
14505                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14506                    final boolean packageDebuggable =
14507                                (dataOwnerPkg.applicationInfo.flags
14508                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14509                    final boolean downgradePermitted =
14510                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14511                    if (!downgradePermitted) {
14512                        try {
14513                            checkDowngrade(dataOwnerPkg, pkgLite);
14514                        } catch (PackageManagerException e) {
14515                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14516                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14517                        }
14518                    }
14519                }
14520
14521                if (installedPkg != null) {
14522                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14523                        // Check for updated system application.
14524                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14525                            if (onSd) {
14526                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14527                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14528                            }
14529                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14530                        } else {
14531                            if (onSd) {
14532                                // Install flag overrides everything.
14533                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14534                            }
14535                            // If current upgrade specifies particular preference
14536                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14537                                // Application explicitly specified internal.
14538                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14539                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14540                                // App explictly prefers external. Let policy decide
14541                            } else {
14542                                // Prefer previous location
14543                                if (isExternal(installedPkg)) {
14544                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14545                                }
14546                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14547                            }
14548                        }
14549                    } else {
14550                        // Invalid install. Return error code
14551                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14552                    }
14553                }
14554            }
14555            // All the special cases have been taken care of.
14556            // Return result based on recommended install location.
14557            if (onSd) {
14558                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14559            }
14560            return pkgLite.recommendedInstallLocation;
14561        }
14562
14563        /*
14564         * Invoke remote method to get package information and install
14565         * location values. Override install location based on default
14566         * policy if needed and then create install arguments based
14567         * on the install location.
14568         */
14569        public void handleStartCopy() throws RemoteException {
14570            int ret = PackageManager.INSTALL_SUCCEEDED;
14571
14572            // If we're already staged, we've firmly committed to an install location
14573            if (origin.staged) {
14574                if (origin.file != null) {
14575                    installFlags |= PackageManager.INSTALL_INTERNAL;
14576                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14577                } else if (origin.cid != null) {
14578                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14579                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14580                } else {
14581                    throw new IllegalStateException("Invalid stage location");
14582                }
14583            }
14584
14585            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14586            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14587            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14588            PackageInfoLite pkgLite = null;
14589
14590            if (onInt && onSd) {
14591                // Check if both bits are set.
14592                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14593                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14594            } else if (onSd && ephemeral) {
14595                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14596                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14597            } else {
14598                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14599                        packageAbiOverride);
14600
14601                if (DEBUG_EPHEMERAL && ephemeral) {
14602                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14603                }
14604
14605                /*
14606                 * If we have too little free space, try to free cache
14607                 * before giving up.
14608                 */
14609                if (!origin.staged && pkgLite.recommendedInstallLocation
14610                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14611                    // TODO: focus freeing disk space on the target device
14612                    final StorageManager storage = StorageManager.from(mContext);
14613                    final long lowThreshold = storage.getStorageLowBytes(
14614                            Environment.getDataDirectory());
14615
14616                    final long sizeBytes = mContainerService.calculateInstalledSize(
14617                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14618
14619                    try {
14620                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14621                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14622                                installFlags, packageAbiOverride);
14623                    } catch (InstallerException e) {
14624                        Slog.w(TAG, "Failed to free cache", e);
14625                    }
14626
14627                    /*
14628                     * The cache free must have deleted the file we
14629                     * downloaded to install.
14630                     *
14631                     * TODO: fix the "freeCache" call to not delete
14632                     *       the file we care about.
14633                     */
14634                    if (pkgLite.recommendedInstallLocation
14635                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14636                        pkgLite.recommendedInstallLocation
14637                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14638                    }
14639                }
14640            }
14641
14642            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14643                int loc = pkgLite.recommendedInstallLocation;
14644                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14645                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14646                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14647                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14648                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14649                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14650                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14651                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14652                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14653                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14654                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14655                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14656                } else {
14657                    // Override with defaults if needed.
14658                    loc = installLocationPolicy(pkgLite);
14659                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14660                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14661                    } else if (!onSd && !onInt) {
14662                        // Override install location with flags
14663                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14664                            // Set the flag to install on external media.
14665                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14666                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14667                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14668                            if (DEBUG_EPHEMERAL) {
14669                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14670                            }
14671                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14672                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14673                                    |PackageManager.INSTALL_INTERNAL);
14674                        } else {
14675                            // Make sure the flag for installing on external
14676                            // media is unset
14677                            installFlags |= PackageManager.INSTALL_INTERNAL;
14678                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14679                        }
14680                    }
14681                }
14682            }
14683
14684            final InstallArgs args = createInstallArgs(this);
14685            mArgs = args;
14686
14687            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14688                // TODO: http://b/22976637
14689                // Apps installed for "all" users use the device owner to verify the app
14690                UserHandle verifierUser = getUser();
14691                if (verifierUser == UserHandle.ALL) {
14692                    verifierUser = UserHandle.SYSTEM;
14693                }
14694
14695                /*
14696                 * Determine if we have any installed package verifiers. If we
14697                 * do, then we'll defer to them to verify the packages.
14698                 */
14699                final int requiredUid = mRequiredVerifierPackage == null ? -1
14700                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14701                                verifierUser.getIdentifier());
14702                if (!origin.existing && requiredUid != -1
14703                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14704                    final Intent verification = new Intent(
14705                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14706                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14707                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14708                            PACKAGE_MIME_TYPE);
14709                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14710
14711                    // Query all live verifiers based on current user state
14712                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14713                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14714
14715                    if (DEBUG_VERIFY) {
14716                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14717                                + verification.toString() + " with " + pkgLite.verifiers.length
14718                                + " optional verifiers");
14719                    }
14720
14721                    final int verificationId = mPendingVerificationToken++;
14722
14723                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14724
14725                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14726                            installerPackageName);
14727
14728                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14729                            installFlags);
14730
14731                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14732                            pkgLite.packageName);
14733
14734                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14735                            pkgLite.versionCode);
14736
14737                    if (verificationInfo != null) {
14738                        if (verificationInfo.originatingUri != null) {
14739                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14740                                    verificationInfo.originatingUri);
14741                        }
14742                        if (verificationInfo.referrer != null) {
14743                            verification.putExtra(Intent.EXTRA_REFERRER,
14744                                    verificationInfo.referrer);
14745                        }
14746                        if (verificationInfo.originatingUid >= 0) {
14747                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14748                                    verificationInfo.originatingUid);
14749                        }
14750                        if (verificationInfo.installerUid >= 0) {
14751                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14752                                    verificationInfo.installerUid);
14753                        }
14754                    }
14755
14756                    final PackageVerificationState verificationState = new PackageVerificationState(
14757                            requiredUid, args);
14758
14759                    mPendingVerification.append(verificationId, verificationState);
14760
14761                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14762                            receivers, verificationState);
14763
14764                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14765                    final long idleDuration = getVerificationTimeout();
14766
14767                    /*
14768                     * If any sufficient verifiers were listed in the package
14769                     * manifest, attempt to ask them.
14770                     */
14771                    if (sufficientVerifiers != null) {
14772                        final int N = sufficientVerifiers.size();
14773                        if (N == 0) {
14774                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14775                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14776                        } else {
14777                            for (int i = 0; i < N; i++) {
14778                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14779                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14780                                        verifierComponent.getPackageName(), idleDuration,
14781                                        verifierUser.getIdentifier(), false, "package verifier");
14782
14783                                final Intent sufficientIntent = new Intent(verification);
14784                                sufficientIntent.setComponent(verifierComponent);
14785                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14786                            }
14787                        }
14788                    }
14789
14790                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14791                            mRequiredVerifierPackage, receivers);
14792                    if (ret == PackageManager.INSTALL_SUCCEEDED
14793                            && mRequiredVerifierPackage != null) {
14794                        Trace.asyncTraceBegin(
14795                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14796                        /*
14797                         * Send the intent to the required verification agent,
14798                         * but only start the verification timeout after the
14799                         * target BroadcastReceivers have run.
14800                         */
14801                        verification.setComponent(requiredVerifierComponent);
14802                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14803                                mRequiredVerifierPackage, idleDuration,
14804                                verifierUser.getIdentifier(), false, "package verifier");
14805                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14806                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14807                                new BroadcastReceiver() {
14808                                    @Override
14809                                    public void onReceive(Context context, Intent intent) {
14810                                        final Message msg = mHandler
14811                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14812                                        msg.arg1 = verificationId;
14813                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14814                                    }
14815                                }, null, 0, null, null);
14816
14817                        /*
14818                         * We don't want the copy to proceed until verification
14819                         * succeeds, so null out this field.
14820                         */
14821                        mArgs = null;
14822                    }
14823                } else {
14824                    /*
14825                     * No package verification is enabled, so immediately start
14826                     * the remote call to initiate copy using temporary file.
14827                     */
14828                    ret = args.copyApk(mContainerService, true);
14829                }
14830            }
14831
14832            mRet = ret;
14833        }
14834
14835        @Override
14836        void handleReturnCode() {
14837            // If mArgs is null, then MCS couldn't be reached. When it
14838            // reconnects, it will try again to install. At that point, this
14839            // will succeed.
14840            if (mArgs != null) {
14841                processPendingInstall(mArgs, mRet);
14842            }
14843        }
14844
14845        @Override
14846        void handleServiceError() {
14847            mArgs = createInstallArgs(this);
14848            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14849        }
14850
14851        public boolean isForwardLocked() {
14852            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14853        }
14854    }
14855
14856    /**
14857     * Used during creation of InstallArgs
14858     *
14859     * @param installFlags package installation flags
14860     * @return true if should be installed on external storage
14861     */
14862    private static boolean installOnExternalAsec(int installFlags) {
14863        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14864            return false;
14865        }
14866        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14867            return true;
14868        }
14869        return false;
14870    }
14871
14872    /**
14873     * Used during creation of InstallArgs
14874     *
14875     * @param installFlags package installation flags
14876     * @return true if should be installed as forward locked
14877     */
14878    private static boolean installForwardLocked(int installFlags) {
14879        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14880    }
14881
14882    private InstallArgs createInstallArgs(InstallParams params) {
14883        if (params.move != null) {
14884            return new MoveInstallArgs(params);
14885        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14886            return new AsecInstallArgs(params);
14887        } else {
14888            return new FileInstallArgs(params);
14889        }
14890    }
14891
14892    /**
14893     * Create args that describe an existing installed package. Typically used
14894     * when cleaning up old installs, or used as a move source.
14895     */
14896    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14897            String resourcePath, String[] instructionSets) {
14898        final boolean isInAsec;
14899        if (installOnExternalAsec(installFlags)) {
14900            /* Apps on SD card are always in ASEC containers. */
14901            isInAsec = true;
14902        } else if (installForwardLocked(installFlags)
14903                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14904            /*
14905             * Forward-locked apps are only in ASEC containers if they're the
14906             * new style
14907             */
14908            isInAsec = true;
14909        } else {
14910            isInAsec = false;
14911        }
14912
14913        if (isInAsec) {
14914            return new AsecInstallArgs(codePath, instructionSets,
14915                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14916        } else {
14917            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14918        }
14919    }
14920
14921    static abstract class InstallArgs {
14922        /** @see InstallParams#origin */
14923        final OriginInfo origin;
14924        /** @see InstallParams#move */
14925        final MoveInfo move;
14926
14927        final IPackageInstallObserver2 observer;
14928        // Always refers to PackageManager flags only
14929        final int installFlags;
14930        final String installerPackageName;
14931        final String volumeUuid;
14932        final UserHandle user;
14933        final String abiOverride;
14934        final String[] installGrantPermissions;
14935        /** If non-null, drop an async trace when the install completes */
14936        final String traceMethod;
14937        final int traceCookie;
14938        final Certificate[][] certificates;
14939        final int installReason;
14940
14941        // The list of instruction sets supported by this app. This is currently
14942        // only used during the rmdex() phase to clean up resources. We can get rid of this
14943        // if we move dex files under the common app path.
14944        /* nullable */ String[] instructionSets;
14945
14946        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14947                int installFlags, String installerPackageName, String volumeUuid,
14948                UserHandle user, String[] instructionSets,
14949                String abiOverride, String[] installGrantPermissions,
14950                String traceMethod, int traceCookie, Certificate[][] certificates,
14951                int installReason) {
14952            this.origin = origin;
14953            this.move = move;
14954            this.installFlags = installFlags;
14955            this.observer = observer;
14956            this.installerPackageName = installerPackageName;
14957            this.volumeUuid = volumeUuid;
14958            this.user = user;
14959            this.instructionSets = instructionSets;
14960            this.abiOverride = abiOverride;
14961            this.installGrantPermissions = installGrantPermissions;
14962            this.traceMethod = traceMethod;
14963            this.traceCookie = traceCookie;
14964            this.certificates = certificates;
14965            this.installReason = installReason;
14966        }
14967
14968        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14969        abstract int doPreInstall(int status);
14970
14971        /**
14972         * Rename package into final resting place. All paths on the given
14973         * scanned package should be updated to reflect the rename.
14974         */
14975        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14976        abstract int doPostInstall(int status, int uid);
14977
14978        /** @see PackageSettingBase#codePathString */
14979        abstract String getCodePath();
14980        /** @see PackageSettingBase#resourcePathString */
14981        abstract String getResourcePath();
14982
14983        // Need installer lock especially for dex file removal.
14984        abstract void cleanUpResourcesLI();
14985        abstract boolean doPostDeleteLI(boolean delete);
14986
14987        /**
14988         * Called before the source arguments are copied. This is used mostly
14989         * for MoveParams when it needs to read the source file to put it in the
14990         * destination.
14991         */
14992        int doPreCopy() {
14993            return PackageManager.INSTALL_SUCCEEDED;
14994        }
14995
14996        /**
14997         * Called after the source arguments are copied. This is used mostly for
14998         * MoveParams when it needs to read the source file to put it in the
14999         * destination.
15000         */
15001        int doPostCopy(int uid) {
15002            return PackageManager.INSTALL_SUCCEEDED;
15003        }
15004
15005        protected boolean isFwdLocked() {
15006            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15007        }
15008
15009        protected boolean isExternalAsec() {
15010            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15011        }
15012
15013        protected boolean isEphemeral() {
15014            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15015        }
15016
15017        UserHandle getUser() {
15018            return user;
15019        }
15020    }
15021
15022    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15023        if (!allCodePaths.isEmpty()) {
15024            if (instructionSets == null) {
15025                throw new IllegalStateException("instructionSet == null");
15026            }
15027            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15028            for (String codePath : allCodePaths) {
15029                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15030                    try {
15031                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15032                    } catch (InstallerException ignored) {
15033                    }
15034                }
15035            }
15036        }
15037    }
15038
15039    /**
15040     * Logic to handle installation of non-ASEC applications, including copying
15041     * and renaming logic.
15042     */
15043    class FileInstallArgs extends InstallArgs {
15044        private File codeFile;
15045        private File resourceFile;
15046
15047        // Example topology:
15048        // /data/app/com.example/base.apk
15049        // /data/app/com.example/split_foo.apk
15050        // /data/app/com.example/lib/arm/libfoo.so
15051        // /data/app/com.example/lib/arm64/libfoo.so
15052        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15053
15054        /** New install */
15055        FileInstallArgs(InstallParams params) {
15056            super(params.origin, params.move, params.observer, params.installFlags,
15057                    params.installerPackageName, params.volumeUuid,
15058                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15059                    params.grantedRuntimePermissions,
15060                    params.traceMethod, params.traceCookie, params.certificates,
15061                    params.installReason);
15062            if (isFwdLocked()) {
15063                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15064            }
15065        }
15066
15067        /** Existing install */
15068        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15069            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15070                    null, null, null, 0, null /*certificates*/,
15071                    PackageManager.INSTALL_REASON_UNKNOWN);
15072            this.codeFile = (codePath != null) ? new File(codePath) : null;
15073            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15074        }
15075
15076        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15077            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15078            try {
15079                return doCopyApk(imcs, temp);
15080            } finally {
15081                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15082            }
15083        }
15084
15085        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15086            if (origin.staged) {
15087                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15088                codeFile = origin.file;
15089                resourceFile = origin.file;
15090                return PackageManager.INSTALL_SUCCEEDED;
15091            }
15092
15093            try {
15094                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15095                final File tempDir =
15096                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15097                codeFile = tempDir;
15098                resourceFile = tempDir;
15099            } catch (IOException e) {
15100                Slog.w(TAG, "Failed to create copy file: " + e);
15101                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15102            }
15103
15104            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15105                @Override
15106                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15107                    if (!FileUtils.isValidExtFilename(name)) {
15108                        throw new IllegalArgumentException("Invalid filename: " + name);
15109                    }
15110                    try {
15111                        final File file = new File(codeFile, name);
15112                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15113                                O_RDWR | O_CREAT, 0644);
15114                        Os.chmod(file.getAbsolutePath(), 0644);
15115                        return new ParcelFileDescriptor(fd);
15116                    } catch (ErrnoException e) {
15117                        throw new RemoteException("Failed to open: " + e.getMessage());
15118                    }
15119                }
15120            };
15121
15122            int ret = PackageManager.INSTALL_SUCCEEDED;
15123            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15124            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15125                Slog.e(TAG, "Failed to copy package");
15126                return ret;
15127            }
15128
15129            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15130            NativeLibraryHelper.Handle handle = null;
15131            try {
15132                handle = NativeLibraryHelper.Handle.create(codeFile);
15133                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15134                        abiOverride);
15135            } catch (IOException e) {
15136                Slog.e(TAG, "Copying native libraries failed", e);
15137                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15138            } finally {
15139                IoUtils.closeQuietly(handle);
15140            }
15141
15142            return ret;
15143        }
15144
15145        int doPreInstall(int status) {
15146            if (status != PackageManager.INSTALL_SUCCEEDED) {
15147                cleanUp();
15148            }
15149            return status;
15150        }
15151
15152        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15153            if (status != PackageManager.INSTALL_SUCCEEDED) {
15154                cleanUp();
15155                return false;
15156            }
15157
15158            final File targetDir = codeFile.getParentFile();
15159            final File beforeCodeFile = codeFile;
15160            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15161
15162            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15163            try {
15164                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15165            } catch (ErrnoException e) {
15166                Slog.w(TAG, "Failed to rename", e);
15167                return false;
15168            }
15169
15170            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15171                Slog.w(TAG, "Failed to restorecon");
15172                return false;
15173            }
15174
15175            // Reflect the rename internally
15176            codeFile = afterCodeFile;
15177            resourceFile = afterCodeFile;
15178
15179            // Reflect the rename in scanned details
15180            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15181            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15182                    afterCodeFile, pkg.baseCodePath));
15183            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15184                    afterCodeFile, pkg.splitCodePaths));
15185
15186            // Reflect the rename in app info
15187            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15188            pkg.setApplicationInfoCodePath(pkg.codePath);
15189            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15190            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15191            pkg.setApplicationInfoResourcePath(pkg.codePath);
15192            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15193            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15194
15195            return true;
15196        }
15197
15198        int doPostInstall(int status, int uid) {
15199            if (status != PackageManager.INSTALL_SUCCEEDED) {
15200                cleanUp();
15201            }
15202            return status;
15203        }
15204
15205        @Override
15206        String getCodePath() {
15207            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15208        }
15209
15210        @Override
15211        String getResourcePath() {
15212            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15213        }
15214
15215        private boolean cleanUp() {
15216            if (codeFile == null || !codeFile.exists()) {
15217                return false;
15218            }
15219
15220            removeCodePathLI(codeFile);
15221
15222            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15223                resourceFile.delete();
15224            }
15225
15226            return true;
15227        }
15228
15229        void cleanUpResourcesLI() {
15230            // Try enumerating all code paths before deleting
15231            List<String> allCodePaths = Collections.EMPTY_LIST;
15232            if (codeFile != null && codeFile.exists()) {
15233                try {
15234                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15235                    allCodePaths = pkg.getAllCodePaths();
15236                } catch (PackageParserException e) {
15237                    // Ignored; we tried our best
15238                }
15239            }
15240
15241            cleanUp();
15242            removeDexFiles(allCodePaths, instructionSets);
15243        }
15244
15245        boolean doPostDeleteLI(boolean delete) {
15246            // XXX err, shouldn't we respect the delete flag?
15247            cleanUpResourcesLI();
15248            return true;
15249        }
15250    }
15251
15252    private boolean isAsecExternal(String cid) {
15253        final String asecPath = PackageHelper.getSdFilesystem(cid);
15254        return !asecPath.startsWith(mAsecInternalPath);
15255    }
15256
15257    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15258            PackageManagerException {
15259        if (copyRet < 0) {
15260            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15261                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15262                throw new PackageManagerException(copyRet, message);
15263            }
15264        }
15265    }
15266
15267    /**
15268     * Extract the StorageManagerService "container ID" from the full code path of an
15269     * .apk.
15270     */
15271    static String cidFromCodePath(String fullCodePath) {
15272        int eidx = fullCodePath.lastIndexOf("/");
15273        String subStr1 = fullCodePath.substring(0, eidx);
15274        int sidx = subStr1.lastIndexOf("/");
15275        return subStr1.substring(sidx+1, eidx);
15276    }
15277
15278    /**
15279     * Logic to handle installation of ASEC applications, including copying and
15280     * renaming logic.
15281     */
15282    class AsecInstallArgs extends InstallArgs {
15283        static final String RES_FILE_NAME = "pkg.apk";
15284        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15285
15286        String cid;
15287        String packagePath;
15288        String resourcePath;
15289
15290        /** New install */
15291        AsecInstallArgs(InstallParams params) {
15292            super(params.origin, params.move, params.observer, params.installFlags,
15293                    params.installerPackageName, params.volumeUuid,
15294                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15295                    params.grantedRuntimePermissions,
15296                    params.traceMethod, params.traceCookie, params.certificates,
15297                    params.installReason);
15298        }
15299
15300        /** Existing install */
15301        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15302                        boolean isExternal, boolean isForwardLocked) {
15303            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15304                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15305                    instructionSets, null, null, null, 0, null /*certificates*/,
15306                    PackageManager.INSTALL_REASON_UNKNOWN);
15307            // Hackily pretend we're still looking at a full code path
15308            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15309                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15310            }
15311
15312            // Extract cid from fullCodePath
15313            int eidx = fullCodePath.lastIndexOf("/");
15314            String subStr1 = fullCodePath.substring(0, eidx);
15315            int sidx = subStr1.lastIndexOf("/");
15316            cid = subStr1.substring(sidx+1, eidx);
15317            setMountPath(subStr1);
15318        }
15319
15320        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15321            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15322                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15323                    instructionSets, null, null, null, 0, null /*certificates*/,
15324                    PackageManager.INSTALL_REASON_UNKNOWN);
15325            this.cid = cid;
15326            setMountPath(PackageHelper.getSdDir(cid));
15327        }
15328
15329        void createCopyFile() {
15330            cid = mInstallerService.allocateExternalStageCidLegacy();
15331        }
15332
15333        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15334            if (origin.staged && origin.cid != null) {
15335                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15336                cid = origin.cid;
15337                setMountPath(PackageHelper.getSdDir(cid));
15338                return PackageManager.INSTALL_SUCCEEDED;
15339            }
15340
15341            if (temp) {
15342                createCopyFile();
15343            } else {
15344                /*
15345                 * Pre-emptively destroy the container since it's destroyed if
15346                 * copying fails due to it existing anyway.
15347                 */
15348                PackageHelper.destroySdDir(cid);
15349            }
15350
15351            final String newMountPath = imcs.copyPackageToContainer(
15352                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15353                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15354
15355            if (newMountPath != null) {
15356                setMountPath(newMountPath);
15357                return PackageManager.INSTALL_SUCCEEDED;
15358            } else {
15359                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15360            }
15361        }
15362
15363        @Override
15364        String getCodePath() {
15365            return packagePath;
15366        }
15367
15368        @Override
15369        String getResourcePath() {
15370            return resourcePath;
15371        }
15372
15373        int doPreInstall(int status) {
15374            if (status != PackageManager.INSTALL_SUCCEEDED) {
15375                // Destroy container
15376                PackageHelper.destroySdDir(cid);
15377            } else {
15378                boolean mounted = PackageHelper.isContainerMounted(cid);
15379                if (!mounted) {
15380                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15381                            Process.SYSTEM_UID);
15382                    if (newMountPath != null) {
15383                        setMountPath(newMountPath);
15384                    } else {
15385                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15386                    }
15387                }
15388            }
15389            return status;
15390        }
15391
15392        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15393            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15394            String newMountPath = null;
15395            if (PackageHelper.isContainerMounted(cid)) {
15396                // Unmount the container
15397                if (!PackageHelper.unMountSdDir(cid)) {
15398                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15399                    return false;
15400                }
15401            }
15402            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15403                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15404                        " which might be stale. Will try to clean up.");
15405                // Clean up the stale container and proceed to recreate.
15406                if (!PackageHelper.destroySdDir(newCacheId)) {
15407                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15408                    return false;
15409                }
15410                // Successfully cleaned up stale container. Try to rename again.
15411                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15412                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15413                            + " inspite of cleaning it up.");
15414                    return false;
15415                }
15416            }
15417            if (!PackageHelper.isContainerMounted(newCacheId)) {
15418                Slog.w(TAG, "Mounting container " + newCacheId);
15419                newMountPath = PackageHelper.mountSdDir(newCacheId,
15420                        getEncryptKey(), Process.SYSTEM_UID);
15421            } else {
15422                newMountPath = PackageHelper.getSdDir(newCacheId);
15423            }
15424            if (newMountPath == null) {
15425                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15426                return false;
15427            }
15428            Log.i(TAG, "Succesfully renamed " + cid +
15429                    " to " + newCacheId +
15430                    " at new path: " + newMountPath);
15431            cid = newCacheId;
15432
15433            final File beforeCodeFile = new File(packagePath);
15434            setMountPath(newMountPath);
15435            final File afterCodeFile = new File(packagePath);
15436
15437            // Reflect the rename in scanned details
15438            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15439            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15440                    afterCodeFile, pkg.baseCodePath));
15441            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15442                    afterCodeFile, pkg.splitCodePaths));
15443
15444            // Reflect the rename in app info
15445            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15446            pkg.setApplicationInfoCodePath(pkg.codePath);
15447            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15448            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15449            pkg.setApplicationInfoResourcePath(pkg.codePath);
15450            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15451            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15452
15453            return true;
15454        }
15455
15456        private void setMountPath(String mountPath) {
15457            final File mountFile = new File(mountPath);
15458
15459            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15460            if (monolithicFile.exists()) {
15461                packagePath = monolithicFile.getAbsolutePath();
15462                if (isFwdLocked()) {
15463                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15464                } else {
15465                    resourcePath = packagePath;
15466                }
15467            } else {
15468                packagePath = mountFile.getAbsolutePath();
15469                resourcePath = packagePath;
15470            }
15471        }
15472
15473        int doPostInstall(int status, int uid) {
15474            if (status != PackageManager.INSTALL_SUCCEEDED) {
15475                cleanUp();
15476            } else {
15477                final int groupOwner;
15478                final String protectedFile;
15479                if (isFwdLocked()) {
15480                    groupOwner = UserHandle.getSharedAppGid(uid);
15481                    protectedFile = RES_FILE_NAME;
15482                } else {
15483                    groupOwner = -1;
15484                    protectedFile = null;
15485                }
15486
15487                if (uid < Process.FIRST_APPLICATION_UID
15488                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15489                    Slog.e(TAG, "Failed to finalize " + cid);
15490                    PackageHelper.destroySdDir(cid);
15491                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15492                }
15493
15494                boolean mounted = PackageHelper.isContainerMounted(cid);
15495                if (!mounted) {
15496                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15497                }
15498            }
15499            return status;
15500        }
15501
15502        private void cleanUp() {
15503            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15504
15505            // Destroy secure container
15506            PackageHelper.destroySdDir(cid);
15507        }
15508
15509        private List<String> getAllCodePaths() {
15510            final File codeFile = new File(getCodePath());
15511            if (codeFile != null && codeFile.exists()) {
15512                try {
15513                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15514                    return pkg.getAllCodePaths();
15515                } catch (PackageParserException e) {
15516                    // Ignored; we tried our best
15517                }
15518            }
15519            return Collections.EMPTY_LIST;
15520        }
15521
15522        void cleanUpResourcesLI() {
15523            // Enumerate all code paths before deleting
15524            cleanUpResourcesLI(getAllCodePaths());
15525        }
15526
15527        private void cleanUpResourcesLI(List<String> allCodePaths) {
15528            cleanUp();
15529            removeDexFiles(allCodePaths, instructionSets);
15530        }
15531
15532        String getPackageName() {
15533            return getAsecPackageName(cid);
15534        }
15535
15536        boolean doPostDeleteLI(boolean delete) {
15537            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15538            final List<String> allCodePaths = getAllCodePaths();
15539            boolean mounted = PackageHelper.isContainerMounted(cid);
15540            if (mounted) {
15541                // Unmount first
15542                if (PackageHelper.unMountSdDir(cid)) {
15543                    mounted = false;
15544                }
15545            }
15546            if (!mounted && delete) {
15547                cleanUpResourcesLI(allCodePaths);
15548            }
15549            return !mounted;
15550        }
15551
15552        @Override
15553        int doPreCopy() {
15554            if (isFwdLocked()) {
15555                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15556                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15557                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15558                }
15559            }
15560
15561            return PackageManager.INSTALL_SUCCEEDED;
15562        }
15563
15564        @Override
15565        int doPostCopy(int uid) {
15566            if (isFwdLocked()) {
15567                if (uid < Process.FIRST_APPLICATION_UID
15568                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15569                                RES_FILE_NAME)) {
15570                    Slog.e(TAG, "Failed to finalize " + cid);
15571                    PackageHelper.destroySdDir(cid);
15572                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15573                }
15574            }
15575
15576            return PackageManager.INSTALL_SUCCEEDED;
15577        }
15578    }
15579
15580    /**
15581     * Logic to handle movement of existing installed applications.
15582     */
15583    class MoveInstallArgs extends InstallArgs {
15584        private File codeFile;
15585        private File resourceFile;
15586
15587        /** New install */
15588        MoveInstallArgs(InstallParams params) {
15589            super(params.origin, params.move, params.observer, params.installFlags,
15590                    params.installerPackageName, params.volumeUuid,
15591                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15592                    params.grantedRuntimePermissions,
15593                    params.traceMethod, params.traceCookie, params.certificates,
15594                    params.installReason);
15595        }
15596
15597        int copyApk(IMediaContainerService imcs, boolean temp) {
15598            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15599                    + move.fromUuid + " to " + move.toUuid);
15600            synchronized (mInstaller) {
15601                try {
15602                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15603                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15604                } catch (InstallerException e) {
15605                    Slog.w(TAG, "Failed to move app", e);
15606                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15607                }
15608            }
15609
15610            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15611            resourceFile = codeFile;
15612            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15613
15614            return PackageManager.INSTALL_SUCCEEDED;
15615        }
15616
15617        int doPreInstall(int status) {
15618            if (status != PackageManager.INSTALL_SUCCEEDED) {
15619                cleanUp(move.toUuid);
15620            }
15621            return status;
15622        }
15623
15624        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15625            if (status != PackageManager.INSTALL_SUCCEEDED) {
15626                cleanUp(move.toUuid);
15627                return false;
15628            }
15629
15630            // Reflect the move in app info
15631            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15632            pkg.setApplicationInfoCodePath(pkg.codePath);
15633            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15634            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15635            pkg.setApplicationInfoResourcePath(pkg.codePath);
15636            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15637            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15638
15639            return true;
15640        }
15641
15642        int doPostInstall(int status, int uid) {
15643            if (status == PackageManager.INSTALL_SUCCEEDED) {
15644                cleanUp(move.fromUuid);
15645            } else {
15646                cleanUp(move.toUuid);
15647            }
15648            return status;
15649        }
15650
15651        @Override
15652        String getCodePath() {
15653            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15654        }
15655
15656        @Override
15657        String getResourcePath() {
15658            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15659        }
15660
15661        private boolean cleanUp(String volumeUuid) {
15662            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15663                    move.dataAppName);
15664            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15665            final int[] userIds = sUserManager.getUserIds();
15666            synchronized (mInstallLock) {
15667                // Clean up both app data and code
15668                // All package moves are frozen until finished
15669                for (int userId : userIds) {
15670                    try {
15671                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15672                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15673                    } catch (InstallerException e) {
15674                        Slog.w(TAG, String.valueOf(e));
15675                    }
15676                }
15677                removeCodePathLI(codeFile);
15678            }
15679            return true;
15680        }
15681
15682        void cleanUpResourcesLI() {
15683            throw new UnsupportedOperationException();
15684        }
15685
15686        boolean doPostDeleteLI(boolean delete) {
15687            throw new UnsupportedOperationException();
15688        }
15689    }
15690
15691    static String getAsecPackageName(String packageCid) {
15692        int idx = packageCid.lastIndexOf("-");
15693        if (idx == -1) {
15694            return packageCid;
15695        }
15696        return packageCid.substring(0, idx);
15697    }
15698
15699    // Utility method used to create code paths based on package name and available index.
15700    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15701        String idxStr = "";
15702        int idx = 1;
15703        // Fall back to default value of idx=1 if prefix is not
15704        // part of oldCodePath
15705        if (oldCodePath != null) {
15706            String subStr = oldCodePath;
15707            // Drop the suffix right away
15708            if (suffix != null && subStr.endsWith(suffix)) {
15709                subStr = subStr.substring(0, subStr.length() - suffix.length());
15710            }
15711            // If oldCodePath already contains prefix find out the
15712            // ending index to either increment or decrement.
15713            int sidx = subStr.lastIndexOf(prefix);
15714            if (sidx != -1) {
15715                subStr = subStr.substring(sidx + prefix.length());
15716                if (subStr != null) {
15717                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15718                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15719                    }
15720                    try {
15721                        idx = Integer.parseInt(subStr);
15722                        if (idx <= 1) {
15723                            idx++;
15724                        } else {
15725                            idx--;
15726                        }
15727                    } catch(NumberFormatException e) {
15728                    }
15729                }
15730            }
15731        }
15732        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15733        return prefix + idxStr;
15734    }
15735
15736    private File getNextCodePath(File targetDir, String packageName) {
15737        File result;
15738        SecureRandom random = new SecureRandom();
15739        byte[] bytes = new byte[16];
15740        do {
15741            random.nextBytes(bytes);
15742            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15743            result = new File(targetDir, packageName + "-" + suffix);
15744        } while (result.exists());
15745        return result;
15746    }
15747
15748    // Utility method that returns the relative package path with respect
15749    // to the installation directory. Like say for /data/data/com.test-1.apk
15750    // string com.test-1 is returned.
15751    static String deriveCodePathName(String codePath) {
15752        if (codePath == null) {
15753            return null;
15754        }
15755        final File codeFile = new File(codePath);
15756        final String name = codeFile.getName();
15757        if (codeFile.isDirectory()) {
15758            return name;
15759        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15760            final int lastDot = name.lastIndexOf('.');
15761            return name.substring(0, lastDot);
15762        } else {
15763            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15764            return null;
15765        }
15766    }
15767
15768    static class PackageInstalledInfo {
15769        String name;
15770        int uid;
15771        // The set of users that originally had this package installed.
15772        int[] origUsers;
15773        // The set of users that now have this package installed.
15774        int[] newUsers;
15775        PackageParser.Package pkg;
15776        int returnCode;
15777        String returnMsg;
15778        PackageRemovedInfo removedInfo;
15779        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15780
15781        public void setError(int code, String msg) {
15782            setReturnCode(code);
15783            setReturnMessage(msg);
15784            Slog.w(TAG, msg);
15785        }
15786
15787        public void setError(String msg, PackageParserException e) {
15788            setReturnCode(e.error);
15789            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15790            Slog.w(TAG, msg, e);
15791        }
15792
15793        public void setError(String msg, PackageManagerException e) {
15794            returnCode = e.error;
15795            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15796            Slog.w(TAG, msg, e);
15797        }
15798
15799        public void setReturnCode(int returnCode) {
15800            this.returnCode = returnCode;
15801            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15802            for (int i = 0; i < childCount; i++) {
15803                addedChildPackages.valueAt(i).returnCode = returnCode;
15804            }
15805        }
15806
15807        private void setReturnMessage(String returnMsg) {
15808            this.returnMsg = returnMsg;
15809            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15810            for (int i = 0; i < childCount; i++) {
15811                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15812            }
15813        }
15814
15815        // In some error cases we want to convey more info back to the observer
15816        String origPackage;
15817        String origPermission;
15818    }
15819
15820    /*
15821     * Install a non-existing package.
15822     */
15823    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15824            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15825            PackageInstalledInfo res, int installReason) {
15826        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15827
15828        // Remember this for later, in case we need to rollback this install
15829        String pkgName = pkg.packageName;
15830
15831        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15832
15833        synchronized(mPackages) {
15834            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15835            if (renamedPackage != null) {
15836                // A package with the same name is already installed, though
15837                // it has been renamed to an older name.  The package we
15838                // are trying to install should be installed as an update to
15839                // the existing one, but that has not been requested, so bail.
15840                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15841                        + " without first uninstalling package running as "
15842                        + renamedPackage);
15843                return;
15844            }
15845            if (mPackages.containsKey(pkgName)) {
15846                // Don't allow installation over an existing package with the same name.
15847                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15848                        + " without first uninstalling.");
15849                return;
15850            }
15851        }
15852
15853        try {
15854            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15855                    System.currentTimeMillis(), user);
15856
15857            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15858
15859            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15860                prepareAppDataAfterInstallLIF(newPackage);
15861
15862            } else {
15863                // Remove package from internal structures, but keep around any
15864                // data that might have already existed
15865                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15866                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15867            }
15868        } catch (PackageManagerException e) {
15869            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15870        }
15871
15872        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15873    }
15874
15875    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15876        // Can't rotate keys during boot or if sharedUser.
15877        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15878                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15879            return false;
15880        }
15881        // app is using upgradeKeySets; make sure all are valid
15882        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15883        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15884        for (int i = 0; i < upgradeKeySets.length; i++) {
15885            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15886                Slog.wtf(TAG, "Package "
15887                         + (oldPs.name != null ? oldPs.name : "<null>")
15888                         + " contains upgrade-key-set reference to unknown key-set: "
15889                         + upgradeKeySets[i]
15890                         + " reverting to signatures check.");
15891                return false;
15892            }
15893        }
15894        return true;
15895    }
15896
15897    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15898        // Upgrade keysets are being used.  Determine if new package has a superset of the
15899        // required keys.
15900        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15901        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15902        for (int i = 0; i < upgradeKeySets.length; i++) {
15903            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15904            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15905                return true;
15906            }
15907        }
15908        return false;
15909    }
15910
15911    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15912        try (DigestInputStream digestStream =
15913                new DigestInputStream(new FileInputStream(file), digest)) {
15914            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15915        }
15916    }
15917
15918    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15919            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15920            int installReason) {
15921        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15922
15923        final PackageParser.Package oldPackage;
15924        final String pkgName = pkg.packageName;
15925        final int[] allUsers;
15926        final int[] installedUsers;
15927
15928        synchronized(mPackages) {
15929            oldPackage = mPackages.get(pkgName);
15930            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15931
15932            // don't allow upgrade to target a release SDK from a pre-release SDK
15933            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15934                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15935            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15936                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15937            if (oldTargetsPreRelease
15938                    && !newTargetsPreRelease
15939                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15940                Slog.w(TAG, "Can't install package targeting released sdk");
15941                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15942                return;
15943            }
15944
15945            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15946
15947            // verify signatures are valid
15948            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15949                if (!checkUpgradeKeySetLP(ps, pkg)) {
15950                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15951                            "New package not signed by keys specified by upgrade-keysets: "
15952                                    + pkgName);
15953                    return;
15954                }
15955            } else {
15956                // default to original signature matching
15957                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15958                        != PackageManager.SIGNATURE_MATCH) {
15959                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15960                            "New package has a different signature: " + pkgName);
15961                    return;
15962                }
15963            }
15964
15965            // don't allow a system upgrade unless the upgrade hash matches
15966            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15967                byte[] digestBytes = null;
15968                try {
15969                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15970                    updateDigest(digest, new File(pkg.baseCodePath));
15971                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15972                        for (String path : pkg.splitCodePaths) {
15973                            updateDigest(digest, new File(path));
15974                        }
15975                    }
15976                    digestBytes = digest.digest();
15977                } catch (NoSuchAlgorithmException | IOException e) {
15978                    res.setError(INSTALL_FAILED_INVALID_APK,
15979                            "Could not compute hash: " + pkgName);
15980                    return;
15981                }
15982                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15983                    res.setError(INSTALL_FAILED_INVALID_APK,
15984                            "New package fails restrict-update check: " + pkgName);
15985                    return;
15986                }
15987                // retain upgrade restriction
15988                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15989            }
15990
15991            // Check for shared user id changes
15992            String invalidPackageName =
15993                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15994            if (invalidPackageName != null) {
15995                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15996                        "Package " + invalidPackageName + " tried to change user "
15997                                + oldPackage.mSharedUserId);
15998                return;
15999            }
16000
16001            // In case of rollback, remember per-user/profile install state
16002            allUsers = sUserManager.getUserIds();
16003            installedUsers = ps.queryInstalledUsers(allUsers, true);
16004
16005            // don't allow an upgrade from full to ephemeral
16006            if (isInstantApp) {
16007                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16008                    for (int currentUser : allUsers) {
16009                        if (!ps.getInstantApp(currentUser)) {
16010                            // can't downgrade from full to instant
16011                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16012                                    + " for user: " + currentUser);
16013                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16014                            return;
16015                        }
16016                    }
16017                } else if (!ps.getInstantApp(user.getIdentifier())) {
16018                    // can't downgrade from full to instant
16019                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16020                            + " for user: " + user.getIdentifier());
16021                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16022                    return;
16023                }
16024            }
16025        }
16026
16027        // Update what is removed
16028        res.removedInfo = new PackageRemovedInfo();
16029        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16030        res.removedInfo.removedPackage = oldPackage.packageName;
16031        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16032        res.removedInfo.isUpdate = true;
16033        res.removedInfo.origUsers = installedUsers;
16034        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
16035        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16036        for (int i = 0; i < installedUsers.length; i++) {
16037            final int userId = installedUsers[i];
16038            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16039        }
16040
16041        final int childCount = (oldPackage.childPackages != null)
16042                ? oldPackage.childPackages.size() : 0;
16043        for (int i = 0; i < childCount; i++) {
16044            boolean childPackageUpdated = false;
16045            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16046            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16047            if (res.addedChildPackages != null) {
16048                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16049                if (childRes != null) {
16050                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16051                    childRes.removedInfo.removedPackage = childPkg.packageName;
16052                    childRes.removedInfo.isUpdate = true;
16053                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16054                    childPackageUpdated = true;
16055                }
16056            }
16057            if (!childPackageUpdated) {
16058                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
16059                childRemovedRes.removedPackage = childPkg.packageName;
16060                childRemovedRes.isUpdate = false;
16061                childRemovedRes.dataRemoved = true;
16062                synchronized (mPackages) {
16063                    if (childPs != null) {
16064                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16065                    }
16066                }
16067                if (res.removedInfo.removedChildPackages == null) {
16068                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16069                }
16070                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16071            }
16072        }
16073
16074        boolean sysPkg = (isSystemApp(oldPackage));
16075        if (sysPkg) {
16076            // Set the system/privileged flags as needed
16077            final boolean privileged =
16078                    (oldPackage.applicationInfo.privateFlags
16079                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16080            final int systemPolicyFlags = policyFlags
16081                    | PackageParser.PARSE_IS_SYSTEM
16082                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16083
16084            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16085                    user, allUsers, installerPackageName, res, installReason);
16086        } else {
16087            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16088                    user, allUsers, installerPackageName, res, installReason);
16089        }
16090    }
16091
16092    public List<String> getPreviousCodePaths(String packageName) {
16093        final PackageSetting ps = mSettings.mPackages.get(packageName);
16094        final List<String> result = new ArrayList<String>();
16095        if (ps != null && ps.oldCodePaths != null) {
16096            result.addAll(ps.oldCodePaths);
16097        }
16098        return result;
16099    }
16100
16101    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16102            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16103            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16104            int installReason) {
16105        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16106                + deletedPackage);
16107
16108        String pkgName = deletedPackage.packageName;
16109        boolean deletedPkg = true;
16110        boolean addedPkg = false;
16111        boolean updatedSettings = false;
16112        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16113        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16114                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16115
16116        final long origUpdateTime = (pkg.mExtras != null)
16117                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16118
16119        // First delete the existing package while retaining the data directory
16120        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16121                res.removedInfo, true, pkg)) {
16122            // If the existing package wasn't successfully deleted
16123            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16124            deletedPkg = false;
16125        } else {
16126            // Successfully deleted the old package; proceed with replace.
16127
16128            // If deleted package lived in a container, give users a chance to
16129            // relinquish resources before killing.
16130            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16131                if (DEBUG_INSTALL) {
16132                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16133                }
16134                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16135                final ArrayList<String> pkgList = new ArrayList<String>(1);
16136                pkgList.add(deletedPackage.applicationInfo.packageName);
16137                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16138            }
16139
16140            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16141                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16142            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16143
16144            try {
16145                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16146                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16147                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16148                        installReason);
16149
16150                // Update the in-memory copy of the previous code paths.
16151                PackageSetting ps = mSettings.mPackages.get(pkgName);
16152                if (!killApp) {
16153                    if (ps.oldCodePaths == null) {
16154                        ps.oldCodePaths = new ArraySet<>();
16155                    }
16156                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16157                    if (deletedPackage.splitCodePaths != null) {
16158                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16159                    }
16160                } else {
16161                    ps.oldCodePaths = null;
16162                }
16163                if (ps.childPackageNames != null) {
16164                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16165                        final String childPkgName = ps.childPackageNames.get(i);
16166                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16167                        childPs.oldCodePaths = ps.oldCodePaths;
16168                    }
16169                }
16170                // set instant app status, but, only if it's explicitly specified
16171                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16172                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16173                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16174                prepareAppDataAfterInstallLIF(newPackage);
16175                addedPkg = true;
16176                mDexManager.notifyPackageUpdated(newPackage.packageName,
16177                        newPackage.baseCodePath, newPackage.splitCodePaths);
16178            } catch (PackageManagerException e) {
16179                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16180            }
16181        }
16182
16183        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16184            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16185
16186            // Revert all internal state mutations and added folders for the failed install
16187            if (addedPkg) {
16188                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16189                        res.removedInfo, true, null);
16190            }
16191
16192            // Restore the old package
16193            if (deletedPkg) {
16194                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16195                File restoreFile = new File(deletedPackage.codePath);
16196                // Parse old package
16197                boolean oldExternal = isExternal(deletedPackage);
16198                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16199                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16200                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16201                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16202                try {
16203                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16204                            null);
16205                } catch (PackageManagerException e) {
16206                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16207                            + e.getMessage());
16208                    return;
16209                }
16210
16211                synchronized (mPackages) {
16212                    // Ensure the installer package name up to date
16213                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16214
16215                    // Update permissions for restored package
16216                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16217
16218                    mSettings.writeLPr();
16219                }
16220
16221                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16222            }
16223        } else {
16224            synchronized (mPackages) {
16225                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16226                if (ps != null) {
16227                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16228                    if (res.removedInfo.removedChildPackages != null) {
16229                        final int childCount = res.removedInfo.removedChildPackages.size();
16230                        // Iterate in reverse as we may modify the collection
16231                        for (int i = childCount - 1; i >= 0; i--) {
16232                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16233                            if (res.addedChildPackages.containsKey(childPackageName)) {
16234                                res.removedInfo.removedChildPackages.removeAt(i);
16235                            } else {
16236                                PackageRemovedInfo childInfo = res.removedInfo
16237                                        .removedChildPackages.valueAt(i);
16238                                childInfo.removedForAllUsers = mPackages.get(
16239                                        childInfo.removedPackage) == null;
16240                            }
16241                        }
16242                    }
16243                }
16244            }
16245        }
16246    }
16247
16248    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16249            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16250            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16251            int installReason) {
16252        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16253                + ", old=" + deletedPackage);
16254
16255        final boolean disabledSystem;
16256
16257        // Remove existing system package
16258        removePackageLI(deletedPackage, true);
16259
16260        synchronized (mPackages) {
16261            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16262        }
16263        if (!disabledSystem) {
16264            // We didn't need to disable the .apk as a current system package,
16265            // which means we are replacing another update that is already
16266            // installed.  We need to make sure to delete the older one's .apk.
16267            res.removedInfo.args = createInstallArgsForExisting(0,
16268                    deletedPackage.applicationInfo.getCodePath(),
16269                    deletedPackage.applicationInfo.getResourcePath(),
16270                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16271        } else {
16272            res.removedInfo.args = null;
16273        }
16274
16275        // Successfully disabled the old package. Now proceed with re-installation
16276        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16277                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16278        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16279
16280        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16281        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16282                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16283
16284        PackageParser.Package newPackage = null;
16285        try {
16286            // Add the package to the internal data structures
16287            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16288
16289            // Set the update and install times
16290            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16291            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16292                    System.currentTimeMillis());
16293
16294            // Update the package dynamic state if succeeded
16295            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16296                // Now that the install succeeded make sure we remove data
16297                // directories for any child package the update removed.
16298                final int deletedChildCount = (deletedPackage.childPackages != null)
16299                        ? deletedPackage.childPackages.size() : 0;
16300                final int newChildCount = (newPackage.childPackages != null)
16301                        ? newPackage.childPackages.size() : 0;
16302                for (int i = 0; i < deletedChildCount; i++) {
16303                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16304                    boolean childPackageDeleted = true;
16305                    for (int j = 0; j < newChildCount; j++) {
16306                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16307                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16308                            childPackageDeleted = false;
16309                            break;
16310                        }
16311                    }
16312                    if (childPackageDeleted) {
16313                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16314                                deletedChildPkg.packageName);
16315                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16316                            PackageRemovedInfo removedChildRes = res.removedInfo
16317                                    .removedChildPackages.get(deletedChildPkg.packageName);
16318                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16319                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16320                        }
16321                    }
16322                }
16323
16324                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16325                        installReason);
16326                prepareAppDataAfterInstallLIF(newPackage);
16327
16328                mDexManager.notifyPackageUpdated(newPackage.packageName,
16329                            newPackage.baseCodePath, newPackage.splitCodePaths);
16330            }
16331        } catch (PackageManagerException e) {
16332            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16333            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16334        }
16335
16336        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16337            // Re installation failed. Restore old information
16338            // Remove new pkg information
16339            if (newPackage != null) {
16340                removeInstalledPackageLI(newPackage, true);
16341            }
16342            // Add back the old system package
16343            try {
16344                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16345            } catch (PackageManagerException e) {
16346                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16347            }
16348
16349            synchronized (mPackages) {
16350                if (disabledSystem) {
16351                    enableSystemPackageLPw(deletedPackage);
16352                }
16353
16354                // Ensure the installer package name up to date
16355                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16356
16357                // Update permissions for restored package
16358                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16359
16360                mSettings.writeLPr();
16361            }
16362
16363            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16364                    + " after failed upgrade");
16365        }
16366    }
16367
16368    /**
16369     * Checks whether the parent or any of the child packages have a change shared
16370     * user. For a package to be a valid update the shred users of the parent and
16371     * the children should match. We may later support changing child shared users.
16372     * @param oldPkg The updated package.
16373     * @param newPkg The update package.
16374     * @return The shared user that change between the versions.
16375     */
16376    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16377            PackageParser.Package newPkg) {
16378        // Check parent shared user
16379        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16380            return newPkg.packageName;
16381        }
16382        // Check child shared users
16383        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16384        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16385        for (int i = 0; i < newChildCount; i++) {
16386            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16387            // If this child was present, did it have the same shared user?
16388            for (int j = 0; j < oldChildCount; j++) {
16389                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16390                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16391                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16392                    return newChildPkg.packageName;
16393                }
16394            }
16395        }
16396        return null;
16397    }
16398
16399    private void removeNativeBinariesLI(PackageSetting ps) {
16400        // Remove the lib path for the parent package
16401        if (ps != null) {
16402            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16403            // Remove the lib path for the child packages
16404            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16405            for (int i = 0; i < childCount; i++) {
16406                PackageSetting childPs = null;
16407                synchronized (mPackages) {
16408                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16409                }
16410                if (childPs != null) {
16411                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16412                            .legacyNativeLibraryPathString);
16413                }
16414            }
16415        }
16416    }
16417
16418    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16419        // Enable the parent package
16420        mSettings.enableSystemPackageLPw(pkg.packageName);
16421        // Enable the child packages
16422        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16423        for (int i = 0; i < childCount; i++) {
16424            PackageParser.Package childPkg = pkg.childPackages.get(i);
16425            mSettings.enableSystemPackageLPw(childPkg.packageName);
16426        }
16427    }
16428
16429    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16430            PackageParser.Package newPkg) {
16431        // Disable the parent package (parent always replaced)
16432        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16433        // Disable the child packages
16434        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16435        for (int i = 0; i < childCount; i++) {
16436            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16437            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16438            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16439        }
16440        return disabled;
16441    }
16442
16443    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16444            String installerPackageName) {
16445        // Enable the parent package
16446        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16447        // Enable the child packages
16448        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16449        for (int i = 0; i < childCount; i++) {
16450            PackageParser.Package childPkg = pkg.childPackages.get(i);
16451            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16452        }
16453    }
16454
16455    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16456        // Collect all used permissions in the UID
16457        ArraySet<String> usedPermissions = new ArraySet<>();
16458        final int packageCount = su.packages.size();
16459        for (int i = 0; i < packageCount; i++) {
16460            PackageSetting ps = su.packages.valueAt(i);
16461            if (ps.pkg == null) {
16462                continue;
16463            }
16464            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16465            for (int j = 0; j < requestedPermCount; j++) {
16466                String permission = ps.pkg.requestedPermissions.get(j);
16467                BasePermission bp = mSettings.mPermissions.get(permission);
16468                if (bp != null) {
16469                    usedPermissions.add(permission);
16470                }
16471            }
16472        }
16473
16474        PermissionsState permissionsState = su.getPermissionsState();
16475        // Prune install permissions
16476        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16477        final int installPermCount = installPermStates.size();
16478        for (int i = installPermCount - 1; i >= 0;  i--) {
16479            PermissionState permissionState = installPermStates.get(i);
16480            if (!usedPermissions.contains(permissionState.getName())) {
16481                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16482                if (bp != null) {
16483                    permissionsState.revokeInstallPermission(bp);
16484                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16485                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16486                }
16487            }
16488        }
16489
16490        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16491
16492        // Prune runtime permissions
16493        for (int userId : allUserIds) {
16494            List<PermissionState> runtimePermStates = permissionsState
16495                    .getRuntimePermissionStates(userId);
16496            final int runtimePermCount = runtimePermStates.size();
16497            for (int i = runtimePermCount - 1; i >= 0; i--) {
16498                PermissionState permissionState = runtimePermStates.get(i);
16499                if (!usedPermissions.contains(permissionState.getName())) {
16500                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16501                    if (bp != null) {
16502                        permissionsState.revokeRuntimePermission(bp, userId);
16503                        permissionsState.updatePermissionFlags(bp, userId,
16504                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16505                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16506                                runtimePermissionChangedUserIds, userId);
16507                    }
16508                }
16509            }
16510        }
16511
16512        return runtimePermissionChangedUserIds;
16513    }
16514
16515    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16516            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16517        // Update the parent package setting
16518        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16519                res, user, installReason);
16520        // Update the child packages setting
16521        final int childCount = (newPackage.childPackages != null)
16522                ? newPackage.childPackages.size() : 0;
16523        for (int i = 0; i < childCount; i++) {
16524            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16525            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16526            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16527                    childRes.origUsers, childRes, user, installReason);
16528        }
16529    }
16530
16531    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16532            String installerPackageName, int[] allUsers, int[] installedForUsers,
16533            PackageInstalledInfo res, UserHandle user, int installReason) {
16534        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16535
16536        String pkgName = newPackage.packageName;
16537        synchronized (mPackages) {
16538            //write settings. the installStatus will be incomplete at this stage.
16539            //note that the new package setting would have already been
16540            //added to mPackages. It hasn't been persisted yet.
16541            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16542            // TODO: Remove this write? It's also written at the end of this method
16543            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16544            mSettings.writeLPr();
16545            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16546        }
16547
16548        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16549        synchronized (mPackages) {
16550            updatePermissionsLPw(newPackage.packageName, newPackage,
16551                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16552                            ? UPDATE_PERMISSIONS_ALL : 0));
16553            // For system-bundled packages, we assume that installing an upgraded version
16554            // of the package implies that the user actually wants to run that new code,
16555            // so we enable the package.
16556            PackageSetting ps = mSettings.mPackages.get(pkgName);
16557            final int userId = user.getIdentifier();
16558            if (ps != null) {
16559                if (isSystemApp(newPackage)) {
16560                    if (DEBUG_INSTALL) {
16561                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16562                    }
16563                    // Enable system package for requested users
16564                    if (res.origUsers != null) {
16565                        for (int origUserId : res.origUsers) {
16566                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16567                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16568                                        origUserId, installerPackageName);
16569                            }
16570                        }
16571                    }
16572                    // Also convey the prior install/uninstall state
16573                    if (allUsers != null && installedForUsers != null) {
16574                        for (int currentUserId : allUsers) {
16575                            final boolean installed = ArrayUtils.contains(
16576                                    installedForUsers, currentUserId);
16577                            if (DEBUG_INSTALL) {
16578                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16579                            }
16580                            ps.setInstalled(installed, currentUserId);
16581                        }
16582                        // these install state changes will be persisted in the
16583                        // upcoming call to mSettings.writeLPr().
16584                    }
16585                }
16586                // It's implied that when a user requests installation, they want the app to be
16587                // installed and enabled.
16588                if (userId != UserHandle.USER_ALL) {
16589                    ps.setInstalled(true, userId);
16590                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16591                }
16592
16593                // When replacing an existing package, preserve the original install reason for all
16594                // users that had the package installed before.
16595                final Set<Integer> previousUserIds = new ArraySet<>();
16596                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16597                    final int installReasonCount = res.removedInfo.installReasons.size();
16598                    for (int i = 0; i < installReasonCount; i++) {
16599                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16600                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16601                        ps.setInstallReason(previousInstallReason, previousUserId);
16602                        previousUserIds.add(previousUserId);
16603                    }
16604                }
16605
16606                // Set install reason for users that are having the package newly installed.
16607                if (userId == UserHandle.USER_ALL) {
16608                    for (int currentUserId : sUserManager.getUserIds()) {
16609                        if (!previousUserIds.contains(currentUserId)) {
16610                            ps.setInstallReason(installReason, currentUserId);
16611                        }
16612                    }
16613                } else if (!previousUserIds.contains(userId)) {
16614                    ps.setInstallReason(installReason, userId);
16615                }
16616                mSettings.writeKernelMappingLPr(ps);
16617            }
16618            res.name = pkgName;
16619            res.uid = newPackage.applicationInfo.uid;
16620            res.pkg = newPackage;
16621            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16622            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16623            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16624            //to update install status
16625            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16626            mSettings.writeLPr();
16627            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16628        }
16629
16630        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16631    }
16632
16633    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16634        try {
16635            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16636            installPackageLI(args, res);
16637        } finally {
16638            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16639        }
16640    }
16641
16642    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16643        final int installFlags = args.installFlags;
16644        final String installerPackageName = args.installerPackageName;
16645        final String volumeUuid = args.volumeUuid;
16646        final File tmpPackageFile = new File(args.getCodePath());
16647        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16648        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16649                || (args.volumeUuid != null));
16650        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16651        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16652        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16653        boolean replace = false;
16654        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16655        if (args.move != null) {
16656            // moving a complete application; perform an initial scan on the new install location
16657            scanFlags |= SCAN_INITIAL;
16658        }
16659        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16660            scanFlags |= SCAN_DONT_KILL_APP;
16661        }
16662        if (instantApp) {
16663            scanFlags |= SCAN_AS_INSTANT_APP;
16664        }
16665        if (fullApp) {
16666            scanFlags |= SCAN_AS_FULL_APP;
16667        }
16668
16669        // Result object to be returned
16670        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16671
16672        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16673
16674        // Sanity check
16675        if (instantApp && (forwardLocked || onExternal)) {
16676            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16677                    + " external=" + onExternal);
16678            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16679            return;
16680        }
16681
16682        // Retrieve PackageSettings and parse package
16683        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16684                | PackageParser.PARSE_ENFORCE_CODE
16685                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16686                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16687                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16688                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16689        PackageParser pp = new PackageParser();
16690        pp.setSeparateProcesses(mSeparateProcesses);
16691        pp.setDisplayMetrics(mMetrics);
16692        pp.setCallback(mPackageParserCallback);
16693
16694        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16695        final PackageParser.Package pkg;
16696        try {
16697            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16698        } catch (PackageParserException e) {
16699            res.setError("Failed parse during installPackageLI", e);
16700            return;
16701        } finally {
16702            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16703        }
16704
16705        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16706        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16707            Slog.w(TAG, "Instant app package " + pkg.packageName
16708                    + " does not target O, this will be a fatal error.");
16709            // STOPSHIP: Make this a fatal error
16710            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16711        }
16712        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16713            Slog.w(TAG, "Instant app package " + pkg.packageName
16714                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16715            // STOPSHIP: Make this a fatal error
16716            pkg.applicationInfo.targetSandboxVersion = 2;
16717        }
16718
16719        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16720            // Static shared libraries have synthetic package names
16721            renameStaticSharedLibraryPackage(pkg);
16722
16723            // No static shared libs on external storage
16724            if (onExternal) {
16725                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16726                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16727                        "Packages declaring static-shared libs cannot be updated");
16728                return;
16729            }
16730        }
16731
16732        // If we are installing a clustered package add results for the children
16733        if (pkg.childPackages != null) {
16734            synchronized (mPackages) {
16735                final int childCount = pkg.childPackages.size();
16736                for (int i = 0; i < childCount; i++) {
16737                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16738                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16739                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16740                    childRes.pkg = childPkg;
16741                    childRes.name = childPkg.packageName;
16742                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16743                    if (childPs != null) {
16744                        childRes.origUsers = childPs.queryInstalledUsers(
16745                                sUserManager.getUserIds(), true);
16746                    }
16747                    if ((mPackages.containsKey(childPkg.packageName))) {
16748                        childRes.removedInfo = new PackageRemovedInfo();
16749                        childRes.removedInfo.removedPackage = childPkg.packageName;
16750                    }
16751                    if (res.addedChildPackages == null) {
16752                        res.addedChildPackages = new ArrayMap<>();
16753                    }
16754                    res.addedChildPackages.put(childPkg.packageName, childRes);
16755                }
16756            }
16757        }
16758
16759        // If package doesn't declare API override, mark that we have an install
16760        // time CPU ABI override.
16761        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16762            pkg.cpuAbiOverride = args.abiOverride;
16763        }
16764
16765        String pkgName = res.name = pkg.packageName;
16766        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16767            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16768                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16769                return;
16770            }
16771        }
16772
16773        try {
16774            // either use what we've been given or parse directly from the APK
16775            if (args.certificates != null) {
16776                try {
16777                    PackageParser.populateCertificates(pkg, args.certificates);
16778                } catch (PackageParserException e) {
16779                    // there was something wrong with the certificates we were given;
16780                    // try to pull them from the APK
16781                    PackageParser.collectCertificates(pkg, parseFlags);
16782                }
16783            } else {
16784                PackageParser.collectCertificates(pkg, parseFlags);
16785            }
16786        } catch (PackageParserException e) {
16787            res.setError("Failed collect during installPackageLI", e);
16788            return;
16789        }
16790
16791        // Get rid of all references to package scan path via parser.
16792        pp = null;
16793        String oldCodePath = null;
16794        boolean systemApp = false;
16795        synchronized (mPackages) {
16796            // Check if installing already existing package
16797            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16798                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16799                if (pkg.mOriginalPackages != null
16800                        && pkg.mOriginalPackages.contains(oldName)
16801                        && mPackages.containsKey(oldName)) {
16802                    // This package is derived from an original package,
16803                    // and this device has been updating from that original
16804                    // name.  We must continue using the original name, so
16805                    // rename the new package here.
16806                    pkg.setPackageName(oldName);
16807                    pkgName = pkg.packageName;
16808                    replace = true;
16809                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16810                            + oldName + " pkgName=" + pkgName);
16811                } else if (mPackages.containsKey(pkgName)) {
16812                    // This package, under its official name, already exists
16813                    // on the device; we should replace it.
16814                    replace = true;
16815                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16816                }
16817
16818                // Child packages are installed through the parent package
16819                if (pkg.parentPackage != null) {
16820                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16821                            "Package " + pkg.packageName + " is child of package "
16822                                    + pkg.parentPackage.parentPackage + ". Child packages "
16823                                    + "can be updated only through the parent package.");
16824                    return;
16825                }
16826
16827                if (replace) {
16828                    // Prevent apps opting out from runtime permissions
16829                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16830                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16831                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16832                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16833                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16834                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16835                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16836                                        + " doesn't support runtime permissions but the old"
16837                                        + " target SDK " + oldTargetSdk + " does.");
16838                        return;
16839                    }
16840                    // Prevent apps from downgrading their targetSandbox.
16841                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16842                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16843                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16844                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16845                                "Package " + pkg.packageName + " new target sandbox "
16846                                + newTargetSandbox + " is incompatible with the previous value of"
16847                                + oldTargetSandbox + ".");
16848                        return;
16849                    }
16850
16851                    // Prevent installing of child packages
16852                    if (oldPackage.parentPackage != null) {
16853                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16854                                "Package " + pkg.packageName + " is child of package "
16855                                        + oldPackage.parentPackage + ". Child packages "
16856                                        + "can be updated only through the parent package.");
16857                        return;
16858                    }
16859                }
16860            }
16861
16862            PackageSetting ps = mSettings.mPackages.get(pkgName);
16863            if (ps != null) {
16864                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16865
16866                // Static shared libs have same package with different versions where
16867                // we internally use a synthetic package name to allow multiple versions
16868                // of the same package, therefore we need to compare signatures against
16869                // the package setting for the latest library version.
16870                PackageSetting signatureCheckPs = ps;
16871                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16872                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16873                    if (libraryEntry != null) {
16874                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16875                    }
16876                }
16877
16878                // Quick sanity check that we're signed correctly if updating;
16879                // we'll check this again later when scanning, but we want to
16880                // bail early here before tripping over redefined permissions.
16881                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16882                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16883                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16884                                + pkg.packageName + " upgrade keys do not match the "
16885                                + "previously installed version");
16886                        return;
16887                    }
16888                } else {
16889                    try {
16890                        verifySignaturesLP(signatureCheckPs, pkg);
16891                    } catch (PackageManagerException e) {
16892                        res.setError(e.error, e.getMessage());
16893                        return;
16894                    }
16895                }
16896
16897                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16898                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16899                    systemApp = (ps.pkg.applicationInfo.flags &
16900                            ApplicationInfo.FLAG_SYSTEM) != 0;
16901                }
16902                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16903            }
16904
16905            int N = pkg.permissions.size();
16906            for (int i = N-1; i >= 0; i--) {
16907                PackageParser.Permission perm = pkg.permissions.get(i);
16908                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16909
16910                // Don't allow anyone but the platform to define ephemeral permissions.
16911                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16912                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16913                    Slog.w(TAG, "Package " + pkg.packageName
16914                            + " attempting to delcare ephemeral permission "
16915                            + perm.info.name + "; Removing ephemeral.");
16916                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16917                }
16918                // Check whether the newly-scanned package wants to define an already-defined perm
16919                if (bp != null) {
16920                    // If the defining package is signed with our cert, it's okay.  This
16921                    // also includes the "updating the same package" case, of course.
16922                    // "updating same package" could also involve key-rotation.
16923                    final boolean sigsOk;
16924                    if (bp.sourcePackage.equals(pkg.packageName)
16925                            && (bp.packageSetting instanceof PackageSetting)
16926                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16927                                    scanFlags))) {
16928                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16929                    } else {
16930                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16931                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16932                    }
16933                    if (!sigsOk) {
16934                        // If the owning package is the system itself, we log but allow
16935                        // install to proceed; we fail the install on all other permission
16936                        // redefinitions.
16937                        if (!bp.sourcePackage.equals("android")) {
16938                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16939                                    + pkg.packageName + " attempting to redeclare permission "
16940                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16941                            res.origPermission = perm.info.name;
16942                            res.origPackage = bp.sourcePackage;
16943                            return;
16944                        } else {
16945                            Slog.w(TAG, "Package " + pkg.packageName
16946                                    + " attempting to redeclare system permission "
16947                                    + perm.info.name + "; ignoring new declaration");
16948                            pkg.permissions.remove(i);
16949                        }
16950                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16951                        // Prevent apps to change protection level to dangerous from any other
16952                        // type as this would allow a privilege escalation where an app adds a
16953                        // normal/signature permission in other app's group and later redefines
16954                        // it as dangerous leading to the group auto-grant.
16955                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16956                                == PermissionInfo.PROTECTION_DANGEROUS) {
16957                            if (bp != null && !bp.isRuntime()) {
16958                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16959                                        + "non-runtime permission " + perm.info.name
16960                                        + " to runtime; keeping old protection level");
16961                                perm.info.protectionLevel = bp.protectionLevel;
16962                            }
16963                        }
16964                    }
16965                }
16966            }
16967        }
16968
16969        if (systemApp) {
16970            if (onExternal) {
16971                // Abort update; system app can't be replaced with app on sdcard
16972                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16973                        "Cannot install updates to system apps on sdcard");
16974                return;
16975            } else if (instantApp) {
16976                // Abort update; system app can't be replaced with an instant app
16977                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16978                        "Cannot update a system app with an instant app");
16979                return;
16980            }
16981        }
16982
16983        if (args.move != null) {
16984            // We did an in-place move, so dex is ready to roll
16985            scanFlags |= SCAN_NO_DEX;
16986            scanFlags |= SCAN_MOVE;
16987
16988            synchronized (mPackages) {
16989                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16990                if (ps == null) {
16991                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16992                            "Missing settings for moved package " + pkgName);
16993                }
16994
16995                // We moved the entire application as-is, so bring over the
16996                // previously derived ABI information.
16997                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16998                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16999            }
17000
17001        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17002            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17003            scanFlags |= SCAN_NO_DEX;
17004
17005            try {
17006                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17007                    args.abiOverride : pkg.cpuAbiOverride);
17008                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17009                        true /*extractLibs*/, mAppLib32InstallDir);
17010            } catch (PackageManagerException pme) {
17011                Slog.e(TAG, "Error deriving application ABI", pme);
17012                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17013                return;
17014            }
17015
17016            // Shared libraries for the package need to be updated.
17017            synchronized (mPackages) {
17018                try {
17019                    updateSharedLibrariesLPr(pkg, null);
17020                } catch (PackageManagerException e) {
17021                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17022                }
17023            }
17024
17025            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17026            // Do not run PackageDexOptimizer through the local performDexOpt
17027            // method because `pkg` may not be in `mPackages` yet.
17028            //
17029            // Also, don't fail application installs if the dexopt step fails.
17030            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17031                    null /* instructionSets */, false /* checkProfiles */,
17032                    getCompilerFilterForReason(REASON_INSTALL),
17033                    getOrCreateCompilerPackageStats(pkg),
17034                    mDexManager.isUsedByOtherApps(pkg.packageName));
17035            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17036
17037            // Notify BackgroundDexOptService that the package has been changed.
17038            // If this is an update of a package which used to fail to compile,
17039            // BDOS will remove it from its blacklist.
17040            // TODO: Layering violation
17041            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17042        }
17043
17044        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17045            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17046            return;
17047        }
17048
17049        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17050
17051        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17052                "installPackageLI")) {
17053            if (replace) {
17054                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17055                    // Static libs have a synthetic package name containing the version
17056                    // and cannot be updated as an update would get a new package name,
17057                    // unless this is the exact same version code which is useful for
17058                    // development.
17059                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17060                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17061                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17062                                + "static-shared libs cannot be updated");
17063                        return;
17064                    }
17065                }
17066                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17067                        installerPackageName, res, args.installReason);
17068            } else {
17069                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17070                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17071            }
17072        }
17073
17074        synchronized (mPackages) {
17075            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17076            if (ps != null) {
17077                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17078                ps.setUpdateAvailable(false /*updateAvailable*/);
17079            }
17080
17081            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17082            for (int i = 0; i < childCount; i++) {
17083                PackageParser.Package childPkg = pkg.childPackages.get(i);
17084                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17085                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17086                if (childPs != null) {
17087                    childRes.newUsers = childPs.queryInstalledUsers(
17088                            sUserManager.getUserIds(), true);
17089                }
17090            }
17091
17092            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17093                updateSequenceNumberLP(pkgName, res.newUsers);
17094                updateInstantAppInstallerLocked(pkgName);
17095            }
17096        }
17097    }
17098
17099    private void startIntentFilterVerifications(int userId, boolean replacing,
17100            PackageParser.Package pkg) {
17101        if (mIntentFilterVerifierComponent == null) {
17102            Slog.w(TAG, "No IntentFilter verification will not be done as "
17103                    + "there is no IntentFilterVerifier available!");
17104            return;
17105        }
17106
17107        final int verifierUid = getPackageUid(
17108                mIntentFilterVerifierComponent.getPackageName(),
17109                MATCH_DEBUG_TRIAGED_MISSING,
17110                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17111
17112        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17113        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17114        mHandler.sendMessage(msg);
17115
17116        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17117        for (int i = 0; i < childCount; i++) {
17118            PackageParser.Package childPkg = pkg.childPackages.get(i);
17119            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17120            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17121            mHandler.sendMessage(msg);
17122        }
17123    }
17124
17125    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17126            PackageParser.Package pkg) {
17127        int size = pkg.activities.size();
17128        if (size == 0) {
17129            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17130                    "No activity, so no need to verify any IntentFilter!");
17131            return;
17132        }
17133
17134        final boolean hasDomainURLs = hasDomainURLs(pkg);
17135        if (!hasDomainURLs) {
17136            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17137                    "No domain URLs, so no need to verify any IntentFilter!");
17138            return;
17139        }
17140
17141        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17142                + " if any IntentFilter from the " + size
17143                + " Activities needs verification ...");
17144
17145        int count = 0;
17146        final String packageName = pkg.packageName;
17147
17148        synchronized (mPackages) {
17149            // If this is a new install and we see that we've already run verification for this
17150            // package, we have nothing to do: it means the state was restored from backup.
17151            if (!replacing) {
17152                IntentFilterVerificationInfo ivi =
17153                        mSettings.getIntentFilterVerificationLPr(packageName);
17154                if (ivi != null) {
17155                    if (DEBUG_DOMAIN_VERIFICATION) {
17156                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17157                                + ivi.getStatusString());
17158                    }
17159                    return;
17160                }
17161            }
17162
17163            // If any filters need to be verified, then all need to be.
17164            boolean needToVerify = false;
17165            for (PackageParser.Activity a : pkg.activities) {
17166                for (ActivityIntentInfo filter : a.intents) {
17167                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17168                        if (DEBUG_DOMAIN_VERIFICATION) {
17169                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17170                        }
17171                        needToVerify = true;
17172                        break;
17173                    }
17174                }
17175            }
17176
17177            if (needToVerify) {
17178                final int verificationId = mIntentFilterVerificationToken++;
17179                for (PackageParser.Activity a : pkg.activities) {
17180                    for (ActivityIntentInfo filter : a.intents) {
17181                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17182                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17183                                    "Verification needed for IntentFilter:" + filter.toString());
17184                            mIntentFilterVerifier.addOneIntentFilterVerification(
17185                                    verifierUid, userId, verificationId, filter, packageName);
17186                            count++;
17187                        }
17188                    }
17189                }
17190            }
17191        }
17192
17193        if (count > 0) {
17194            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17195                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17196                    +  " for userId:" + userId);
17197            mIntentFilterVerifier.startVerifications(userId);
17198        } else {
17199            if (DEBUG_DOMAIN_VERIFICATION) {
17200                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17201            }
17202        }
17203    }
17204
17205    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17206        final ComponentName cn  = filter.activity.getComponentName();
17207        final String packageName = cn.getPackageName();
17208
17209        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17210                packageName);
17211        if (ivi == null) {
17212            return true;
17213        }
17214        int status = ivi.getStatus();
17215        switch (status) {
17216            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17217            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17218                return true;
17219
17220            default:
17221                // Nothing to do
17222                return false;
17223        }
17224    }
17225
17226    private static boolean isMultiArch(ApplicationInfo info) {
17227        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17228    }
17229
17230    private static boolean isExternal(PackageParser.Package pkg) {
17231        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17232    }
17233
17234    private static boolean isExternal(PackageSetting ps) {
17235        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17236    }
17237
17238    private static boolean isSystemApp(PackageParser.Package pkg) {
17239        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17240    }
17241
17242    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17243        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17244    }
17245
17246    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17247        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17248    }
17249
17250    private static boolean isSystemApp(PackageSetting ps) {
17251        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17252    }
17253
17254    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17255        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17256    }
17257
17258    private int packageFlagsToInstallFlags(PackageSetting ps) {
17259        int installFlags = 0;
17260        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17261            // This existing package was an external ASEC install when we have
17262            // the external flag without a UUID
17263            installFlags |= PackageManager.INSTALL_EXTERNAL;
17264        }
17265        if (ps.isForwardLocked()) {
17266            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17267        }
17268        return installFlags;
17269    }
17270
17271    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17272        if (isExternal(pkg)) {
17273            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17274                return StorageManager.UUID_PRIMARY_PHYSICAL;
17275            } else {
17276                return pkg.volumeUuid;
17277            }
17278        } else {
17279            return StorageManager.UUID_PRIVATE_INTERNAL;
17280        }
17281    }
17282
17283    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17284        if (isExternal(pkg)) {
17285            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17286                return mSettings.getExternalVersion();
17287            } else {
17288                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17289            }
17290        } else {
17291            return mSettings.getInternalVersion();
17292        }
17293    }
17294
17295    private void deleteTempPackageFiles() {
17296        final FilenameFilter filter = new FilenameFilter() {
17297            public boolean accept(File dir, String name) {
17298                return name.startsWith("vmdl") && name.endsWith(".tmp");
17299            }
17300        };
17301        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17302            file.delete();
17303        }
17304    }
17305
17306    @Override
17307    public void deletePackageAsUser(String packageName, int versionCode,
17308            IPackageDeleteObserver observer, int userId, int flags) {
17309        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17310                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17311    }
17312
17313    @Override
17314    public void deletePackageVersioned(VersionedPackage versionedPackage,
17315            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17316        mContext.enforceCallingOrSelfPermission(
17317                android.Manifest.permission.DELETE_PACKAGES, null);
17318        Preconditions.checkNotNull(versionedPackage);
17319        Preconditions.checkNotNull(observer);
17320        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17321                PackageManager.VERSION_CODE_HIGHEST,
17322                Integer.MAX_VALUE, "versionCode must be >= -1");
17323
17324        final String packageName = versionedPackage.getPackageName();
17325        // TODO: We will change version code to long, so in the new API it is long
17326        final int versionCode = (int) versionedPackage.getVersionCode();
17327        final String internalPackageName;
17328        synchronized (mPackages) {
17329            // Normalize package name to handle renamed packages and static libs
17330            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17331                    // TODO: We will change version code to long, so in the new API it is long
17332                    (int) versionedPackage.getVersionCode());
17333        }
17334
17335        final int uid = Binder.getCallingUid();
17336        if (!isOrphaned(internalPackageName)
17337                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17338            try {
17339                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17340                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17341                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17342                observer.onUserActionRequired(intent);
17343            } catch (RemoteException re) {
17344            }
17345            return;
17346        }
17347        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17348        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17349        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17350            mContext.enforceCallingOrSelfPermission(
17351                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17352                    "deletePackage for user " + userId);
17353        }
17354
17355        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17356            try {
17357                observer.onPackageDeleted(packageName,
17358                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17359            } catch (RemoteException re) {
17360            }
17361            return;
17362        }
17363
17364        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17365            try {
17366                observer.onPackageDeleted(packageName,
17367                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17368            } catch (RemoteException re) {
17369            }
17370            return;
17371        }
17372
17373        if (DEBUG_REMOVE) {
17374            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17375                    + " deleteAllUsers: " + deleteAllUsers + " version="
17376                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17377                    ? "VERSION_CODE_HIGHEST" : versionCode));
17378        }
17379        // Queue up an async operation since the package deletion may take a little while.
17380        mHandler.post(new Runnable() {
17381            public void run() {
17382                mHandler.removeCallbacks(this);
17383                int returnCode;
17384                if (!deleteAllUsers) {
17385                    returnCode = deletePackageX(internalPackageName, versionCode,
17386                            userId, deleteFlags);
17387                } else {
17388                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17389                            internalPackageName, users);
17390                    // If nobody is blocking uninstall, proceed with delete for all users
17391                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17392                        returnCode = deletePackageX(internalPackageName, versionCode,
17393                                userId, deleteFlags);
17394                    } else {
17395                        // Otherwise uninstall individually for users with blockUninstalls=false
17396                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17397                        for (int userId : users) {
17398                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17399                                returnCode = deletePackageX(internalPackageName, versionCode,
17400                                        userId, userFlags);
17401                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17402                                    Slog.w(TAG, "Package delete failed for user " + userId
17403                                            + ", returnCode " + returnCode);
17404                                }
17405                            }
17406                        }
17407                        // The app has only been marked uninstalled for certain users.
17408                        // We still need to report that delete was blocked
17409                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17410                    }
17411                }
17412                try {
17413                    observer.onPackageDeleted(packageName, returnCode, null);
17414                } catch (RemoteException e) {
17415                    Log.i(TAG, "Observer no longer exists.");
17416                } //end catch
17417            } //end run
17418        });
17419    }
17420
17421    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17422        if (pkg.staticSharedLibName != null) {
17423            return pkg.manifestPackageName;
17424        }
17425        return pkg.packageName;
17426    }
17427
17428    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17429        // Handle renamed packages
17430        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17431        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17432
17433        // Is this a static library?
17434        SparseArray<SharedLibraryEntry> versionedLib =
17435                mStaticLibsByDeclaringPackage.get(packageName);
17436        if (versionedLib == null || versionedLib.size() <= 0) {
17437            return packageName;
17438        }
17439
17440        // Figure out which lib versions the caller can see
17441        SparseIntArray versionsCallerCanSee = null;
17442        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17443        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17444                && callingAppId != Process.ROOT_UID) {
17445            versionsCallerCanSee = new SparseIntArray();
17446            String libName = versionedLib.valueAt(0).info.getName();
17447            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17448            if (uidPackages != null) {
17449                for (String uidPackage : uidPackages) {
17450                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17451                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17452                    if (libIdx >= 0) {
17453                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17454                        versionsCallerCanSee.append(libVersion, libVersion);
17455                    }
17456                }
17457            }
17458        }
17459
17460        // Caller can see nothing - done
17461        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17462            return packageName;
17463        }
17464
17465        // Find the version the caller can see and the app version code
17466        SharedLibraryEntry highestVersion = null;
17467        final int versionCount = versionedLib.size();
17468        for (int i = 0; i < versionCount; i++) {
17469            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17470            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17471                    libEntry.info.getVersion()) < 0) {
17472                continue;
17473            }
17474            // TODO: We will change version code to long, so in the new API it is long
17475            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17476            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17477                if (libVersionCode == versionCode) {
17478                    return libEntry.apk;
17479                }
17480            } else if (highestVersion == null) {
17481                highestVersion = libEntry;
17482            } else if (libVersionCode  > highestVersion.info
17483                    .getDeclaringPackage().getVersionCode()) {
17484                highestVersion = libEntry;
17485            }
17486        }
17487
17488        if (highestVersion != null) {
17489            return highestVersion.apk;
17490        }
17491
17492        return packageName;
17493    }
17494
17495    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17496        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17497              || callingUid == Process.SYSTEM_UID) {
17498            return true;
17499        }
17500        final int callingUserId = UserHandle.getUserId(callingUid);
17501        // If the caller installed the pkgName, then allow it to silently uninstall.
17502        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17503            return true;
17504        }
17505
17506        // Allow package verifier to silently uninstall.
17507        if (mRequiredVerifierPackage != null &&
17508                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17509            return true;
17510        }
17511
17512        // Allow package uninstaller to silently uninstall.
17513        if (mRequiredUninstallerPackage != null &&
17514                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17515            return true;
17516        }
17517
17518        // Allow storage manager to silently uninstall.
17519        if (mStorageManagerPackage != null &&
17520                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17521            return true;
17522        }
17523        return false;
17524    }
17525
17526    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17527        int[] result = EMPTY_INT_ARRAY;
17528        for (int userId : userIds) {
17529            if (getBlockUninstallForUser(packageName, userId)) {
17530                result = ArrayUtils.appendInt(result, userId);
17531            }
17532        }
17533        return result;
17534    }
17535
17536    @Override
17537    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17538        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17539    }
17540
17541    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17542        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17543                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17544        try {
17545            if (dpm != null) {
17546                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17547                        /* callingUserOnly =*/ false);
17548                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17549                        : deviceOwnerComponentName.getPackageName();
17550                // Does the package contains the device owner?
17551                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17552                // this check is probably not needed, since DO should be registered as a device
17553                // admin on some user too. (Original bug for this: b/17657954)
17554                if (packageName.equals(deviceOwnerPackageName)) {
17555                    return true;
17556                }
17557                // Does it contain a device admin for any user?
17558                int[] users;
17559                if (userId == UserHandle.USER_ALL) {
17560                    users = sUserManager.getUserIds();
17561                } else {
17562                    users = new int[]{userId};
17563                }
17564                for (int i = 0; i < users.length; ++i) {
17565                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17566                        return true;
17567                    }
17568                }
17569            }
17570        } catch (RemoteException e) {
17571        }
17572        return false;
17573    }
17574
17575    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17576        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17577    }
17578
17579    /**
17580     *  This method is an internal method that could be get invoked either
17581     *  to delete an installed package or to clean up a failed installation.
17582     *  After deleting an installed package, a broadcast is sent to notify any
17583     *  listeners that the package has been removed. For cleaning up a failed
17584     *  installation, the broadcast is not necessary since the package's
17585     *  installation wouldn't have sent the initial broadcast either
17586     *  The key steps in deleting a package are
17587     *  deleting the package information in internal structures like mPackages,
17588     *  deleting the packages base directories through installd
17589     *  updating mSettings to reflect current status
17590     *  persisting settings for later use
17591     *  sending a broadcast if necessary
17592     */
17593    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17594        final PackageRemovedInfo info = new PackageRemovedInfo();
17595        final boolean res;
17596
17597        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17598                ? UserHandle.USER_ALL : userId;
17599
17600        if (isPackageDeviceAdmin(packageName, removeUser)) {
17601            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17602            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17603        }
17604
17605        PackageSetting uninstalledPs = null;
17606        PackageParser.Package pkg = null;
17607
17608        // for the uninstall-updates case and restricted profiles, remember the per-
17609        // user handle installed state
17610        int[] allUsers;
17611        synchronized (mPackages) {
17612            uninstalledPs = mSettings.mPackages.get(packageName);
17613            if (uninstalledPs == null) {
17614                Slog.w(TAG, "Not removing non-existent package " + packageName);
17615                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17616            }
17617
17618            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17619                    && uninstalledPs.versionCode != versionCode) {
17620                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17621                        + uninstalledPs.versionCode + " != " + versionCode);
17622                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17623            }
17624
17625            // Static shared libs can be declared by any package, so let us not
17626            // allow removing a package if it provides a lib others depend on.
17627            pkg = mPackages.get(packageName);
17628            if (pkg != null && pkg.staticSharedLibName != null) {
17629                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17630                        pkg.staticSharedLibVersion);
17631                if (libEntry != null) {
17632                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17633                            libEntry.info, 0, userId);
17634                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17635                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17636                                + " hosting lib " + libEntry.info.getName() + " version "
17637                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17638                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17639                    }
17640                }
17641            }
17642
17643            allUsers = sUserManager.getUserIds();
17644            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17645        }
17646
17647        final int freezeUser;
17648        if (isUpdatedSystemApp(uninstalledPs)
17649                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17650            // We're downgrading a system app, which will apply to all users, so
17651            // freeze them all during the downgrade
17652            freezeUser = UserHandle.USER_ALL;
17653        } else {
17654            freezeUser = removeUser;
17655        }
17656
17657        synchronized (mInstallLock) {
17658            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17659            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17660                    deleteFlags, "deletePackageX")) {
17661                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17662                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17663            }
17664            synchronized (mPackages) {
17665                if (res) {
17666                    if (pkg != null) {
17667                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17668                    }
17669                    updateSequenceNumberLP(packageName, info.removedUsers);
17670                    updateInstantAppInstallerLocked(packageName);
17671                }
17672            }
17673        }
17674
17675        if (res) {
17676            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17677            info.sendPackageRemovedBroadcasts(killApp);
17678            info.sendSystemPackageUpdatedBroadcasts();
17679            info.sendSystemPackageAppearedBroadcasts();
17680        }
17681        // Force a gc here.
17682        Runtime.getRuntime().gc();
17683        // Delete the resources here after sending the broadcast to let
17684        // other processes clean up before deleting resources.
17685        if (info.args != null) {
17686            synchronized (mInstallLock) {
17687                info.args.doPostDeleteLI(true);
17688            }
17689        }
17690
17691        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17692    }
17693
17694    class PackageRemovedInfo {
17695        String removedPackage;
17696        int uid = -1;
17697        int removedAppId = -1;
17698        int[] origUsers;
17699        int[] removedUsers = null;
17700        int[] broadcastUsers = null;
17701        SparseArray<Integer> installReasons;
17702        boolean isRemovedPackageSystemUpdate = false;
17703        boolean isUpdate;
17704        boolean dataRemoved;
17705        boolean removedForAllUsers;
17706        boolean isStaticSharedLib;
17707        // Clean up resources deleted packages.
17708        InstallArgs args = null;
17709        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17710        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17711
17712        void sendPackageRemovedBroadcasts(boolean killApp) {
17713            sendPackageRemovedBroadcastInternal(killApp);
17714            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17715            for (int i = 0; i < childCount; i++) {
17716                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17717                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17718            }
17719        }
17720
17721        void sendSystemPackageUpdatedBroadcasts() {
17722            if (isRemovedPackageSystemUpdate) {
17723                sendSystemPackageUpdatedBroadcastsInternal();
17724                final int childCount = (removedChildPackages != null)
17725                        ? removedChildPackages.size() : 0;
17726                for (int i = 0; i < childCount; i++) {
17727                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17728                    if (childInfo.isRemovedPackageSystemUpdate) {
17729                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17730                    }
17731                }
17732            }
17733        }
17734
17735        void sendSystemPackageAppearedBroadcasts() {
17736            final int packageCount = (appearedChildPackages != null)
17737                    ? appearedChildPackages.size() : 0;
17738            for (int i = 0; i < packageCount; i++) {
17739                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17740                sendPackageAddedForNewUsers(installedInfo.name, true,
17741                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17742            }
17743        }
17744
17745        private void sendSystemPackageUpdatedBroadcastsInternal() {
17746            Bundle extras = new Bundle(2);
17747            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17748            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17749            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17750                    extras, 0, null, null, null);
17751            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17752                    extras, 0, null, null, null);
17753            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17754                    null, 0, removedPackage, null, null);
17755        }
17756
17757        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17758            // Don't send static shared library removal broadcasts as these
17759            // libs are visible only the the apps that depend on them an one
17760            // cannot remove the library if it has a dependency.
17761            if (isStaticSharedLib) {
17762                return;
17763            }
17764            Bundle extras = new Bundle(2);
17765            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17766            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17767            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17768            if (isUpdate || isRemovedPackageSystemUpdate) {
17769                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17770            }
17771            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17772            if (removedPackage != null) {
17773                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17774                        extras, 0, null, null, broadcastUsers);
17775                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17776                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17777                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17778                            null, null, broadcastUsers);
17779                }
17780            }
17781            if (removedAppId >= 0) {
17782                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17783                        broadcastUsers);
17784            }
17785        }
17786    }
17787
17788    /*
17789     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17790     * flag is not set, the data directory is removed as well.
17791     * make sure this flag is set for partially installed apps. If not its meaningless to
17792     * delete a partially installed application.
17793     */
17794    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17795            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17796        String packageName = ps.name;
17797        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17798        // Retrieve object to delete permissions for shared user later on
17799        final PackageParser.Package deletedPkg;
17800        final PackageSetting deletedPs;
17801        // reader
17802        synchronized (mPackages) {
17803            deletedPkg = mPackages.get(packageName);
17804            deletedPs = mSettings.mPackages.get(packageName);
17805            if (outInfo != null) {
17806                outInfo.removedPackage = packageName;
17807                outInfo.isStaticSharedLib = deletedPkg != null
17808                        && deletedPkg.staticSharedLibName != null;
17809                outInfo.removedUsers = deletedPs != null
17810                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17811                        : null;
17812                if (outInfo.removedUsers == null) {
17813                    outInfo.broadcastUsers = null;
17814                } else {
17815                    outInfo.broadcastUsers = EMPTY_INT_ARRAY;
17816                    int[] allUsers = outInfo.removedUsers;
17817                    for (int i = allUsers.length - 1; i >= 0; --i) {
17818                        final int userId = allUsers[i];
17819                        if (deletedPs.getInstantApp(userId)) {
17820                            continue;
17821                        }
17822                        outInfo.broadcastUsers =
17823                                ArrayUtils.appendInt(outInfo.broadcastUsers, userId);
17824                    }
17825                }
17826            }
17827        }
17828
17829        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17830
17831        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17832            final PackageParser.Package resolvedPkg;
17833            if (deletedPkg != null) {
17834                resolvedPkg = deletedPkg;
17835            } else {
17836                // We don't have a parsed package when it lives on an ejected
17837                // adopted storage device, so fake something together
17838                resolvedPkg = new PackageParser.Package(ps.name);
17839                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17840            }
17841            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17842                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17843            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17844            if (outInfo != null) {
17845                outInfo.dataRemoved = true;
17846            }
17847            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17848        }
17849
17850        int removedAppId = -1;
17851
17852        // writer
17853        synchronized (mPackages) {
17854            boolean installedStateChanged = false;
17855            if (deletedPs != null) {
17856                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17857                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17858                    clearDefaultBrowserIfNeeded(packageName);
17859                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17860                    removedAppId = mSettings.removePackageLPw(packageName);
17861                    if (outInfo != null) {
17862                        outInfo.removedAppId = removedAppId;
17863                    }
17864                    updatePermissionsLPw(deletedPs.name, null, 0);
17865                    if (deletedPs.sharedUser != null) {
17866                        // Remove permissions associated with package. Since runtime
17867                        // permissions are per user we have to kill the removed package
17868                        // or packages running under the shared user of the removed
17869                        // package if revoking the permissions requested only by the removed
17870                        // package is successful and this causes a change in gids.
17871                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17872                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17873                                    userId);
17874                            if (userIdToKill == UserHandle.USER_ALL
17875                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17876                                // If gids changed for this user, kill all affected packages.
17877                                mHandler.post(new Runnable() {
17878                                    @Override
17879                                    public void run() {
17880                                        // This has to happen with no lock held.
17881                                        killApplication(deletedPs.name, deletedPs.appId,
17882                                                KILL_APP_REASON_GIDS_CHANGED);
17883                                    }
17884                                });
17885                                break;
17886                            }
17887                        }
17888                    }
17889                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17890                }
17891                // make sure to preserve per-user disabled state if this removal was just
17892                // a downgrade of a system app to the factory package
17893                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17894                    if (DEBUG_REMOVE) {
17895                        Slog.d(TAG, "Propagating install state across downgrade");
17896                    }
17897                    for (int userId : allUserHandles) {
17898                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17899                        if (DEBUG_REMOVE) {
17900                            Slog.d(TAG, "    user " + userId + " => " + installed);
17901                        }
17902                        if (installed != ps.getInstalled(userId)) {
17903                            installedStateChanged = true;
17904                        }
17905                        ps.setInstalled(installed, userId);
17906                    }
17907                }
17908            }
17909            // can downgrade to reader
17910            if (writeSettings) {
17911                // Save settings now
17912                mSettings.writeLPr();
17913            }
17914            if (installedStateChanged) {
17915                mSettings.writeKernelMappingLPr(ps);
17916            }
17917        }
17918        if (removedAppId != -1) {
17919            // A user ID was deleted here. Go through all users and remove it
17920            // from KeyStore.
17921            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17922        }
17923    }
17924
17925    static boolean locationIsPrivileged(File path) {
17926        try {
17927            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17928                    .getCanonicalPath();
17929            return path.getCanonicalPath().startsWith(privilegedAppDir);
17930        } catch (IOException e) {
17931            Slog.e(TAG, "Unable to access code path " + path);
17932        }
17933        return false;
17934    }
17935
17936    /*
17937     * Tries to delete system package.
17938     */
17939    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17940            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17941            boolean writeSettings) {
17942        if (deletedPs.parentPackageName != null) {
17943            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17944            return false;
17945        }
17946
17947        final boolean applyUserRestrictions
17948                = (allUserHandles != null) && (outInfo.origUsers != null);
17949        final PackageSetting disabledPs;
17950        // Confirm if the system package has been updated
17951        // An updated system app can be deleted. This will also have to restore
17952        // the system pkg from system partition
17953        // reader
17954        synchronized (mPackages) {
17955            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17956        }
17957
17958        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17959                + " disabledPs=" + disabledPs);
17960
17961        if (disabledPs == null) {
17962            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17963            return false;
17964        } else if (DEBUG_REMOVE) {
17965            Slog.d(TAG, "Deleting system pkg from data partition");
17966        }
17967
17968        if (DEBUG_REMOVE) {
17969            if (applyUserRestrictions) {
17970                Slog.d(TAG, "Remembering install states:");
17971                for (int userId : allUserHandles) {
17972                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17973                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17974                }
17975            }
17976        }
17977
17978        // Delete the updated package
17979        outInfo.isRemovedPackageSystemUpdate = true;
17980        if (outInfo.removedChildPackages != null) {
17981            final int childCount = (deletedPs.childPackageNames != null)
17982                    ? deletedPs.childPackageNames.size() : 0;
17983            for (int i = 0; i < childCount; i++) {
17984                String childPackageName = deletedPs.childPackageNames.get(i);
17985                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17986                        .contains(childPackageName)) {
17987                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17988                            childPackageName);
17989                    if (childInfo != null) {
17990                        childInfo.isRemovedPackageSystemUpdate = true;
17991                    }
17992                }
17993            }
17994        }
17995
17996        if (disabledPs.versionCode < deletedPs.versionCode) {
17997            // Delete data for downgrades
17998            flags &= ~PackageManager.DELETE_KEEP_DATA;
17999        } else {
18000            // Preserve data by setting flag
18001            flags |= PackageManager.DELETE_KEEP_DATA;
18002        }
18003
18004        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18005                outInfo, writeSettings, disabledPs.pkg);
18006        if (!ret) {
18007            return false;
18008        }
18009
18010        // writer
18011        synchronized (mPackages) {
18012            // Reinstate the old system package
18013            enableSystemPackageLPw(disabledPs.pkg);
18014            // Remove any native libraries from the upgraded package.
18015            removeNativeBinariesLI(deletedPs);
18016        }
18017
18018        // Install the system package
18019        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18020        int parseFlags = mDefParseFlags
18021                | PackageParser.PARSE_MUST_BE_APK
18022                | PackageParser.PARSE_IS_SYSTEM
18023                | PackageParser.PARSE_IS_SYSTEM_DIR;
18024        if (locationIsPrivileged(disabledPs.codePath)) {
18025            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18026        }
18027
18028        final PackageParser.Package newPkg;
18029        try {
18030            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18031                0 /* currentTime */, null);
18032        } catch (PackageManagerException e) {
18033            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18034                    + e.getMessage());
18035            return false;
18036        }
18037
18038        try {
18039            // update shared libraries for the newly re-installed system package
18040            updateSharedLibrariesLPr(newPkg, null);
18041        } catch (PackageManagerException e) {
18042            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18043        }
18044
18045        prepareAppDataAfterInstallLIF(newPkg);
18046
18047        // writer
18048        synchronized (mPackages) {
18049            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18050
18051            // Propagate the permissions state as we do not want to drop on the floor
18052            // runtime permissions. The update permissions method below will take
18053            // care of removing obsolete permissions and grant install permissions.
18054            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18055            updatePermissionsLPw(newPkg.packageName, newPkg,
18056                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18057
18058            if (applyUserRestrictions) {
18059                boolean installedStateChanged = false;
18060                if (DEBUG_REMOVE) {
18061                    Slog.d(TAG, "Propagating install state across reinstall");
18062                }
18063                for (int userId : allUserHandles) {
18064                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18065                    if (DEBUG_REMOVE) {
18066                        Slog.d(TAG, "    user " + userId + " => " + installed);
18067                    }
18068                    if (installed != ps.getInstalled(userId)) {
18069                        installedStateChanged = true;
18070                    }
18071                    ps.setInstalled(installed, userId);
18072
18073                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18074                }
18075                // Regardless of writeSettings we need to ensure that this restriction
18076                // state propagation is persisted
18077                mSettings.writeAllUsersPackageRestrictionsLPr();
18078                if (installedStateChanged) {
18079                    mSettings.writeKernelMappingLPr(ps);
18080                }
18081            }
18082            // can downgrade to reader here
18083            if (writeSettings) {
18084                mSettings.writeLPr();
18085            }
18086        }
18087        return true;
18088    }
18089
18090    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18091            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18092            PackageRemovedInfo outInfo, boolean writeSettings,
18093            PackageParser.Package replacingPackage) {
18094        synchronized (mPackages) {
18095            if (outInfo != null) {
18096                outInfo.uid = ps.appId;
18097            }
18098
18099            if (outInfo != null && outInfo.removedChildPackages != null) {
18100                final int childCount = (ps.childPackageNames != null)
18101                        ? ps.childPackageNames.size() : 0;
18102                for (int i = 0; i < childCount; i++) {
18103                    String childPackageName = ps.childPackageNames.get(i);
18104                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18105                    if (childPs == null) {
18106                        return false;
18107                    }
18108                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18109                            childPackageName);
18110                    if (childInfo != null) {
18111                        childInfo.uid = childPs.appId;
18112                    }
18113                }
18114            }
18115        }
18116
18117        // Delete package data from internal structures and also remove data if flag is set
18118        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18119
18120        // Delete the child packages data
18121        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18122        for (int i = 0; i < childCount; i++) {
18123            PackageSetting childPs;
18124            synchronized (mPackages) {
18125                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18126            }
18127            if (childPs != null) {
18128                PackageRemovedInfo childOutInfo = (outInfo != null
18129                        && outInfo.removedChildPackages != null)
18130                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18131                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18132                        && (replacingPackage != null
18133                        && !replacingPackage.hasChildPackage(childPs.name))
18134                        ? flags & ~DELETE_KEEP_DATA : flags;
18135                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18136                        deleteFlags, writeSettings);
18137            }
18138        }
18139
18140        // Delete application code and resources only for parent packages
18141        if (ps.parentPackageName == null) {
18142            if (deleteCodeAndResources && (outInfo != null)) {
18143                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18144                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18145                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18146            }
18147        }
18148
18149        return true;
18150    }
18151
18152    @Override
18153    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18154            int userId) {
18155        mContext.enforceCallingOrSelfPermission(
18156                android.Manifest.permission.DELETE_PACKAGES, null);
18157        synchronized (mPackages) {
18158            PackageSetting ps = mSettings.mPackages.get(packageName);
18159            if (ps == null) {
18160                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18161                return false;
18162            }
18163            // Cannot block uninstall of static shared libs as they are
18164            // considered a part of the using app (emulating static linking).
18165            // Also static libs are installed always on internal storage.
18166            PackageParser.Package pkg = mPackages.get(packageName);
18167            if (pkg != null && pkg.staticSharedLibName != null) {
18168                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18169                        + " providing static shared library: " + pkg.staticSharedLibName);
18170                return false;
18171            }
18172            if (!ps.getInstalled(userId)) {
18173                // Can't block uninstall for an app that is not installed or enabled.
18174                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18175                return false;
18176            }
18177            ps.setBlockUninstall(blockUninstall, userId);
18178            mSettings.writePackageRestrictionsLPr(userId);
18179        }
18180        return true;
18181    }
18182
18183    @Override
18184    public boolean getBlockUninstallForUser(String packageName, int userId) {
18185        synchronized (mPackages) {
18186            PackageSetting ps = mSettings.mPackages.get(packageName);
18187            if (ps == null) {
18188                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18189                return false;
18190            }
18191            return ps.getBlockUninstall(userId);
18192        }
18193    }
18194
18195    @Override
18196    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18197        int callingUid = Binder.getCallingUid();
18198        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18199            throw new SecurityException(
18200                    "setRequiredForSystemUser can only be run by the system or root");
18201        }
18202        synchronized (mPackages) {
18203            PackageSetting ps = mSettings.mPackages.get(packageName);
18204            if (ps == null) {
18205                Log.w(TAG, "Package doesn't exist: " + packageName);
18206                return false;
18207            }
18208            if (systemUserApp) {
18209                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18210            } else {
18211                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18212            }
18213            mSettings.writeLPr();
18214        }
18215        return true;
18216    }
18217
18218    /*
18219     * This method handles package deletion in general
18220     */
18221    private boolean deletePackageLIF(String packageName, UserHandle user,
18222            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18223            PackageRemovedInfo outInfo, boolean writeSettings,
18224            PackageParser.Package replacingPackage) {
18225        if (packageName == null) {
18226            Slog.w(TAG, "Attempt to delete null packageName.");
18227            return false;
18228        }
18229
18230        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18231
18232        PackageSetting ps;
18233        synchronized (mPackages) {
18234            ps = mSettings.mPackages.get(packageName);
18235            if (ps == null) {
18236                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18237                return false;
18238            }
18239
18240            if (ps.parentPackageName != null && (!isSystemApp(ps)
18241                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18242                if (DEBUG_REMOVE) {
18243                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18244                            + ((user == null) ? UserHandle.USER_ALL : user));
18245                }
18246                final int removedUserId = (user != null) ? user.getIdentifier()
18247                        : UserHandle.USER_ALL;
18248                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18249                    return false;
18250                }
18251                markPackageUninstalledForUserLPw(ps, user);
18252                scheduleWritePackageRestrictionsLocked(user);
18253                return true;
18254            }
18255        }
18256
18257        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18258                && user.getIdentifier() != UserHandle.USER_ALL)) {
18259            // The caller is asking that the package only be deleted for a single
18260            // user.  To do this, we just mark its uninstalled state and delete
18261            // its data. If this is a system app, we only allow this to happen if
18262            // they have set the special DELETE_SYSTEM_APP which requests different
18263            // semantics than normal for uninstalling system apps.
18264            markPackageUninstalledForUserLPw(ps, user);
18265
18266            if (!isSystemApp(ps)) {
18267                // Do not uninstall the APK if an app should be cached
18268                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18269                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18270                    // Other user still have this package installed, so all
18271                    // we need to do is clear this user's data and save that
18272                    // it is uninstalled.
18273                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18274                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18275                        return false;
18276                    }
18277                    scheduleWritePackageRestrictionsLocked(user);
18278                    return true;
18279                } else {
18280                    // We need to set it back to 'installed' so the uninstall
18281                    // broadcasts will be sent correctly.
18282                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18283                    ps.setInstalled(true, user.getIdentifier());
18284                    mSettings.writeKernelMappingLPr(ps);
18285                }
18286            } else {
18287                // This is a system app, so we assume that the
18288                // other users still have this package installed, so all
18289                // we need to do is clear this user's data and save that
18290                // it is uninstalled.
18291                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18292                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18293                    return false;
18294                }
18295                scheduleWritePackageRestrictionsLocked(user);
18296                return true;
18297            }
18298        }
18299
18300        // If we are deleting a composite package for all users, keep track
18301        // of result for each child.
18302        if (ps.childPackageNames != null && outInfo != null) {
18303            synchronized (mPackages) {
18304                final int childCount = ps.childPackageNames.size();
18305                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18306                for (int i = 0; i < childCount; i++) {
18307                    String childPackageName = ps.childPackageNames.get(i);
18308                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18309                    childInfo.removedPackage = childPackageName;
18310                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18311                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18312                    if (childPs != null) {
18313                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18314                    }
18315                }
18316            }
18317        }
18318
18319        boolean ret = false;
18320        if (isSystemApp(ps)) {
18321            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18322            // When an updated system application is deleted we delete the existing resources
18323            // as well and fall back to existing code in system partition
18324            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18325        } else {
18326            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18327            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18328                    outInfo, writeSettings, replacingPackage);
18329        }
18330
18331        // Take a note whether we deleted the package for all users
18332        if (outInfo != null) {
18333            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18334            if (outInfo.removedChildPackages != null) {
18335                synchronized (mPackages) {
18336                    final int childCount = outInfo.removedChildPackages.size();
18337                    for (int i = 0; i < childCount; i++) {
18338                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18339                        if (childInfo != null) {
18340                            childInfo.removedForAllUsers = mPackages.get(
18341                                    childInfo.removedPackage) == null;
18342                        }
18343                    }
18344                }
18345            }
18346            // If we uninstalled an update to a system app there may be some
18347            // child packages that appeared as they are declared in the system
18348            // app but were not declared in the update.
18349            if (isSystemApp(ps)) {
18350                synchronized (mPackages) {
18351                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18352                    final int childCount = (updatedPs.childPackageNames != null)
18353                            ? updatedPs.childPackageNames.size() : 0;
18354                    for (int i = 0; i < childCount; i++) {
18355                        String childPackageName = updatedPs.childPackageNames.get(i);
18356                        if (outInfo.removedChildPackages == null
18357                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18358                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18359                            if (childPs == null) {
18360                                continue;
18361                            }
18362                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18363                            installRes.name = childPackageName;
18364                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18365                            installRes.pkg = mPackages.get(childPackageName);
18366                            installRes.uid = childPs.pkg.applicationInfo.uid;
18367                            if (outInfo.appearedChildPackages == null) {
18368                                outInfo.appearedChildPackages = new ArrayMap<>();
18369                            }
18370                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18371                        }
18372                    }
18373                }
18374            }
18375        }
18376
18377        return ret;
18378    }
18379
18380    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18381        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18382                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18383        for (int nextUserId : userIds) {
18384            if (DEBUG_REMOVE) {
18385                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18386            }
18387            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18388                    false /*installed*/,
18389                    true /*stopped*/,
18390                    true /*notLaunched*/,
18391                    false /*hidden*/,
18392                    false /*suspended*/,
18393                    false /*instantApp*/,
18394                    null /*lastDisableAppCaller*/,
18395                    null /*enabledComponents*/,
18396                    null /*disabledComponents*/,
18397                    false /*blockUninstall*/,
18398                    ps.readUserState(nextUserId).domainVerificationStatus,
18399                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18400        }
18401        mSettings.writeKernelMappingLPr(ps);
18402    }
18403
18404    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18405            PackageRemovedInfo outInfo) {
18406        final PackageParser.Package pkg;
18407        synchronized (mPackages) {
18408            pkg = mPackages.get(ps.name);
18409        }
18410
18411        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18412                : new int[] {userId};
18413        for (int nextUserId : userIds) {
18414            if (DEBUG_REMOVE) {
18415                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18416                        + nextUserId);
18417            }
18418
18419            destroyAppDataLIF(pkg, userId,
18420                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18421            destroyAppProfilesLIF(pkg, userId);
18422            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18423            schedulePackageCleaning(ps.name, nextUserId, false);
18424            synchronized (mPackages) {
18425                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18426                    scheduleWritePackageRestrictionsLocked(nextUserId);
18427                }
18428                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18429            }
18430        }
18431
18432        if (outInfo != null) {
18433            outInfo.removedPackage = ps.name;
18434            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18435            outInfo.removedAppId = ps.appId;
18436            outInfo.removedUsers = userIds;
18437            outInfo.broadcastUsers = userIds;
18438        }
18439
18440        return true;
18441    }
18442
18443    private final class ClearStorageConnection implements ServiceConnection {
18444        IMediaContainerService mContainerService;
18445
18446        @Override
18447        public void onServiceConnected(ComponentName name, IBinder service) {
18448            synchronized (this) {
18449                mContainerService = IMediaContainerService.Stub
18450                        .asInterface(Binder.allowBlocking(service));
18451                notifyAll();
18452            }
18453        }
18454
18455        @Override
18456        public void onServiceDisconnected(ComponentName name) {
18457        }
18458    }
18459
18460    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18461        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18462
18463        final boolean mounted;
18464        if (Environment.isExternalStorageEmulated()) {
18465            mounted = true;
18466        } else {
18467            final String status = Environment.getExternalStorageState();
18468
18469            mounted = status.equals(Environment.MEDIA_MOUNTED)
18470                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18471        }
18472
18473        if (!mounted) {
18474            return;
18475        }
18476
18477        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18478        int[] users;
18479        if (userId == UserHandle.USER_ALL) {
18480            users = sUserManager.getUserIds();
18481        } else {
18482            users = new int[] { userId };
18483        }
18484        final ClearStorageConnection conn = new ClearStorageConnection();
18485        if (mContext.bindServiceAsUser(
18486                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18487            try {
18488                for (int curUser : users) {
18489                    long timeout = SystemClock.uptimeMillis() + 5000;
18490                    synchronized (conn) {
18491                        long now;
18492                        while (conn.mContainerService == null &&
18493                                (now = SystemClock.uptimeMillis()) < timeout) {
18494                            try {
18495                                conn.wait(timeout - now);
18496                            } catch (InterruptedException e) {
18497                            }
18498                        }
18499                    }
18500                    if (conn.mContainerService == null) {
18501                        return;
18502                    }
18503
18504                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18505                    clearDirectory(conn.mContainerService,
18506                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18507                    if (allData) {
18508                        clearDirectory(conn.mContainerService,
18509                                userEnv.buildExternalStorageAppDataDirs(packageName));
18510                        clearDirectory(conn.mContainerService,
18511                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18512                    }
18513                }
18514            } finally {
18515                mContext.unbindService(conn);
18516            }
18517        }
18518    }
18519
18520    @Override
18521    public void clearApplicationProfileData(String packageName) {
18522        enforceSystemOrRoot("Only the system can clear all profile data");
18523
18524        final PackageParser.Package pkg;
18525        synchronized (mPackages) {
18526            pkg = mPackages.get(packageName);
18527        }
18528
18529        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18530            synchronized (mInstallLock) {
18531                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18532            }
18533        }
18534    }
18535
18536    @Override
18537    public void clearApplicationUserData(final String packageName,
18538            final IPackageDataObserver observer, final int userId) {
18539        mContext.enforceCallingOrSelfPermission(
18540                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18541
18542        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18543                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18544
18545        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18546            throw new SecurityException("Cannot clear data for a protected package: "
18547                    + packageName);
18548        }
18549        // Queue up an async operation since the package deletion may take a little while.
18550        mHandler.post(new Runnable() {
18551            public void run() {
18552                mHandler.removeCallbacks(this);
18553                final boolean succeeded;
18554                try (PackageFreezer freezer = freezePackage(packageName,
18555                        "clearApplicationUserData")) {
18556                    synchronized (mInstallLock) {
18557                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18558                    }
18559                    clearExternalStorageDataSync(packageName, userId, true);
18560                    synchronized (mPackages) {
18561                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18562                                packageName, userId);
18563                    }
18564                }
18565                if (succeeded) {
18566                    // invoke DeviceStorageMonitor's update method to clear any notifications
18567                    DeviceStorageMonitorInternal dsm = LocalServices
18568                            .getService(DeviceStorageMonitorInternal.class);
18569                    if (dsm != null) {
18570                        dsm.checkMemory();
18571                    }
18572                }
18573                if(observer != null) {
18574                    try {
18575                        observer.onRemoveCompleted(packageName, succeeded);
18576                    } catch (RemoteException e) {
18577                        Log.i(TAG, "Observer no longer exists.");
18578                    }
18579                } //end if observer
18580            } //end run
18581        });
18582    }
18583
18584    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18585        if (packageName == null) {
18586            Slog.w(TAG, "Attempt to delete null packageName.");
18587            return false;
18588        }
18589
18590        // Try finding details about the requested package
18591        PackageParser.Package pkg;
18592        synchronized (mPackages) {
18593            pkg = mPackages.get(packageName);
18594            if (pkg == null) {
18595                final PackageSetting ps = mSettings.mPackages.get(packageName);
18596                if (ps != null) {
18597                    pkg = ps.pkg;
18598                }
18599            }
18600
18601            if (pkg == null) {
18602                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18603                return false;
18604            }
18605
18606            PackageSetting ps = (PackageSetting) pkg.mExtras;
18607            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18608        }
18609
18610        clearAppDataLIF(pkg, userId,
18611                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18612
18613        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18614        removeKeystoreDataIfNeeded(userId, appId);
18615
18616        UserManagerInternal umInternal = getUserManagerInternal();
18617        final int flags;
18618        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18619            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18620        } else if (umInternal.isUserRunning(userId)) {
18621            flags = StorageManager.FLAG_STORAGE_DE;
18622        } else {
18623            flags = 0;
18624        }
18625        prepareAppDataContentsLIF(pkg, userId, flags);
18626
18627        return true;
18628    }
18629
18630    /**
18631     * Reverts user permission state changes (permissions and flags) in
18632     * all packages for a given user.
18633     *
18634     * @param userId The device user for which to do a reset.
18635     */
18636    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18637        final int packageCount = mPackages.size();
18638        for (int i = 0; i < packageCount; i++) {
18639            PackageParser.Package pkg = mPackages.valueAt(i);
18640            PackageSetting ps = (PackageSetting) pkg.mExtras;
18641            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18642        }
18643    }
18644
18645    private void resetNetworkPolicies(int userId) {
18646        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18647    }
18648
18649    /**
18650     * Reverts user permission state changes (permissions and flags).
18651     *
18652     * @param ps The package for which to reset.
18653     * @param userId The device user for which to do a reset.
18654     */
18655    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18656            final PackageSetting ps, final int userId) {
18657        if (ps.pkg == null) {
18658            return;
18659        }
18660
18661        // These are flags that can change base on user actions.
18662        final int userSettableMask = FLAG_PERMISSION_USER_SET
18663                | FLAG_PERMISSION_USER_FIXED
18664                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18665                | FLAG_PERMISSION_REVIEW_REQUIRED;
18666
18667        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18668                | FLAG_PERMISSION_POLICY_FIXED;
18669
18670        boolean writeInstallPermissions = false;
18671        boolean writeRuntimePermissions = false;
18672
18673        final int permissionCount = ps.pkg.requestedPermissions.size();
18674        for (int i = 0; i < permissionCount; i++) {
18675            String permission = ps.pkg.requestedPermissions.get(i);
18676
18677            BasePermission bp = mSettings.mPermissions.get(permission);
18678            if (bp == null) {
18679                continue;
18680            }
18681
18682            // If shared user we just reset the state to which only this app contributed.
18683            if (ps.sharedUser != null) {
18684                boolean used = false;
18685                final int packageCount = ps.sharedUser.packages.size();
18686                for (int j = 0; j < packageCount; j++) {
18687                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18688                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18689                            && pkg.pkg.requestedPermissions.contains(permission)) {
18690                        used = true;
18691                        break;
18692                    }
18693                }
18694                if (used) {
18695                    continue;
18696                }
18697            }
18698
18699            PermissionsState permissionsState = ps.getPermissionsState();
18700
18701            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18702
18703            // Always clear the user settable flags.
18704            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18705                    bp.name) != null;
18706            // If permission review is enabled and this is a legacy app, mark the
18707            // permission as requiring a review as this is the initial state.
18708            int flags = 0;
18709            if (mPermissionReviewRequired
18710                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18711                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18712            }
18713            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18714                if (hasInstallState) {
18715                    writeInstallPermissions = true;
18716                } else {
18717                    writeRuntimePermissions = true;
18718                }
18719            }
18720
18721            // Below is only runtime permission handling.
18722            if (!bp.isRuntime()) {
18723                continue;
18724            }
18725
18726            // Never clobber system or policy.
18727            if ((oldFlags & policyOrSystemFlags) != 0) {
18728                continue;
18729            }
18730
18731            // If this permission was granted by default, make sure it is.
18732            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18733                if (permissionsState.grantRuntimePermission(bp, userId)
18734                        != PERMISSION_OPERATION_FAILURE) {
18735                    writeRuntimePermissions = true;
18736                }
18737            // If permission review is enabled the permissions for a legacy apps
18738            // are represented as constantly granted runtime ones, so don't revoke.
18739            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18740                // Otherwise, reset the permission.
18741                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18742                switch (revokeResult) {
18743                    case PERMISSION_OPERATION_SUCCESS:
18744                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18745                        writeRuntimePermissions = true;
18746                        final int appId = ps.appId;
18747                        mHandler.post(new Runnable() {
18748                            @Override
18749                            public void run() {
18750                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18751                            }
18752                        });
18753                    } break;
18754                }
18755            }
18756        }
18757
18758        // Synchronously write as we are taking permissions away.
18759        if (writeRuntimePermissions) {
18760            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18761        }
18762
18763        // Synchronously write as we are taking permissions away.
18764        if (writeInstallPermissions) {
18765            mSettings.writeLPr();
18766        }
18767    }
18768
18769    /**
18770     * Remove entries from the keystore daemon. Will only remove it if the
18771     * {@code appId} is valid.
18772     */
18773    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18774        if (appId < 0) {
18775            return;
18776        }
18777
18778        final KeyStore keyStore = KeyStore.getInstance();
18779        if (keyStore != null) {
18780            if (userId == UserHandle.USER_ALL) {
18781                for (final int individual : sUserManager.getUserIds()) {
18782                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18783                }
18784            } else {
18785                keyStore.clearUid(UserHandle.getUid(userId, appId));
18786            }
18787        } else {
18788            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18789        }
18790    }
18791
18792    @Override
18793    public void deleteApplicationCacheFiles(final String packageName,
18794            final IPackageDataObserver observer) {
18795        final int userId = UserHandle.getCallingUserId();
18796        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18797    }
18798
18799    @Override
18800    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18801            final IPackageDataObserver observer) {
18802        mContext.enforceCallingOrSelfPermission(
18803                android.Manifest.permission.DELETE_CACHE_FILES, null);
18804        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18805                /* requireFullPermission= */ true, /* checkShell= */ false,
18806                "delete application cache files");
18807
18808        final PackageParser.Package pkg;
18809        synchronized (mPackages) {
18810            pkg = mPackages.get(packageName);
18811        }
18812
18813        // Queue up an async operation since the package deletion may take a little while.
18814        mHandler.post(new Runnable() {
18815            public void run() {
18816                synchronized (mInstallLock) {
18817                    final int flags = StorageManager.FLAG_STORAGE_DE
18818                            | StorageManager.FLAG_STORAGE_CE;
18819                    // We're only clearing cache files, so we don't care if the
18820                    // app is unfrozen and still able to run
18821                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18822                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18823                }
18824                clearExternalStorageDataSync(packageName, userId, false);
18825                if (observer != null) {
18826                    try {
18827                        observer.onRemoveCompleted(packageName, true);
18828                    } catch (RemoteException e) {
18829                        Log.i(TAG, "Observer no longer exists.");
18830                    }
18831                }
18832            }
18833        });
18834    }
18835
18836    @Override
18837    public void getPackageSizeInfo(final String packageName, int userHandle,
18838            final IPackageStatsObserver observer) {
18839        throw new UnsupportedOperationException(
18840                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18841    }
18842
18843    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18844        final PackageSetting ps;
18845        synchronized (mPackages) {
18846            ps = mSettings.mPackages.get(packageName);
18847            if (ps == null) {
18848                Slog.w(TAG, "Failed to find settings for " + packageName);
18849                return false;
18850            }
18851        }
18852
18853        final String[] packageNames = { packageName };
18854        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18855        final String[] codePaths = { ps.codePathString };
18856
18857        try {
18858            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18859                    ps.appId, ceDataInodes, codePaths, stats);
18860
18861            // For now, ignore code size of packages on system partition
18862            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18863                stats.codeSize = 0;
18864            }
18865
18866            // External clients expect these to be tracked separately
18867            stats.dataSize -= stats.cacheSize;
18868
18869        } catch (InstallerException e) {
18870            Slog.w(TAG, String.valueOf(e));
18871            return false;
18872        }
18873
18874        return true;
18875    }
18876
18877    private int getUidTargetSdkVersionLockedLPr(int uid) {
18878        Object obj = mSettings.getUserIdLPr(uid);
18879        if (obj instanceof SharedUserSetting) {
18880            final SharedUserSetting sus = (SharedUserSetting) obj;
18881            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18882            final Iterator<PackageSetting> it = sus.packages.iterator();
18883            while (it.hasNext()) {
18884                final PackageSetting ps = it.next();
18885                if (ps.pkg != null) {
18886                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18887                    if (v < vers) vers = v;
18888                }
18889            }
18890            return vers;
18891        } else if (obj instanceof PackageSetting) {
18892            final PackageSetting ps = (PackageSetting) obj;
18893            if (ps.pkg != null) {
18894                return ps.pkg.applicationInfo.targetSdkVersion;
18895            }
18896        }
18897        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18898    }
18899
18900    @Override
18901    public void addPreferredActivity(IntentFilter filter, int match,
18902            ComponentName[] set, ComponentName activity, int userId) {
18903        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18904                "Adding preferred");
18905    }
18906
18907    private void addPreferredActivityInternal(IntentFilter filter, int match,
18908            ComponentName[] set, ComponentName activity, boolean always, int userId,
18909            String opname) {
18910        // writer
18911        int callingUid = Binder.getCallingUid();
18912        enforceCrossUserPermission(callingUid, userId,
18913                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18914        if (filter.countActions() == 0) {
18915            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18916            return;
18917        }
18918        synchronized (mPackages) {
18919            if (mContext.checkCallingOrSelfPermission(
18920                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18921                    != PackageManager.PERMISSION_GRANTED) {
18922                if (getUidTargetSdkVersionLockedLPr(callingUid)
18923                        < Build.VERSION_CODES.FROYO) {
18924                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18925                            + callingUid);
18926                    return;
18927                }
18928                mContext.enforceCallingOrSelfPermission(
18929                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18930            }
18931
18932            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18933            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18934                    + userId + ":");
18935            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18936            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18937            scheduleWritePackageRestrictionsLocked(userId);
18938            postPreferredActivityChangedBroadcast(userId);
18939        }
18940    }
18941
18942    private void postPreferredActivityChangedBroadcast(int userId) {
18943        mHandler.post(() -> {
18944            final IActivityManager am = ActivityManager.getService();
18945            if (am == null) {
18946                return;
18947            }
18948
18949            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18950            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18951            try {
18952                am.broadcastIntent(null, intent, null, null,
18953                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18954                        null, false, false, userId);
18955            } catch (RemoteException e) {
18956            }
18957        });
18958    }
18959
18960    @Override
18961    public void replacePreferredActivity(IntentFilter filter, int match,
18962            ComponentName[] set, ComponentName activity, int userId) {
18963        if (filter.countActions() != 1) {
18964            throw new IllegalArgumentException(
18965                    "replacePreferredActivity expects filter to have only 1 action.");
18966        }
18967        if (filter.countDataAuthorities() != 0
18968                || filter.countDataPaths() != 0
18969                || filter.countDataSchemes() > 1
18970                || filter.countDataTypes() != 0) {
18971            throw new IllegalArgumentException(
18972                    "replacePreferredActivity expects filter to have no data authorities, " +
18973                    "paths, or types; and at most one scheme.");
18974        }
18975
18976        final int callingUid = Binder.getCallingUid();
18977        enforceCrossUserPermission(callingUid, userId,
18978                true /* requireFullPermission */, false /* checkShell */,
18979                "replace preferred activity");
18980        synchronized (mPackages) {
18981            if (mContext.checkCallingOrSelfPermission(
18982                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18983                    != PackageManager.PERMISSION_GRANTED) {
18984                if (getUidTargetSdkVersionLockedLPr(callingUid)
18985                        < Build.VERSION_CODES.FROYO) {
18986                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18987                            + Binder.getCallingUid());
18988                    return;
18989                }
18990                mContext.enforceCallingOrSelfPermission(
18991                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18992            }
18993
18994            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18995            if (pir != null) {
18996                // Get all of the existing entries that exactly match this filter.
18997                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18998                if (existing != null && existing.size() == 1) {
18999                    PreferredActivity cur = existing.get(0);
19000                    if (DEBUG_PREFERRED) {
19001                        Slog.i(TAG, "Checking replace of preferred:");
19002                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19003                        if (!cur.mPref.mAlways) {
19004                            Slog.i(TAG, "  -- CUR; not mAlways!");
19005                        } else {
19006                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19007                            Slog.i(TAG, "  -- CUR: mSet="
19008                                    + Arrays.toString(cur.mPref.mSetComponents));
19009                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19010                            Slog.i(TAG, "  -- NEW: mMatch="
19011                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19012                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19013                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19014                        }
19015                    }
19016                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19017                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19018                            && cur.mPref.sameSet(set)) {
19019                        // Setting the preferred activity to what it happens to be already
19020                        if (DEBUG_PREFERRED) {
19021                            Slog.i(TAG, "Replacing with same preferred activity "
19022                                    + cur.mPref.mShortComponent + " for user "
19023                                    + userId + ":");
19024                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19025                        }
19026                        return;
19027                    }
19028                }
19029
19030                if (existing != null) {
19031                    if (DEBUG_PREFERRED) {
19032                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19033                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19034                    }
19035                    for (int i = 0; i < existing.size(); i++) {
19036                        PreferredActivity pa = existing.get(i);
19037                        if (DEBUG_PREFERRED) {
19038                            Slog.i(TAG, "Removing existing preferred activity "
19039                                    + pa.mPref.mComponent + ":");
19040                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19041                        }
19042                        pir.removeFilter(pa);
19043                    }
19044                }
19045            }
19046            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19047                    "Replacing preferred");
19048        }
19049    }
19050
19051    @Override
19052    public void clearPackagePreferredActivities(String packageName) {
19053        final int uid = Binder.getCallingUid();
19054        // writer
19055        synchronized (mPackages) {
19056            PackageParser.Package pkg = mPackages.get(packageName);
19057            if (pkg == null || pkg.applicationInfo.uid != uid) {
19058                if (mContext.checkCallingOrSelfPermission(
19059                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19060                        != PackageManager.PERMISSION_GRANTED) {
19061                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
19062                            < Build.VERSION_CODES.FROYO) {
19063                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19064                                + Binder.getCallingUid());
19065                        return;
19066                    }
19067                    mContext.enforceCallingOrSelfPermission(
19068                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19069                }
19070            }
19071
19072            int user = UserHandle.getCallingUserId();
19073            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19074                scheduleWritePackageRestrictionsLocked(user);
19075            }
19076        }
19077    }
19078
19079    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19080    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19081        ArrayList<PreferredActivity> removed = null;
19082        boolean changed = false;
19083        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19084            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19085            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19086            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19087                continue;
19088            }
19089            Iterator<PreferredActivity> it = pir.filterIterator();
19090            while (it.hasNext()) {
19091                PreferredActivity pa = it.next();
19092                // Mark entry for removal only if it matches the package name
19093                // and the entry is of type "always".
19094                if (packageName == null ||
19095                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19096                                && pa.mPref.mAlways)) {
19097                    if (removed == null) {
19098                        removed = new ArrayList<PreferredActivity>();
19099                    }
19100                    removed.add(pa);
19101                }
19102            }
19103            if (removed != null) {
19104                for (int j=0; j<removed.size(); j++) {
19105                    PreferredActivity pa = removed.get(j);
19106                    pir.removeFilter(pa);
19107                }
19108                changed = true;
19109            }
19110        }
19111        if (changed) {
19112            postPreferredActivityChangedBroadcast(userId);
19113        }
19114        return changed;
19115    }
19116
19117    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19118    private void clearIntentFilterVerificationsLPw(int userId) {
19119        final int packageCount = mPackages.size();
19120        for (int i = 0; i < packageCount; i++) {
19121            PackageParser.Package pkg = mPackages.valueAt(i);
19122            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19123        }
19124    }
19125
19126    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19127    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19128        if (userId == UserHandle.USER_ALL) {
19129            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19130                    sUserManager.getUserIds())) {
19131                for (int oneUserId : sUserManager.getUserIds()) {
19132                    scheduleWritePackageRestrictionsLocked(oneUserId);
19133                }
19134            }
19135        } else {
19136            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19137                scheduleWritePackageRestrictionsLocked(userId);
19138            }
19139        }
19140    }
19141
19142    void clearDefaultBrowserIfNeeded(String packageName) {
19143        for (int oneUserId : sUserManager.getUserIds()) {
19144            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19145            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19146            if (packageName.equals(defaultBrowserPackageName)) {
19147                setDefaultBrowserPackageName(null, oneUserId);
19148            }
19149        }
19150    }
19151
19152    @Override
19153    public void resetApplicationPreferences(int userId) {
19154        mContext.enforceCallingOrSelfPermission(
19155                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19156        final long identity = Binder.clearCallingIdentity();
19157        // writer
19158        try {
19159            synchronized (mPackages) {
19160                clearPackagePreferredActivitiesLPw(null, userId);
19161                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19162                // TODO: We have to reset the default SMS and Phone. This requires
19163                // significant refactoring to keep all default apps in the package
19164                // manager (cleaner but more work) or have the services provide
19165                // callbacks to the package manager to request a default app reset.
19166                applyFactoryDefaultBrowserLPw(userId);
19167                clearIntentFilterVerificationsLPw(userId);
19168                primeDomainVerificationsLPw(userId);
19169                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19170                scheduleWritePackageRestrictionsLocked(userId);
19171            }
19172            resetNetworkPolicies(userId);
19173        } finally {
19174            Binder.restoreCallingIdentity(identity);
19175        }
19176    }
19177
19178    @Override
19179    public int getPreferredActivities(List<IntentFilter> outFilters,
19180            List<ComponentName> outActivities, String packageName) {
19181
19182        int num = 0;
19183        final int userId = UserHandle.getCallingUserId();
19184        // reader
19185        synchronized (mPackages) {
19186            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19187            if (pir != null) {
19188                final Iterator<PreferredActivity> it = pir.filterIterator();
19189                while (it.hasNext()) {
19190                    final PreferredActivity pa = it.next();
19191                    if (packageName == null
19192                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19193                                    && pa.mPref.mAlways)) {
19194                        if (outFilters != null) {
19195                            outFilters.add(new IntentFilter(pa));
19196                        }
19197                        if (outActivities != null) {
19198                            outActivities.add(pa.mPref.mComponent);
19199                        }
19200                    }
19201                }
19202            }
19203        }
19204
19205        return num;
19206    }
19207
19208    @Override
19209    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19210            int userId) {
19211        int callingUid = Binder.getCallingUid();
19212        if (callingUid != Process.SYSTEM_UID) {
19213            throw new SecurityException(
19214                    "addPersistentPreferredActivity can only be run by the system");
19215        }
19216        if (filter.countActions() == 0) {
19217            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19218            return;
19219        }
19220        synchronized (mPackages) {
19221            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19222                    ":");
19223            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19224            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19225                    new PersistentPreferredActivity(filter, activity));
19226            scheduleWritePackageRestrictionsLocked(userId);
19227            postPreferredActivityChangedBroadcast(userId);
19228        }
19229    }
19230
19231    @Override
19232    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19233        int callingUid = Binder.getCallingUid();
19234        if (callingUid != Process.SYSTEM_UID) {
19235            throw new SecurityException(
19236                    "clearPackagePersistentPreferredActivities can only be run by the system");
19237        }
19238        ArrayList<PersistentPreferredActivity> removed = null;
19239        boolean changed = false;
19240        synchronized (mPackages) {
19241            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19242                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19243                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19244                        .valueAt(i);
19245                if (userId != thisUserId) {
19246                    continue;
19247                }
19248                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19249                while (it.hasNext()) {
19250                    PersistentPreferredActivity ppa = it.next();
19251                    // Mark entry for removal only if it matches the package name.
19252                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19253                        if (removed == null) {
19254                            removed = new ArrayList<PersistentPreferredActivity>();
19255                        }
19256                        removed.add(ppa);
19257                    }
19258                }
19259                if (removed != null) {
19260                    for (int j=0; j<removed.size(); j++) {
19261                        PersistentPreferredActivity ppa = removed.get(j);
19262                        ppir.removeFilter(ppa);
19263                    }
19264                    changed = true;
19265                }
19266            }
19267
19268            if (changed) {
19269                scheduleWritePackageRestrictionsLocked(userId);
19270                postPreferredActivityChangedBroadcast(userId);
19271            }
19272        }
19273    }
19274
19275    /**
19276     * Common machinery for picking apart a restored XML blob and passing
19277     * it to a caller-supplied functor to be applied to the running system.
19278     */
19279    private void restoreFromXml(XmlPullParser parser, int userId,
19280            String expectedStartTag, BlobXmlRestorer functor)
19281            throws IOException, XmlPullParserException {
19282        int type;
19283        while ((type = parser.next()) != XmlPullParser.START_TAG
19284                && type != XmlPullParser.END_DOCUMENT) {
19285        }
19286        if (type != XmlPullParser.START_TAG) {
19287            // oops didn't find a start tag?!
19288            if (DEBUG_BACKUP) {
19289                Slog.e(TAG, "Didn't find start tag during restore");
19290            }
19291            return;
19292        }
19293Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19294        // this is supposed to be TAG_PREFERRED_BACKUP
19295        if (!expectedStartTag.equals(parser.getName())) {
19296            if (DEBUG_BACKUP) {
19297                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19298            }
19299            return;
19300        }
19301
19302        // skip interfering stuff, then we're aligned with the backing implementation
19303        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19304Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19305        functor.apply(parser, userId);
19306    }
19307
19308    private interface BlobXmlRestorer {
19309        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19310    }
19311
19312    /**
19313     * Non-Binder method, support for the backup/restore mechanism: write the
19314     * full set of preferred activities in its canonical XML format.  Returns the
19315     * XML output as a byte array, or null if there is none.
19316     */
19317    @Override
19318    public byte[] getPreferredActivityBackup(int userId) {
19319        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19320            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19321        }
19322
19323        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19324        try {
19325            final XmlSerializer serializer = new FastXmlSerializer();
19326            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19327            serializer.startDocument(null, true);
19328            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19329
19330            synchronized (mPackages) {
19331                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19332            }
19333
19334            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19335            serializer.endDocument();
19336            serializer.flush();
19337        } catch (Exception e) {
19338            if (DEBUG_BACKUP) {
19339                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19340            }
19341            return null;
19342        }
19343
19344        return dataStream.toByteArray();
19345    }
19346
19347    @Override
19348    public void restorePreferredActivities(byte[] backup, int userId) {
19349        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19350            throw new SecurityException("Only the system may call restorePreferredActivities()");
19351        }
19352
19353        try {
19354            final XmlPullParser parser = Xml.newPullParser();
19355            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19356            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19357                    new BlobXmlRestorer() {
19358                        @Override
19359                        public void apply(XmlPullParser parser, int userId)
19360                                throws XmlPullParserException, IOException {
19361                            synchronized (mPackages) {
19362                                mSettings.readPreferredActivitiesLPw(parser, userId);
19363                            }
19364                        }
19365                    } );
19366        } catch (Exception e) {
19367            if (DEBUG_BACKUP) {
19368                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19369            }
19370        }
19371    }
19372
19373    /**
19374     * Non-Binder method, support for the backup/restore mechanism: write the
19375     * default browser (etc) settings in its canonical XML format.  Returns the default
19376     * browser XML representation as a byte array, or null if there is none.
19377     */
19378    @Override
19379    public byte[] getDefaultAppsBackup(int userId) {
19380        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19381            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19382        }
19383
19384        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19385        try {
19386            final XmlSerializer serializer = new FastXmlSerializer();
19387            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19388            serializer.startDocument(null, true);
19389            serializer.startTag(null, TAG_DEFAULT_APPS);
19390
19391            synchronized (mPackages) {
19392                mSettings.writeDefaultAppsLPr(serializer, userId);
19393            }
19394
19395            serializer.endTag(null, TAG_DEFAULT_APPS);
19396            serializer.endDocument();
19397            serializer.flush();
19398        } catch (Exception e) {
19399            if (DEBUG_BACKUP) {
19400                Slog.e(TAG, "Unable to write default apps for backup", e);
19401            }
19402            return null;
19403        }
19404
19405        return dataStream.toByteArray();
19406    }
19407
19408    @Override
19409    public void restoreDefaultApps(byte[] backup, int userId) {
19410        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19411            throw new SecurityException("Only the system may call restoreDefaultApps()");
19412        }
19413
19414        try {
19415            final XmlPullParser parser = Xml.newPullParser();
19416            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19417            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19418                    new BlobXmlRestorer() {
19419                        @Override
19420                        public void apply(XmlPullParser parser, int userId)
19421                                throws XmlPullParserException, IOException {
19422                            synchronized (mPackages) {
19423                                mSettings.readDefaultAppsLPw(parser, userId);
19424                            }
19425                        }
19426                    } );
19427        } catch (Exception e) {
19428            if (DEBUG_BACKUP) {
19429                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19430            }
19431        }
19432    }
19433
19434    @Override
19435    public byte[] getIntentFilterVerificationBackup(int userId) {
19436        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19437            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19438        }
19439
19440        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19441        try {
19442            final XmlSerializer serializer = new FastXmlSerializer();
19443            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19444            serializer.startDocument(null, true);
19445            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19446
19447            synchronized (mPackages) {
19448                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19449            }
19450
19451            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19452            serializer.endDocument();
19453            serializer.flush();
19454        } catch (Exception e) {
19455            if (DEBUG_BACKUP) {
19456                Slog.e(TAG, "Unable to write default apps for backup", e);
19457            }
19458            return null;
19459        }
19460
19461        return dataStream.toByteArray();
19462    }
19463
19464    @Override
19465    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19466        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19467            throw new SecurityException("Only the system may call restorePreferredActivities()");
19468        }
19469
19470        try {
19471            final XmlPullParser parser = Xml.newPullParser();
19472            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19473            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19474                    new BlobXmlRestorer() {
19475                        @Override
19476                        public void apply(XmlPullParser parser, int userId)
19477                                throws XmlPullParserException, IOException {
19478                            synchronized (mPackages) {
19479                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19480                                mSettings.writeLPr();
19481                            }
19482                        }
19483                    } );
19484        } catch (Exception e) {
19485            if (DEBUG_BACKUP) {
19486                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19487            }
19488        }
19489    }
19490
19491    @Override
19492    public byte[] getPermissionGrantBackup(int userId) {
19493        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19494            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
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_PERMISSION_BACKUP);
19503
19504            synchronized (mPackages) {
19505                serializeRuntimePermissionGrantsLPr(serializer, userId);
19506            }
19507
19508            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19509            serializer.endDocument();
19510            serializer.flush();
19511        } catch (Exception e) {
19512            if (DEBUG_BACKUP) {
19513                Slog.e(TAG, "Unable to write default apps for backup", e);
19514            }
19515            return null;
19516        }
19517
19518        return dataStream.toByteArray();
19519    }
19520
19521    @Override
19522    public void restorePermissionGrants(byte[] backup, int userId) {
19523        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19524            throw new SecurityException("Only the system may call restorePermissionGrants()");
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_PERMISSION_BACKUP,
19531                    new BlobXmlRestorer() {
19532                        @Override
19533                        public void apply(XmlPullParser parser, int userId)
19534                                throws XmlPullParserException, IOException {
19535                            synchronized (mPackages) {
19536                                processRestoredPermissionGrantsLPr(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    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19548            throws IOException {
19549        serializer.startTag(null, TAG_ALL_GRANTS);
19550
19551        final int N = mSettings.mPackages.size();
19552        for (int i = 0; i < N; i++) {
19553            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19554            boolean pkgGrantsKnown = false;
19555
19556            PermissionsState packagePerms = ps.getPermissionsState();
19557
19558            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19559                final int grantFlags = state.getFlags();
19560                // only look at grants that are not system/policy fixed
19561                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19562                    final boolean isGranted = state.isGranted();
19563                    // And only back up the user-twiddled state bits
19564                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19565                        final String packageName = mSettings.mPackages.keyAt(i);
19566                        if (!pkgGrantsKnown) {
19567                            serializer.startTag(null, TAG_GRANT);
19568                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19569                            pkgGrantsKnown = true;
19570                        }
19571
19572                        final boolean userSet =
19573                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19574                        final boolean userFixed =
19575                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19576                        final boolean revoke =
19577                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19578
19579                        serializer.startTag(null, TAG_PERMISSION);
19580                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19581                        if (isGranted) {
19582                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19583                        }
19584                        if (userSet) {
19585                            serializer.attribute(null, ATTR_USER_SET, "true");
19586                        }
19587                        if (userFixed) {
19588                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19589                        }
19590                        if (revoke) {
19591                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19592                        }
19593                        serializer.endTag(null, TAG_PERMISSION);
19594                    }
19595                }
19596            }
19597
19598            if (pkgGrantsKnown) {
19599                serializer.endTag(null, TAG_GRANT);
19600            }
19601        }
19602
19603        serializer.endTag(null, TAG_ALL_GRANTS);
19604    }
19605
19606    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19607            throws XmlPullParserException, IOException {
19608        String pkgName = null;
19609        int outerDepth = parser.getDepth();
19610        int type;
19611        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19612                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19613            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19614                continue;
19615            }
19616
19617            final String tagName = parser.getName();
19618            if (tagName.equals(TAG_GRANT)) {
19619                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19620                if (DEBUG_BACKUP) {
19621                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19622                }
19623            } else if (tagName.equals(TAG_PERMISSION)) {
19624
19625                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19626                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19627
19628                int newFlagSet = 0;
19629                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19630                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19631                }
19632                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19633                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19634                }
19635                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19636                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19637                }
19638                if (DEBUG_BACKUP) {
19639                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19640                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19641                }
19642                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19643                if (ps != null) {
19644                    // Already installed so we apply the grant immediately
19645                    if (DEBUG_BACKUP) {
19646                        Slog.v(TAG, "        + already installed; applying");
19647                    }
19648                    PermissionsState perms = ps.getPermissionsState();
19649                    BasePermission bp = mSettings.mPermissions.get(permName);
19650                    if (bp != null) {
19651                        if (isGranted) {
19652                            perms.grantRuntimePermission(bp, userId);
19653                        }
19654                        if (newFlagSet != 0) {
19655                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19656                        }
19657                    }
19658                } else {
19659                    // Need to wait for post-restore install to apply the grant
19660                    if (DEBUG_BACKUP) {
19661                        Slog.v(TAG, "        - not yet installed; saving for later");
19662                    }
19663                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19664                            isGranted, newFlagSet, userId);
19665                }
19666            } else {
19667                PackageManagerService.reportSettingsProblem(Log.WARN,
19668                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19669                XmlUtils.skipCurrentTag(parser);
19670            }
19671        }
19672
19673        scheduleWriteSettingsLocked();
19674        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19675    }
19676
19677    @Override
19678    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19679            int sourceUserId, int targetUserId, int flags) {
19680        mContext.enforceCallingOrSelfPermission(
19681                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19682        int callingUid = Binder.getCallingUid();
19683        enforceOwnerRights(ownerPackage, callingUid);
19684        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19685        if (intentFilter.countActions() == 0) {
19686            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19687            return;
19688        }
19689        synchronized (mPackages) {
19690            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19691                    ownerPackage, targetUserId, flags);
19692            CrossProfileIntentResolver resolver =
19693                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19694            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19695            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19696            if (existing != null) {
19697                int size = existing.size();
19698                for (int i = 0; i < size; i++) {
19699                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19700                        return;
19701                    }
19702                }
19703            }
19704            resolver.addFilter(newFilter);
19705            scheduleWritePackageRestrictionsLocked(sourceUserId);
19706        }
19707    }
19708
19709    @Override
19710    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19711        mContext.enforceCallingOrSelfPermission(
19712                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19713        int callingUid = Binder.getCallingUid();
19714        enforceOwnerRights(ownerPackage, callingUid);
19715        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19716        synchronized (mPackages) {
19717            CrossProfileIntentResolver resolver =
19718                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19719            ArraySet<CrossProfileIntentFilter> set =
19720                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19721            for (CrossProfileIntentFilter filter : set) {
19722                if (filter.getOwnerPackage().equals(ownerPackage)) {
19723                    resolver.removeFilter(filter);
19724                }
19725            }
19726            scheduleWritePackageRestrictionsLocked(sourceUserId);
19727        }
19728    }
19729
19730    // Enforcing that callingUid is owning pkg on userId
19731    private void enforceOwnerRights(String pkg, int callingUid) {
19732        // The system owns everything.
19733        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19734            return;
19735        }
19736        int callingUserId = UserHandle.getUserId(callingUid);
19737        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19738        if (pi == null) {
19739            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19740                    + callingUserId);
19741        }
19742        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19743            throw new SecurityException("Calling uid " + callingUid
19744                    + " does not own package " + pkg);
19745        }
19746    }
19747
19748    @Override
19749    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19750        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19751    }
19752
19753    /**
19754     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19755     * then reports the most likely home activity or null if there are more than one.
19756     */
19757    public ComponentName getDefaultHomeActivity(int userId) {
19758        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19759        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19760        if (cn != null) {
19761            return cn;
19762        }
19763
19764        // Find the launcher with the highest priority and return that component if there are no
19765        // other home activity with the same priority.
19766        int lastPriority = Integer.MIN_VALUE;
19767        ComponentName lastComponent = null;
19768        final int size = allHomeCandidates.size();
19769        for (int i = 0; i < size; i++) {
19770            final ResolveInfo ri = allHomeCandidates.get(i);
19771            if (ri.priority > lastPriority) {
19772                lastComponent = ri.activityInfo.getComponentName();
19773                lastPriority = ri.priority;
19774            } else if (ri.priority == lastPriority) {
19775                // Two components found with same priority.
19776                lastComponent = null;
19777            }
19778        }
19779        return lastComponent;
19780    }
19781
19782    private Intent getHomeIntent() {
19783        Intent intent = new Intent(Intent.ACTION_MAIN);
19784        intent.addCategory(Intent.CATEGORY_HOME);
19785        intent.addCategory(Intent.CATEGORY_DEFAULT);
19786        return intent;
19787    }
19788
19789    private IntentFilter getHomeFilter() {
19790        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19791        filter.addCategory(Intent.CATEGORY_HOME);
19792        filter.addCategory(Intent.CATEGORY_DEFAULT);
19793        return filter;
19794    }
19795
19796    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19797            int userId) {
19798        Intent intent  = getHomeIntent();
19799        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19800                PackageManager.GET_META_DATA, userId);
19801        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19802                true, false, false, userId);
19803
19804        allHomeCandidates.clear();
19805        if (list != null) {
19806            for (ResolveInfo ri : list) {
19807                allHomeCandidates.add(ri);
19808            }
19809        }
19810        return (preferred == null || preferred.activityInfo == null)
19811                ? null
19812                : new ComponentName(preferred.activityInfo.packageName,
19813                        preferred.activityInfo.name);
19814    }
19815
19816    @Override
19817    public void setHomeActivity(ComponentName comp, int userId) {
19818        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19819        getHomeActivitiesAsUser(homeActivities, userId);
19820
19821        boolean found = false;
19822
19823        final int size = homeActivities.size();
19824        final ComponentName[] set = new ComponentName[size];
19825        for (int i = 0; i < size; i++) {
19826            final ResolveInfo candidate = homeActivities.get(i);
19827            final ActivityInfo info = candidate.activityInfo;
19828            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19829            set[i] = activityName;
19830            if (!found && activityName.equals(comp)) {
19831                found = true;
19832            }
19833        }
19834        if (!found) {
19835            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19836                    + userId);
19837        }
19838        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19839                set, comp, userId);
19840    }
19841
19842    private @Nullable String getSetupWizardPackageName() {
19843        final Intent intent = new Intent(Intent.ACTION_MAIN);
19844        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19845
19846        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19847                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19848                        | MATCH_DISABLED_COMPONENTS,
19849                UserHandle.myUserId());
19850        if (matches.size() == 1) {
19851            return matches.get(0).getComponentInfo().packageName;
19852        } else {
19853            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19854                    + ": matches=" + matches);
19855            return null;
19856        }
19857    }
19858
19859    private @Nullable String getStorageManagerPackageName() {
19860        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19861
19862        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19863                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19864                        | MATCH_DISABLED_COMPONENTS,
19865                UserHandle.myUserId());
19866        if (matches.size() == 1) {
19867            return matches.get(0).getComponentInfo().packageName;
19868        } else {
19869            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19870                    + matches.size() + ": matches=" + matches);
19871            return null;
19872        }
19873    }
19874
19875    @Override
19876    public void setApplicationEnabledSetting(String appPackageName,
19877            int newState, int flags, int userId, String callingPackage) {
19878        if (!sUserManager.exists(userId)) return;
19879        if (callingPackage == null) {
19880            callingPackage = Integer.toString(Binder.getCallingUid());
19881        }
19882        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19883    }
19884
19885    @Override
19886    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19887        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19888        synchronized (mPackages) {
19889            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19890            if (pkgSetting != null) {
19891                pkgSetting.setUpdateAvailable(updateAvailable);
19892            }
19893        }
19894    }
19895
19896    @Override
19897    public void setComponentEnabledSetting(ComponentName componentName,
19898            int newState, int flags, int userId) {
19899        if (!sUserManager.exists(userId)) return;
19900        setEnabledSetting(componentName.getPackageName(),
19901                componentName.getClassName(), newState, flags, userId, null);
19902    }
19903
19904    private void setEnabledSetting(final String packageName, String className, int newState,
19905            final int flags, int userId, String callingPackage) {
19906        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19907              || newState == COMPONENT_ENABLED_STATE_ENABLED
19908              || newState == COMPONENT_ENABLED_STATE_DISABLED
19909              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19910              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19911            throw new IllegalArgumentException("Invalid new component state: "
19912                    + newState);
19913        }
19914        PackageSetting pkgSetting;
19915        final int uid = Binder.getCallingUid();
19916        final int permission;
19917        if (uid == Process.SYSTEM_UID) {
19918            permission = PackageManager.PERMISSION_GRANTED;
19919        } else {
19920            permission = mContext.checkCallingOrSelfPermission(
19921                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19922        }
19923        enforceCrossUserPermission(uid, userId,
19924                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19925        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19926        boolean sendNow = false;
19927        boolean isApp = (className == null);
19928        String componentName = isApp ? packageName : className;
19929        int packageUid = -1;
19930        ArrayList<String> components;
19931
19932        // writer
19933        synchronized (mPackages) {
19934            pkgSetting = mSettings.mPackages.get(packageName);
19935            if (pkgSetting == null) {
19936                if (className == null) {
19937                    throw new IllegalArgumentException("Unknown package: " + packageName);
19938                }
19939                throw new IllegalArgumentException(
19940                        "Unknown component: " + packageName + "/" + className);
19941            }
19942        }
19943
19944        // Limit who can change which apps
19945        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19946            // Don't allow apps that don't have permission to modify other apps
19947            if (!allowedByPermission) {
19948                throw new SecurityException(
19949                        "Permission Denial: attempt to change component state from pid="
19950                        + Binder.getCallingPid()
19951                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19952            }
19953            // Don't allow changing protected packages.
19954            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19955                throw new SecurityException("Cannot disable a protected package: " + packageName);
19956            }
19957        }
19958
19959        synchronized (mPackages) {
19960            if (uid == Process.SHELL_UID
19961                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19962                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19963                // unless it is a test package.
19964                int oldState = pkgSetting.getEnabled(userId);
19965                if (className == null
19966                    &&
19967                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19968                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19969                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19970                    &&
19971                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19972                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19973                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19974                    // ok
19975                } else {
19976                    throw new SecurityException(
19977                            "Shell cannot change component state for " + packageName + "/"
19978                            + className + " to " + newState);
19979                }
19980            }
19981            if (className == null) {
19982                // We're dealing with an application/package level state change
19983                if (pkgSetting.getEnabled(userId) == newState) {
19984                    // Nothing to do
19985                    return;
19986                }
19987                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19988                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19989                    // Don't care about who enables an app.
19990                    callingPackage = null;
19991                }
19992                pkgSetting.setEnabled(newState, userId, callingPackage);
19993                // pkgSetting.pkg.mSetEnabled = newState;
19994            } else {
19995                // We're dealing with a component level state change
19996                // First, verify that this is a valid class name.
19997                PackageParser.Package pkg = pkgSetting.pkg;
19998                if (pkg == null || !pkg.hasComponentClassName(className)) {
19999                    if (pkg != null &&
20000                            pkg.applicationInfo.targetSdkVersion >=
20001                                    Build.VERSION_CODES.JELLY_BEAN) {
20002                        throw new IllegalArgumentException("Component class " + className
20003                                + " does not exist in " + packageName);
20004                    } else {
20005                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20006                                + className + " does not exist in " + packageName);
20007                    }
20008                }
20009                switch (newState) {
20010                case COMPONENT_ENABLED_STATE_ENABLED:
20011                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20012                        return;
20013                    }
20014                    break;
20015                case COMPONENT_ENABLED_STATE_DISABLED:
20016                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20017                        return;
20018                    }
20019                    break;
20020                case COMPONENT_ENABLED_STATE_DEFAULT:
20021                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20022                        return;
20023                    }
20024                    break;
20025                default:
20026                    Slog.e(TAG, "Invalid new component state: " + newState);
20027                    return;
20028                }
20029            }
20030            scheduleWritePackageRestrictionsLocked(userId);
20031            updateSequenceNumberLP(packageName, new int[] { userId });
20032            final long callingId = Binder.clearCallingIdentity();
20033            try {
20034                updateInstantAppInstallerLocked(packageName);
20035            } finally {
20036                Binder.restoreCallingIdentity(callingId);
20037            }
20038            components = mPendingBroadcasts.get(userId, packageName);
20039            final boolean newPackage = components == null;
20040            if (newPackage) {
20041                components = new ArrayList<String>();
20042            }
20043            if (!components.contains(componentName)) {
20044                components.add(componentName);
20045            }
20046            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20047                sendNow = true;
20048                // Purge entry from pending broadcast list if another one exists already
20049                // since we are sending one right away.
20050                mPendingBroadcasts.remove(userId, packageName);
20051            } else {
20052                if (newPackage) {
20053                    mPendingBroadcasts.put(userId, packageName, components);
20054                }
20055                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20056                    // Schedule a message
20057                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20058                }
20059            }
20060        }
20061
20062        long callingId = Binder.clearCallingIdentity();
20063        try {
20064            if (sendNow) {
20065                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20066                sendPackageChangedBroadcast(packageName,
20067                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20068            }
20069        } finally {
20070            Binder.restoreCallingIdentity(callingId);
20071        }
20072    }
20073
20074    @Override
20075    public void flushPackageRestrictionsAsUser(int userId) {
20076        if (!sUserManager.exists(userId)) {
20077            return;
20078        }
20079        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20080                false /* checkShell */, "flushPackageRestrictions");
20081        synchronized (mPackages) {
20082            mSettings.writePackageRestrictionsLPr(userId);
20083            mDirtyUsers.remove(userId);
20084            if (mDirtyUsers.isEmpty()) {
20085                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20086            }
20087        }
20088    }
20089
20090    private void sendPackageChangedBroadcast(String packageName,
20091            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20092        if (DEBUG_INSTALL)
20093            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20094                    + componentNames);
20095        Bundle extras = new Bundle(4);
20096        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20097        String nameList[] = new String[componentNames.size()];
20098        componentNames.toArray(nameList);
20099        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20100        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20101        extras.putInt(Intent.EXTRA_UID, packageUid);
20102        // If this is not reporting a change of the overall package, then only send it
20103        // to registered receivers.  We don't want to launch a swath of apps for every
20104        // little component state change.
20105        final int flags = !componentNames.contains(packageName)
20106                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20107        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20108                new int[] {UserHandle.getUserId(packageUid)});
20109    }
20110
20111    @Override
20112    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20113        if (!sUserManager.exists(userId)) return;
20114        final int uid = Binder.getCallingUid();
20115        final int permission = mContext.checkCallingOrSelfPermission(
20116                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20117        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20118        enforceCrossUserPermission(uid, userId,
20119                true /* requireFullPermission */, true /* checkShell */, "stop package");
20120        // writer
20121        synchronized (mPackages) {
20122            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20123                    allowedByPermission, uid, userId)) {
20124                scheduleWritePackageRestrictionsLocked(userId);
20125            }
20126        }
20127    }
20128
20129    @Override
20130    public String getInstallerPackageName(String packageName) {
20131        // reader
20132        synchronized (mPackages) {
20133            return mSettings.getInstallerPackageNameLPr(packageName);
20134        }
20135    }
20136
20137    public boolean isOrphaned(String packageName) {
20138        // reader
20139        synchronized (mPackages) {
20140            return mSettings.isOrphaned(packageName);
20141        }
20142    }
20143
20144    @Override
20145    public int getApplicationEnabledSetting(String packageName, int userId) {
20146        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20147        int uid = Binder.getCallingUid();
20148        enforceCrossUserPermission(uid, userId,
20149                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20150        // reader
20151        synchronized (mPackages) {
20152            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20153        }
20154    }
20155
20156    @Override
20157    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20158        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20159        int uid = Binder.getCallingUid();
20160        enforceCrossUserPermission(uid, userId,
20161                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20162        // reader
20163        synchronized (mPackages) {
20164            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20165        }
20166    }
20167
20168    @Override
20169    public void enterSafeMode() {
20170        enforceSystemOrRoot("Only the system can request entering safe mode");
20171
20172        if (!mSystemReady) {
20173            mSafeMode = true;
20174        }
20175    }
20176
20177    @Override
20178    public void systemReady() {
20179        mSystemReady = true;
20180        final ContentResolver resolver = mContext.getContentResolver();
20181        ContentObserver co = new ContentObserver(mHandler) {
20182            @Override
20183            public void onChange(boolean selfChange) {
20184                mEphemeralAppsDisabled =
20185                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20186                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20187            }
20188        };
20189        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20190                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20191                false, co, UserHandle.USER_SYSTEM);
20192        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20193                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20194        co.onChange(true);
20195
20196        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20197        // disabled after already being started.
20198        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20199                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20200
20201        // Read the compatibilty setting when the system is ready.
20202        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20203                mContext.getContentResolver(),
20204                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20205        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20206        if (DEBUG_SETTINGS) {
20207            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20208        }
20209
20210        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20211
20212        synchronized (mPackages) {
20213            // Verify that all of the preferred activity components actually
20214            // exist.  It is possible for applications to be updated and at
20215            // that point remove a previously declared activity component that
20216            // had been set as a preferred activity.  We try to clean this up
20217            // the next time we encounter that preferred activity, but it is
20218            // possible for the user flow to never be able to return to that
20219            // situation so here we do a sanity check to make sure we haven't
20220            // left any junk around.
20221            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20222            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20223                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20224                removed.clear();
20225                for (PreferredActivity pa : pir.filterSet()) {
20226                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20227                        removed.add(pa);
20228                    }
20229                }
20230                if (removed.size() > 0) {
20231                    for (int r=0; r<removed.size(); r++) {
20232                        PreferredActivity pa = removed.get(r);
20233                        Slog.w(TAG, "Removing dangling preferred activity: "
20234                                + pa.mPref.mComponent);
20235                        pir.removeFilter(pa);
20236                    }
20237                    mSettings.writePackageRestrictionsLPr(
20238                            mSettings.mPreferredActivities.keyAt(i));
20239                }
20240            }
20241
20242            for (int userId : UserManagerService.getInstance().getUserIds()) {
20243                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20244                    grantPermissionsUserIds = ArrayUtils.appendInt(
20245                            grantPermissionsUserIds, userId);
20246                }
20247            }
20248        }
20249        sUserManager.systemReady();
20250
20251        // If we upgraded grant all default permissions before kicking off.
20252        for (int userId : grantPermissionsUserIds) {
20253            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20254        }
20255
20256        // If we did not grant default permissions, we preload from this the
20257        // default permission exceptions lazily to ensure we don't hit the
20258        // disk on a new user creation.
20259        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20260            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20261        }
20262
20263        // Kick off any messages waiting for system ready
20264        if (mPostSystemReadyMessages != null) {
20265            for (Message msg : mPostSystemReadyMessages) {
20266                msg.sendToTarget();
20267            }
20268            mPostSystemReadyMessages = null;
20269        }
20270
20271        // Watch for external volumes that come and go over time
20272        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20273        storage.registerListener(mStorageListener);
20274
20275        mInstallerService.systemReady();
20276        mPackageDexOptimizer.systemReady();
20277
20278        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20279                StorageManagerInternal.class);
20280        StorageManagerInternal.addExternalStoragePolicy(
20281                new StorageManagerInternal.ExternalStorageMountPolicy() {
20282            @Override
20283            public int getMountMode(int uid, String packageName) {
20284                if (Process.isIsolated(uid)) {
20285                    return Zygote.MOUNT_EXTERNAL_NONE;
20286                }
20287                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20288                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20289                }
20290                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20291                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20292                }
20293                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20294                    return Zygote.MOUNT_EXTERNAL_READ;
20295                }
20296                return Zygote.MOUNT_EXTERNAL_WRITE;
20297            }
20298
20299            @Override
20300            public boolean hasExternalStorage(int uid, String packageName) {
20301                return true;
20302            }
20303        });
20304
20305        // Now that we're mostly running, clean up stale users and apps
20306        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20307        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20308
20309        if (mPrivappPermissionsViolations != null) {
20310            Slog.wtf(TAG,"Signature|privileged permissions not in "
20311                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20312            mPrivappPermissionsViolations = null;
20313        }
20314    }
20315
20316    public void waitForAppDataPrepared() {
20317        if (mPrepareAppDataFuture == null) {
20318            return;
20319        }
20320        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20321        mPrepareAppDataFuture = null;
20322    }
20323
20324    @Override
20325    public boolean isSafeMode() {
20326        return mSafeMode;
20327    }
20328
20329    @Override
20330    public boolean hasSystemUidErrors() {
20331        return mHasSystemUidErrors;
20332    }
20333
20334    static String arrayToString(int[] array) {
20335        StringBuffer buf = new StringBuffer(128);
20336        buf.append('[');
20337        if (array != null) {
20338            for (int i=0; i<array.length; i++) {
20339                if (i > 0) buf.append(", ");
20340                buf.append(array[i]);
20341            }
20342        }
20343        buf.append(']');
20344        return buf.toString();
20345    }
20346
20347    static class DumpState {
20348        public static final int DUMP_LIBS = 1 << 0;
20349        public static final int DUMP_FEATURES = 1 << 1;
20350        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20351        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20352        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20353        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20354        public static final int DUMP_PERMISSIONS = 1 << 6;
20355        public static final int DUMP_PACKAGES = 1 << 7;
20356        public static final int DUMP_SHARED_USERS = 1 << 8;
20357        public static final int DUMP_MESSAGES = 1 << 9;
20358        public static final int DUMP_PROVIDERS = 1 << 10;
20359        public static final int DUMP_VERIFIERS = 1 << 11;
20360        public static final int DUMP_PREFERRED = 1 << 12;
20361        public static final int DUMP_PREFERRED_XML = 1 << 13;
20362        public static final int DUMP_KEYSETS = 1 << 14;
20363        public static final int DUMP_VERSION = 1 << 15;
20364        public static final int DUMP_INSTALLS = 1 << 16;
20365        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20366        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20367        public static final int DUMP_FROZEN = 1 << 19;
20368        public static final int DUMP_DEXOPT = 1 << 20;
20369        public static final int DUMP_COMPILER_STATS = 1 << 21;
20370        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20371
20372        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20373
20374        private int mTypes;
20375
20376        private int mOptions;
20377
20378        private boolean mTitlePrinted;
20379
20380        private SharedUserSetting mSharedUser;
20381
20382        public boolean isDumping(int type) {
20383            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20384                return true;
20385            }
20386
20387            return (mTypes & type) != 0;
20388        }
20389
20390        public void setDump(int type) {
20391            mTypes |= type;
20392        }
20393
20394        public boolean isOptionEnabled(int option) {
20395            return (mOptions & option) != 0;
20396        }
20397
20398        public void setOptionEnabled(int option) {
20399            mOptions |= option;
20400        }
20401
20402        public boolean onTitlePrinted() {
20403            final boolean printed = mTitlePrinted;
20404            mTitlePrinted = true;
20405            return printed;
20406        }
20407
20408        public boolean getTitlePrinted() {
20409            return mTitlePrinted;
20410        }
20411
20412        public void setTitlePrinted(boolean enabled) {
20413            mTitlePrinted = enabled;
20414        }
20415
20416        public SharedUserSetting getSharedUser() {
20417            return mSharedUser;
20418        }
20419
20420        public void setSharedUser(SharedUserSetting user) {
20421            mSharedUser = user;
20422        }
20423    }
20424
20425    @Override
20426    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20427            FileDescriptor err, String[] args, ShellCallback callback,
20428            ResultReceiver resultReceiver) {
20429        (new PackageManagerShellCommand(this)).exec(
20430                this, in, out, err, args, callback, resultReceiver);
20431    }
20432
20433    @Override
20434    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20435        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20436
20437        DumpState dumpState = new DumpState();
20438        boolean fullPreferred = false;
20439        boolean checkin = false;
20440
20441        String packageName = null;
20442        ArraySet<String> permissionNames = null;
20443
20444        int opti = 0;
20445        while (opti < args.length) {
20446            String opt = args[opti];
20447            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20448                break;
20449            }
20450            opti++;
20451
20452            if ("-a".equals(opt)) {
20453                // Right now we only know how to print all.
20454            } else if ("-h".equals(opt)) {
20455                pw.println("Package manager dump options:");
20456                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20457                pw.println("    --checkin: dump for a checkin");
20458                pw.println("    -f: print details of intent filters");
20459                pw.println("    -h: print this help");
20460                pw.println("  cmd may be one of:");
20461                pw.println("    l[ibraries]: list known shared libraries");
20462                pw.println("    f[eatures]: list device features");
20463                pw.println("    k[eysets]: print known keysets");
20464                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20465                pw.println("    perm[issions]: dump permissions");
20466                pw.println("    permission [name ...]: dump declaration and use of given permission");
20467                pw.println("    pref[erred]: print preferred package settings");
20468                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20469                pw.println("    prov[iders]: dump content providers");
20470                pw.println("    p[ackages]: dump installed packages");
20471                pw.println("    s[hared-users]: dump shared user IDs");
20472                pw.println("    m[essages]: print collected runtime messages");
20473                pw.println("    v[erifiers]: print package verifier info");
20474                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20475                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20476                pw.println("    version: print database version info");
20477                pw.println("    write: write current settings now");
20478                pw.println("    installs: details about install sessions");
20479                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20480                pw.println("    dexopt: dump dexopt state");
20481                pw.println("    compiler-stats: dump compiler statistics");
20482                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20483                pw.println("    <package.name>: info about given package");
20484                return;
20485            } else if ("--checkin".equals(opt)) {
20486                checkin = true;
20487            } else if ("-f".equals(opt)) {
20488                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20489            } else if ("--proto".equals(opt)) {
20490                dumpProto(fd);
20491                return;
20492            } else {
20493                pw.println("Unknown argument: " + opt + "; use -h for help");
20494            }
20495        }
20496
20497        // Is the caller requesting to dump a particular piece of data?
20498        if (opti < args.length) {
20499            String cmd = args[opti];
20500            opti++;
20501            // Is this a package name?
20502            if ("android".equals(cmd) || cmd.contains(".")) {
20503                packageName = cmd;
20504                // When dumping a single package, we always dump all of its
20505                // filter information since the amount of data will be reasonable.
20506                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20507            } else if ("check-permission".equals(cmd)) {
20508                if (opti >= args.length) {
20509                    pw.println("Error: check-permission missing permission argument");
20510                    return;
20511                }
20512                String perm = args[opti];
20513                opti++;
20514                if (opti >= args.length) {
20515                    pw.println("Error: check-permission missing package argument");
20516                    return;
20517                }
20518
20519                String pkg = args[opti];
20520                opti++;
20521                int user = UserHandle.getUserId(Binder.getCallingUid());
20522                if (opti < args.length) {
20523                    try {
20524                        user = Integer.parseInt(args[opti]);
20525                    } catch (NumberFormatException e) {
20526                        pw.println("Error: check-permission user argument is not a number: "
20527                                + args[opti]);
20528                        return;
20529                    }
20530                }
20531
20532                // Normalize package name to handle renamed packages and static libs
20533                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20534
20535                pw.println(checkPermission(perm, pkg, user));
20536                return;
20537            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20538                dumpState.setDump(DumpState.DUMP_LIBS);
20539            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20540                dumpState.setDump(DumpState.DUMP_FEATURES);
20541            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20542                if (opti >= args.length) {
20543                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20544                            | DumpState.DUMP_SERVICE_RESOLVERS
20545                            | DumpState.DUMP_RECEIVER_RESOLVERS
20546                            | DumpState.DUMP_CONTENT_RESOLVERS);
20547                } else {
20548                    while (opti < args.length) {
20549                        String name = args[opti];
20550                        if ("a".equals(name) || "activity".equals(name)) {
20551                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20552                        } else if ("s".equals(name) || "service".equals(name)) {
20553                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20554                        } else if ("r".equals(name) || "receiver".equals(name)) {
20555                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20556                        } else if ("c".equals(name) || "content".equals(name)) {
20557                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20558                        } else {
20559                            pw.println("Error: unknown resolver table type: " + name);
20560                            return;
20561                        }
20562                        opti++;
20563                    }
20564                }
20565            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20566                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20567            } else if ("permission".equals(cmd)) {
20568                if (opti >= args.length) {
20569                    pw.println("Error: permission requires permission name");
20570                    return;
20571                }
20572                permissionNames = new ArraySet<>();
20573                while (opti < args.length) {
20574                    permissionNames.add(args[opti]);
20575                    opti++;
20576                }
20577                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20578                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20579            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20580                dumpState.setDump(DumpState.DUMP_PREFERRED);
20581            } else if ("preferred-xml".equals(cmd)) {
20582                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20583                if (opti < args.length && "--full".equals(args[opti])) {
20584                    fullPreferred = true;
20585                    opti++;
20586                }
20587            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20588                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20589            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20590                dumpState.setDump(DumpState.DUMP_PACKAGES);
20591            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20592                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20593            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20594                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20595            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20596                dumpState.setDump(DumpState.DUMP_MESSAGES);
20597            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20598                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20599            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20600                    || "intent-filter-verifiers".equals(cmd)) {
20601                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20602            } else if ("version".equals(cmd)) {
20603                dumpState.setDump(DumpState.DUMP_VERSION);
20604            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20605                dumpState.setDump(DumpState.DUMP_KEYSETS);
20606            } else if ("installs".equals(cmd)) {
20607                dumpState.setDump(DumpState.DUMP_INSTALLS);
20608            } else if ("frozen".equals(cmd)) {
20609                dumpState.setDump(DumpState.DUMP_FROZEN);
20610            } else if ("dexopt".equals(cmd)) {
20611                dumpState.setDump(DumpState.DUMP_DEXOPT);
20612            } else if ("compiler-stats".equals(cmd)) {
20613                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20614            } else if ("enabled-overlays".equals(cmd)) {
20615                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20616            } else if ("write".equals(cmd)) {
20617                synchronized (mPackages) {
20618                    mSettings.writeLPr();
20619                    pw.println("Settings written.");
20620                    return;
20621                }
20622            }
20623        }
20624
20625        if (checkin) {
20626            pw.println("vers,1");
20627        }
20628
20629        // reader
20630        synchronized (mPackages) {
20631            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20632                if (!checkin) {
20633                    if (dumpState.onTitlePrinted())
20634                        pw.println();
20635                    pw.println("Database versions:");
20636                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20637                }
20638            }
20639
20640            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20641                if (!checkin) {
20642                    if (dumpState.onTitlePrinted())
20643                        pw.println();
20644                    pw.println("Verifiers:");
20645                    pw.print("  Required: ");
20646                    pw.print(mRequiredVerifierPackage);
20647                    pw.print(" (uid=");
20648                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20649                            UserHandle.USER_SYSTEM));
20650                    pw.println(")");
20651                } else if (mRequiredVerifierPackage != null) {
20652                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20653                    pw.print(",");
20654                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20655                            UserHandle.USER_SYSTEM));
20656                }
20657            }
20658
20659            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20660                    packageName == null) {
20661                if (mIntentFilterVerifierComponent != null) {
20662                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20663                    if (!checkin) {
20664                        if (dumpState.onTitlePrinted())
20665                            pw.println();
20666                        pw.println("Intent Filter Verifier:");
20667                        pw.print("  Using: ");
20668                        pw.print(verifierPackageName);
20669                        pw.print(" (uid=");
20670                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20671                                UserHandle.USER_SYSTEM));
20672                        pw.println(")");
20673                    } else if (verifierPackageName != null) {
20674                        pw.print("ifv,"); pw.print(verifierPackageName);
20675                        pw.print(",");
20676                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20677                                UserHandle.USER_SYSTEM));
20678                    }
20679                } else {
20680                    pw.println();
20681                    pw.println("No Intent Filter Verifier available!");
20682                }
20683            }
20684
20685            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20686                boolean printedHeader = false;
20687                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20688                while (it.hasNext()) {
20689                    String libName = it.next();
20690                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20691                    if (versionedLib == null) {
20692                        continue;
20693                    }
20694                    final int versionCount = versionedLib.size();
20695                    for (int i = 0; i < versionCount; i++) {
20696                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20697                        if (!checkin) {
20698                            if (!printedHeader) {
20699                                if (dumpState.onTitlePrinted())
20700                                    pw.println();
20701                                pw.println("Libraries:");
20702                                printedHeader = true;
20703                            }
20704                            pw.print("  ");
20705                        } else {
20706                            pw.print("lib,");
20707                        }
20708                        pw.print(libEntry.info.getName());
20709                        if (libEntry.info.isStatic()) {
20710                            pw.print(" version=" + libEntry.info.getVersion());
20711                        }
20712                        if (!checkin) {
20713                            pw.print(" -> ");
20714                        }
20715                        if (libEntry.path != null) {
20716                            pw.print(" (jar) ");
20717                            pw.print(libEntry.path);
20718                        } else {
20719                            pw.print(" (apk) ");
20720                            pw.print(libEntry.apk);
20721                        }
20722                        pw.println();
20723                    }
20724                }
20725            }
20726
20727            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20728                if (dumpState.onTitlePrinted())
20729                    pw.println();
20730                if (!checkin) {
20731                    pw.println("Features:");
20732                }
20733
20734                synchronized (mAvailableFeatures) {
20735                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20736                        if (checkin) {
20737                            pw.print("feat,");
20738                            pw.print(feat.name);
20739                            pw.print(",");
20740                            pw.println(feat.version);
20741                        } else {
20742                            pw.print("  ");
20743                            pw.print(feat.name);
20744                            if (feat.version > 0) {
20745                                pw.print(" version=");
20746                                pw.print(feat.version);
20747                            }
20748                            pw.println();
20749                        }
20750                    }
20751                }
20752            }
20753
20754            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20755                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20756                        : "Activity Resolver Table:", "  ", packageName,
20757                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20758                    dumpState.setTitlePrinted(true);
20759                }
20760            }
20761            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20762                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20763                        : "Receiver Resolver Table:", "  ", packageName,
20764                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20765                    dumpState.setTitlePrinted(true);
20766                }
20767            }
20768            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20769                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20770                        : "Service Resolver Table:", "  ", packageName,
20771                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20772                    dumpState.setTitlePrinted(true);
20773                }
20774            }
20775            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20776                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20777                        : "Provider Resolver Table:", "  ", packageName,
20778                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20779                    dumpState.setTitlePrinted(true);
20780                }
20781            }
20782
20783            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20784                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20785                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20786                    int user = mSettings.mPreferredActivities.keyAt(i);
20787                    if (pir.dump(pw,
20788                            dumpState.getTitlePrinted()
20789                                ? "\nPreferred Activities User " + user + ":"
20790                                : "Preferred Activities User " + user + ":", "  ",
20791                            packageName, true, false)) {
20792                        dumpState.setTitlePrinted(true);
20793                    }
20794                }
20795            }
20796
20797            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20798                pw.flush();
20799                FileOutputStream fout = new FileOutputStream(fd);
20800                BufferedOutputStream str = new BufferedOutputStream(fout);
20801                XmlSerializer serializer = new FastXmlSerializer();
20802                try {
20803                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20804                    serializer.startDocument(null, true);
20805                    serializer.setFeature(
20806                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20807                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20808                    serializer.endDocument();
20809                    serializer.flush();
20810                } catch (IllegalArgumentException e) {
20811                    pw.println("Failed writing: " + e);
20812                } catch (IllegalStateException e) {
20813                    pw.println("Failed writing: " + e);
20814                } catch (IOException e) {
20815                    pw.println("Failed writing: " + e);
20816                }
20817            }
20818
20819            if (!checkin
20820                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20821                    && packageName == null) {
20822                pw.println();
20823                int count = mSettings.mPackages.size();
20824                if (count == 0) {
20825                    pw.println("No applications!");
20826                    pw.println();
20827                } else {
20828                    final String prefix = "  ";
20829                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20830                    if (allPackageSettings.size() == 0) {
20831                        pw.println("No domain preferred apps!");
20832                        pw.println();
20833                    } else {
20834                        pw.println("App verification status:");
20835                        pw.println();
20836                        count = 0;
20837                        for (PackageSetting ps : allPackageSettings) {
20838                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20839                            if (ivi == null || ivi.getPackageName() == null) continue;
20840                            pw.println(prefix + "Package: " + ivi.getPackageName());
20841                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20842                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20843                            pw.println();
20844                            count++;
20845                        }
20846                        if (count == 0) {
20847                            pw.println(prefix + "No app verification established.");
20848                            pw.println();
20849                        }
20850                        for (int userId : sUserManager.getUserIds()) {
20851                            pw.println("App linkages for user " + userId + ":");
20852                            pw.println();
20853                            count = 0;
20854                            for (PackageSetting ps : allPackageSettings) {
20855                                final long status = ps.getDomainVerificationStatusForUser(userId);
20856                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20857                                        && !DEBUG_DOMAIN_VERIFICATION) {
20858                                    continue;
20859                                }
20860                                pw.println(prefix + "Package: " + ps.name);
20861                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20862                                String statusStr = IntentFilterVerificationInfo.
20863                                        getStatusStringFromValue(status);
20864                                pw.println(prefix + "Status:  " + statusStr);
20865                                pw.println();
20866                                count++;
20867                            }
20868                            if (count == 0) {
20869                                pw.println(prefix + "No configured app linkages.");
20870                                pw.println();
20871                            }
20872                        }
20873                    }
20874                }
20875            }
20876
20877            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20878                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20879                if (packageName == null && permissionNames == null) {
20880                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20881                        if (iperm == 0) {
20882                            if (dumpState.onTitlePrinted())
20883                                pw.println();
20884                            pw.println("AppOp Permissions:");
20885                        }
20886                        pw.print("  AppOp Permission ");
20887                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20888                        pw.println(":");
20889                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20890                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20891                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20892                        }
20893                    }
20894                }
20895            }
20896
20897            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20898                boolean printedSomething = false;
20899                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20900                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20901                        continue;
20902                    }
20903                    if (!printedSomething) {
20904                        if (dumpState.onTitlePrinted())
20905                            pw.println();
20906                        pw.println("Registered ContentProviders:");
20907                        printedSomething = true;
20908                    }
20909                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20910                    pw.print("    "); pw.println(p.toString());
20911                }
20912                printedSomething = false;
20913                for (Map.Entry<String, PackageParser.Provider> entry :
20914                        mProvidersByAuthority.entrySet()) {
20915                    PackageParser.Provider p = entry.getValue();
20916                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20917                        continue;
20918                    }
20919                    if (!printedSomething) {
20920                        if (dumpState.onTitlePrinted())
20921                            pw.println();
20922                        pw.println("ContentProvider Authorities:");
20923                        printedSomething = true;
20924                    }
20925                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20926                    pw.print("    "); pw.println(p.toString());
20927                    if (p.info != null && p.info.applicationInfo != null) {
20928                        final String appInfo = p.info.applicationInfo.toString();
20929                        pw.print("      applicationInfo="); pw.println(appInfo);
20930                    }
20931                }
20932            }
20933
20934            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20935                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20936            }
20937
20938            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20939                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20940            }
20941
20942            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20943                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20944            }
20945
20946            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20947                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20948            }
20949
20950            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20951                // XXX should handle packageName != null by dumping only install data that
20952                // the given package is involved with.
20953                if (dumpState.onTitlePrinted()) pw.println();
20954
20955                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20956                ipw.println();
20957                ipw.println("Frozen packages:");
20958                ipw.increaseIndent();
20959                if (mFrozenPackages.size() == 0) {
20960                    ipw.println("(none)");
20961                } else {
20962                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20963                        ipw.println(mFrozenPackages.valueAt(i));
20964                    }
20965                }
20966                ipw.decreaseIndent();
20967            }
20968
20969            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20970                if (dumpState.onTitlePrinted()) pw.println();
20971                dumpDexoptStateLPr(pw, packageName);
20972            }
20973
20974            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20975                if (dumpState.onTitlePrinted()) pw.println();
20976                dumpCompilerStatsLPr(pw, packageName);
20977            }
20978
20979            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20980                if (dumpState.onTitlePrinted()) pw.println();
20981                dumpEnabledOverlaysLPr(pw);
20982            }
20983
20984            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20985                if (dumpState.onTitlePrinted()) pw.println();
20986                mSettings.dumpReadMessagesLPr(pw, dumpState);
20987
20988                pw.println();
20989                pw.println("Package warning messages:");
20990                BufferedReader in = null;
20991                String line = null;
20992                try {
20993                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20994                    while ((line = in.readLine()) != null) {
20995                        if (line.contains("ignored: updated version")) continue;
20996                        pw.println(line);
20997                    }
20998                } catch (IOException ignored) {
20999                } finally {
21000                    IoUtils.closeQuietly(in);
21001                }
21002            }
21003
21004            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21005                BufferedReader in = null;
21006                String line = null;
21007                try {
21008                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21009                    while ((line = in.readLine()) != null) {
21010                        if (line.contains("ignored: updated version")) continue;
21011                        pw.print("msg,");
21012                        pw.println(line);
21013                    }
21014                } catch (IOException ignored) {
21015                } finally {
21016                    IoUtils.closeQuietly(in);
21017                }
21018            }
21019        }
21020
21021        // PackageInstaller should be called outside of mPackages lock
21022        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21023            // XXX should handle packageName != null by dumping only install data that
21024            // the given package is involved with.
21025            if (dumpState.onTitlePrinted()) pw.println();
21026            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21027        }
21028    }
21029
21030    private void dumpProto(FileDescriptor fd) {
21031        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21032
21033        synchronized (mPackages) {
21034            final long requiredVerifierPackageToken =
21035                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21036            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21037            proto.write(
21038                    PackageServiceDumpProto.PackageShortProto.UID,
21039                    getPackageUid(
21040                            mRequiredVerifierPackage,
21041                            MATCH_DEBUG_TRIAGED_MISSING,
21042                            UserHandle.USER_SYSTEM));
21043            proto.end(requiredVerifierPackageToken);
21044
21045            if (mIntentFilterVerifierComponent != null) {
21046                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21047                final long verifierPackageToken =
21048                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21049                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21050                proto.write(
21051                        PackageServiceDumpProto.PackageShortProto.UID,
21052                        getPackageUid(
21053                                verifierPackageName,
21054                                MATCH_DEBUG_TRIAGED_MISSING,
21055                                UserHandle.USER_SYSTEM));
21056                proto.end(verifierPackageToken);
21057            }
21058
21059            dumpSharedLibrariesProto(proto);
21060            dumpFeaturesProto(proto);
21061            mSettings.dumpPackagesProto(proto);
21062            mSettings.dumpSharedUsersProto(proto);
21063            dumpMessagesProto(proto);
21064        }
21065        proto.flush();
21066    }
21067
21068    private void dumpMessagesProto(ProtoOutputStream proto) {
21069        BufferedReader in = null;
21070        String line = null;
21071        try {
21072            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21073            while ((line = in.readLine()) != null) {
21074                if (line.contains("ignored: updated version")) continue;
21075                proto.write(PackageServiceDumpProto.MESSAGES, line);
21076            }
21077        } catch (IOException ignored) {
21078        } finally {
21079            IoUtils.closeQuietly(in);
21080        }
21081    }
21082
21083    private void dumpFeaturesProto(ProtoOutputStream proto) {
21084        synchronized (mAvailableFeatures) {
21085            final int count = mAvailableFeatures.size();
21086            for (int i = 0; i < count; i++) {
21087                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21088                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21089                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21090                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21091                proto.end(featureToken);
21092            }
21093        }
21094    }
21095
21096    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21097        final int count = mSharedLibraries.size();
21098        for (int i = 0; i < count; i++) {
21099            final String libName = mSharedLibraries.keyAt(i);
21100            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21101            if (versionedLib == null) {
21102                continue;
21103            }
21104            final int versionCount = versionedLib.size();
21105            for (int j = 0; j < versionCount; j++) {
21106                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21107                final long sharedLibraryToken =
21108                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21109                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21110                final boolean isJar = (libEntry.path != null);
21111                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21112                if (isJar) {
21113                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21114                } else {
21115                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21116                }
21117                proto.end(sharedLibraryToken);
21118            }
21119        }
21120    }
21121
21122    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21123        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21124        ipw.println();
21125        ipw.println("Dexopt state:");
21126        ipw.increaseIndent();
21127        Collection<PackageParser.Package> packages = null;
21128        if (packageName != null) {
21129            PackageParser.Package targetPackage = mPackages.get(packageName);
21130            if (targetPackage != null) {
21131                packages = Collections.singletonList(targetPackage);
21132            } else {
21133                ipw.println("Unable to find package: " + packageName);
21134                return;
21135            }
21136        } else {
21137            packages = mPackages.values();
21138        }
21139
21140        for (PackageParser.Package pkg : packages) {
21141            ipw.println("[" + pkg.packageName + "]");
21142            ipw.increaseIndent();
21143            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21144            ipw.decreaseIndent();
21145        }
21146    }
21147
21148    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21149        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21150        ipw.println();
21151        ipw.println("Compiler stats:");
21152        ipw.increaseIndent();
21153        Collection<PackageParser.Package> packages = null;
21154        if (packageName != null) {
21155            PackageParser.Package targetPackage = mPackages.get(packageName);
21156            if (targetPackage != null) {
21157                packages = Collections.singletonList(targetPackage);
21158            } else {
21159                ipw.println("Unable to find package: " + packageName);
21160                return;
21161            }
21162        } else {
21163            packages = mPackages.values();
21164        }
21165
21166        for (PackageParser.Package pkg : packages) {
21167            ipw.println("[" + pkg.packageName + "]");
21168            ipw.increaseIndent();
21169
21170            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21171            if (stats == null) {
21172                ipw.println("(No recorded stats)");
21173            } else {
21174                stats.dump(ipw);
21175            }
21176            ipw.decreaseIndent();
21177        }
21178    }
21179
21180    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21181        pw.println("Enabled overlay paths:");
21182        final int N = mEnabledOverlayPaths.size();
21183        for (int i = 0; i < N; i++) {
21184            final int userId = mEnabledOverlayPaths.keyAt(i);
21185            pw.println(String.format("    User %d:", userId));
21186            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21187                mEnabledOverlayPaths.valueAt(i);
21188            final int M = userSpecificOverlays.size();
21189            for (int j = 0; j < M; j++) {
21190                final String targetPackageName = userSpecificOverlays.keyAt(j);
21191                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21192                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21193            }
21194        }
21195    }
21196
21197    private String dumpDomainString(String packageName) {
21198        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21199                .getList();
21200        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21201
21202        ArraySet<String> result = new ArraySet<>();
21203        if (iviList.size() > 0) {
21204            for (IntentFilterVerificationInfo ivi : iviList) {
21205                for (String host : ivi.getDomains()) {
21206                    result.add(host);
21207                }
21208            }
21209        }
21210        if (filters != null && filters.size() > 0) {
21211            for (IntentFilter filter : filters) {
21212                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21213                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21214                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21215                    result.addAll(filter.getHostsList());
21216                }
21217            }
21218        }
21219
21220        StringBuilder sb = new StringBuilder(result.size() * 16);
21221        for (String domain : result) {
21222            if (sb.length() > 0) sb.append(" ");
21223            sb.append(domain);
21224        }
21225        return sb.toString();
21226    }
21227
21228    // ------- apps on sdcard specific code -------
21229    static final boolean DEBUG_SD_INSTALL = false;
21230
21231    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21232
21233    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21234
21235    private boolean mMediaMounted = false;
21236
21237    static String getEncryptKey() {
21238        try {
21239            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21240                    SD_ENCRYPTION_KEYSTORE_NAME);
21241            if (sdEncKey == null) {
21242                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21243                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21244                if (sdEncKey == null) {
21245                    Slog.e(TAG, "Failed to create encryption keys");
21246                    return null;
21247                }
21248            }
21249            return sdEncKey;
21250        } catch (NoSuchAlgorithmException nsae) {
21251            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21252            return null;
21253        } catch (IOException ioe) {
21254            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21255            return null;
21256        }
21257    }
21258
21259    /*
21260     * Update media status on PackageManager.
21261     */
21262    @Override
21263    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21264        int callingUid = Binder.getCallingUid();
21265        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21266            throw new SecurityException("Media status can only be updated by the system");
21267        }
21268        // reader; this apparently protects mMediaMounted, but should probably
21269        // be a different lock in that case.
21270        synchronized (mPackages) {
21271            Log.i(TAG, "Updating external media status from "
21272                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21273                    + (mediaStatus ? "mounted" : "unmounted"));
21274            if (DEBUG_SD_INSTALL)
21275                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21276                        + ", mMediaMounted=" + mMediaMounted);
21277            if (mediaStatus == mMediaMounted) {
21278                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21279                        : 0, -1);
21280                mHandler.sendMessage(msg);
21281                return;
21282            }
21283            mMediaMounted = mediaStatus;
21284        }
21285        // Queue up an async operation since the package installation may take a
21286        // little while.
21287        mHandler.post(new Runnable() {
21288            public void run() {
21289                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21290            }
21291        });
21292    }
21293
21294    /**
21295     * Called by StorageManagerService when the initial ASECs to scan are available.
21296     * Should block until all the ASEC containers are finished being scanned.
21297     */
21298    public void scanAvailableAsecs() {
21299        updateExternalMediaStatusInner(true, false, false);
21300    }
21301
21302    /*
21303     * Collect information of applications on external media, map them against
21304     * existing containers and update information based on current mount status.
21305     * Please note that we always have to report status if reportStatus has been
21306     * set to true especially when unloading packages.
21307     */
21308    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21309            boolean externalStorage) {
21310        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21311        int[] uidArr = EmptyArray.INT;
21312
21313        final String[] list = PackageHelper.getSecureContainerList();
21314        if (ArrayUtils.isEmpty(list)) {
21315            Log.i(TAG, "No secure containers found");
21316        } else {
21317            // Process list of secure containers and categorize them
21318            // as active or stale based on their package internal state.
21319
21320            // reader
21321            synchronized (mPackages) {
21322                for (String cid : list) {
21323                    // Leave stages untouched for now; installer service owns them
21324                    if (PackageInstallerService.isStageName(cid)) continue;
21325
21326                    if (DEBUG_SD_INSTALL)
21327                        Log.i(TAG, "Processing container " + cid);
21328                    String pkgName = getAsecPackageName(cid);
21329                    if (pkgName == null) {
21330                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21331                        continue;
21332                    }
21333                    if (DEBUG_SD_INSTALL)
21334                        Log.i(TAG, "Looking for pkg : " + pkgName);
21335
21336                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21337                    if (ps == null) {
21338                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21339                        continue;
21340                    }
21341
21342                    /*
21343                     * Skip packages that are not external if we're unmounting
21344                     * external storage.
21345                     */
21346                    if (externalStorage && !isMounted && !isExternal(ps)) {
21347                        continue;
21348                    }
21349
21350                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21351                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21352                    // The package status is changed only if the code path
21353                    // matches between settings and the container id.
21354                    if (ps.codePathString != null
21355                            && ps.codePathString.startsWith(args.getCodePath())) {
21356                        if (DEBUG_SD_INSTALL) {
21357                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21358                                    + " at code path: " + ps.codePathString);
21359                        }
21360
21361                        // We do have a valid package installed on sdcard
21362                        processCids.put(args, ps.codePathString);
21363                        final int uid = ps.appId;
21364                        if (uid != -1) {
21365                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21366                        }
21367                    } else {
21368                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21369                                + ps.codePathString);
21370                    }
21371                }
21372            }
21373
21374            Arrays.sort(uidArr);
21375        }
21376
21377        // Process packages with valid entries.
21378        if (isMounted) {
21379            if (DEBUG_SD_INSTALL)
21380                Log.i(TAG, "Loading packages");
21381            loadMediaPackages(processCids, uidArr, externalStorage);
21382            startCleaningPackages();
21383            mInstallerService.onSecureContainersAvailable();
21384        } else {
21385            if (DEBUG_SD_INSTALL)
21386                Log.i(TAG, "Unloading packages");
21387            unloadMediaPackages(processCids, uidArr, reportStatus);
21388        }
21389    }
21390
21391    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21392            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21393        final int size = infos.size();
21394        final String[] packageNames = new String[size];
21395        final int[] packageUids = new int[size];
21396        for (int i = 0; i < size; i++) {
21397            final ApplicationInfo info = infos.get(i);
21398            packageNames[i] = info.packageName;
21399            packageUids[i] = info.uid;
21400        }
21401        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21402                finishedReceiver);
21403    }
21404
21405    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21406            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21407        sendResourcesChangedBroadcast(mediaStatus, replacing,
21408                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21409    }
21410
21411    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21412            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21413        int size = pkgList.length;
21414        if (size > 0) {
21415            // Send broadcasts here
21416            Bundle extras = new Bundle();
21417            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21418            if (uidArr != null) {
21419                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21420            }
21421            if (replacing) {
21422                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21423            }
21424            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21425                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21426            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21427        }
21428    }
21429
21430   /*
21431     * Look at potentially valid container ids from processCids If package
21432     * information doesn't match the one on record or package scanning fails,
21433     * the cid is added to list of removeCids. We currently don't delete stale
21434     * containers.
21435     */
21436    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21437            boolean externalStorage) {
21438        ArrayList<String> pkgList = new ArrayList<String>();
21439        Set<AsecInstallArgs> keys = processCids.keySet();
21440
21441        for (AsecInstallArgs args : keys) {
21442            String codePath = processCids.get(args);
21443            if (DEBUG_SD_INSTALL)
21444                Log.i(TAG, "Loading container : " + args.cid);
21445            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21446            try {
21447                // Make sure there are no container errors first.
21448                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21449                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21450                            + " when installing from sdcard");
21451                    continue;
21452                }
21453                // Check code path here.
21454                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21455                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21456                            + " does not match one in settings " + codePath);
21457                    continue;
21458                }
21459                // Parse package
21460                int parseFlags = mDefParseFlags;
21461                if (args.isExternalAsec()) {
21462                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21463                }
21464                if (args.isFwdLocked()) {
21465                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21466                }
21467
21468                synchronized (mInstallLock) {
21469                    PackageParser.Package pkg = null;
21470                    try {
21471                        // Sadly we don't know the package name yet to freeze it
21472                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21473                                SCAN_IGNORE_FROZEN, 0, null);
21474                    } catch (PackageManagerException e) {
21475                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21476                    }
21477                    // Scan the package
21478                    if (pkg != null) {
21479                        /*
21480                         * TODO why is the lock being held? doPostInstall is
21481                         * called in other places without the lock. This needs
21482                         * to be straightened out.
21483                         */
21484                        // writer
21485                        synchronized (mPackages) {
21486                            retCode = PackageManager.INSTALL_SUCCEEDED;
21487                            pkgList.add(pkg.packageName);
21488                            // Post process args
21489                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21490                                    pkg.applicationInfo.uid);
21491                        }
21492                    } else {
21493                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21494                    }
21495                }
21496
21497            } finally {
21498                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21499                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21500                }
21501            }
21502        }
21503        // writer
21504        synchronized (mPackages) {
21505            // If the platform SDK has changed since the last time we booted,
21506            // we need to re-grant app permission to catch any new ones that
21507            // appear. This is really a hack, and means that apps can in some
21508            // cases get permissions that the user didn't initially explicitly
21509            // allow... it would be nice to have some better way to handle
21510            // this situation.
21511            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21512                    : mSettings.getInternalVersion();
21513            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21514                    : StorageManager.UUID_PRIVATE_INTERNAL;
21515
21516            int updateFlags = UPDATE_PERMISSIONS_ALL;
21517            if (ver.sdkVersion != mSdkVersion) {
21518                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21519                        + mSdkVersion + "; regranting permissions for external");
21520                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21521            }
21522            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21523
21524            // Yay, everything is now upgraded
21525            ver.forceCurrent();
21526
21527            // can downgrade to reader
21528            // Persist settings
21529            mSettings.writeLPr();
21530        }
21531        // Send a broadcast to let everyone know we are done processing
21532        if (pkgList.size() > 0) {
21533            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21534        }
21535    }
21536
21537   /*
21538     * Utility method to unload a list of specified containers
21539     */
21540    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21541        // Just unmount all valid containers.
21542        for (AsecInstallArgs arg : cidArgs) {
21543            synchronized (mInstallLock) {
21544                arg.doPostDeleteLI(false);
21545           }
21546       }
21547   }
21548
21549    /*
21550     * Unload packages mounted on external media. This involves deleting package
21551     * data from internal structures, sending broadcasts about disabled packages,
21552     * gc'ing to free up references, unmounting all secure containers
21553     * corresponding to packages on external media, and posting a
21554     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21555     * that we always have to post this message if status has been requested no
21556     * matter what.
21557     */
21558    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21559            final boolean reportStatus) {
21560        if (DEBUG_SD_INSTALL)
21561            Log.i(TAG, "unloading media packages");
21562        ArrayList<String> pkgList = new ArrayList<String>();
21563        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21564        final Set<AsecInstallArgs> keys = processCids.keySet();
21565        for (AsecInstallArgs args : keys) {
21566            String pkgName = args.getPackageName();
21567            if (DEBUG_SD_INSTALL)
21568                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21569            // Delete package internally
21570            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21571            synchronized (mInstallLock) {
21572                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21573                final boolean res;
21574                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21575                        "unloadMediaPackages")) {
21576                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21577                            null);
21578                }
21579                if (res) {
21580                    pkgList.add(pkgName);
21581                } else {
21582                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21583                    failedList.add(args);
21584                }
21585            }
21586        }
21587
21588        // reader
21589        synchronized (mPackages) {
21590            // We didn't update the settings after removing each package;
21591            // write them now for all packages.
21592            mSettings.writeLPr();
21593        }
21594
21595        // We have to absolutely send UPDATED_MEDIA_STATUS only
21596        // after confirming that all the receivers processed the ordered
21597        // broadcast when packages get disabled, force a gc to clean things up.
21598        // and unload all the containers.
21599        if (pkgList.size() > 0) {
21600            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21601                    new IIntentReceiver.Stub() {
21602                public void performReceive(Intent intent, int resultCode, String data,
21603                        Bundle extras, boolean ordered, boolean sticky,
21604                        int sendingUser) throws RemoteException {
21605                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21606                            reportStatus ? 1 : 0, 1, keys);
21607                    mHandler.sendMessage(msg);
21608                }
21609            });
21610        } else {
21611            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21612                    keys);
21613            mHandler.sendMessage(msg);
21614        }
21615    }
21616
21617    private void loadPrivatePackages(final VolumeInfo vol) {
21618        mHandler.post(new Runnable() {
21619            @Override
21620            public void run() {
21621                loadPrivatePackagesInner(vol);
21622            }
21623        });
21624    }
21625
21626    private void loadPrivatePackagesInner(VolumeInfo vol) {
21627        final String volumeUuid = vol.fsUuid;
21628        if (TextUtils.isEmpty(volumeUuid)) {
21629            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21630            return;
21631        }
21632
21633        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21634        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21635        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21636
21637        final VersionInfo ver;
21638        final List<PackageSetting> packages;
21639        synchronized (mPackages) {
21640            ver = mSettings.findOrCreateVersion(volumeUuid);
21641            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21642        }
21643
21644        for (PackageSetting ps : packages) {
21645            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21646            synchronized (mInstallLock) {
21647                final PackageParser.Package pkg;
21648                try {
21649                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21650                    loaded.add(pkg.applicationInfo);
21651
21652                } catch (PackageManagerException e) {
21653                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21654                }
21655
21656                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21657                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21658                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21659                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21660                }
21661            }
21662        }
21663
21664        // Reconcile app data for all started/unlocked users
21665        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21666        final UserManager um = mContext.getSystemService(UserManager.class);
21667        UserManagerInternal umInternal = getUserManagerInternal();
21668        for (UserInfo user : um.getUsers()) {
21669            final int flags;
21670            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21671                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21672            } else if (umInternal.isUserRunning(user.id)) {
21673                flags = StorageManager.FLAG_STORAGE_DE;
21674            } else {
21675                continue;
21676            }
21677
21678            try {
21679                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21680                synchronized (mInstallLock) {
21681                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21682                }
21683            } catch (IllegalStateException e) {
21684                // Device was probably ejected, and we'll process that event momentarily
21685                Slog.w(TAG, "Failed to prepare storage: " + e);
21686            }
21687        }
21688
21689        synchronized (mPackages) {
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 " + volumeUuid);
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            mSettings.writeLPr();
21702        }
21703
21704        for (PackageFreezer freezer : freezers) {
21705            freezer.close();
21706        }
21707
21708        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21709        sendResourcesChangedBroadcast(true, false, loaded, null);
21710    }
21711
21712    private void unloadPrivatePackages(final VolumeInfo vol) {
21713        mHandler.post(new Runnable() {
21714            @Override
21715            public void run() {
21716                unloadPrivatePackagesInner(vol);
21717            }
21718        });
21719    }
21720
21721    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21722        final String volumeUuid = vol.fsUuid;
21723        if (TextUtils.isEmpty(volumeUuid)) {
21724            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21725            return;
21726        }
21727
21728        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21729        synchronized (mInstallLock) {
21730        synchronized (mPackages) {
21731            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21732            for (PackageSetting ps : packages) {
21733                if (ps.pkg == null) continue;
21734
21735                final ApplicationInfo info = ps.pkg.applicationInfo;
21736                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21737                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21738
21739                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21740                        "unloadPrivatePackagesInner")) {
21741                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21742                            false, null)) {
21743                        unloaded.add(info);
21744                    } else {
21745                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21746                    }
21747                }
21748
21749                // Try very hard to release any references to this package
21750                // so we don't risk the system server being killed due to
21751                // open FDs
21752                AttributeCache.instance().removePackage(ps.name);
21753            }
21754
21755            mSettings.writeLPr();
21756        }
21757        }
21758
21759        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21760        sendResourcesChangedBroadcast(false, false, unloaded, null);
21761
21762        // Try very hard to release any references to this path so we don't risk
21763        // the system server being killed due to open FDs
21764        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21765
21766        for (int i = 0; i < 3; i++) {
21767            System.gc();
21768            System.runFinalization();
21769        }
21770    }
21771
21772    private void assertPackageKnown(String volumeUuid, String packageName)
21773            throws PackageManagerException {
21774        synchronized (mPackages) {
21775            // Normalize package name to handle renamed packages
21776            packageName = normalizePackageNameLPr(packageName);
21777
21778            final PackageSetting ps = mSettings.mPackages.get(packageName);
21779            if (ps == null) {
21780                throw new PackageManagerException("Package " + packageName + " is unknown");
21781            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21782                throw new PackageManagerException(
21783                        "Package " + packageName + " found on unknown volume " + volumeUuid
21784                                + "; expected volume " + ps.volumeUuid);
21785            }
21786        }
21787    }
21788
21789    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21790            throws PackageManagerException {
21791        synchronized (mPackages) {
21792            // Normalize package name to handle renamed packages
21793            packageName = normalizePackageNameLPr(packageName);
21794
21795            final PackageSetting ps = mSettings.mPackages.get(packageName);
21796            if (ps == null) {
21797                throw new PackageManagerException("Package " + packageName + " is unknown");
21798            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21799                throw new PackageManagerException(
21800                        "Package " + packageName + " found on unknown volume " + volumeUuid
21801                                + "; expected volume " + ps.volumeUuid);
21802            } else if (!ps.getInstalled(userId)) {
21803                throw new PackageManagerException(
21804                        "Package " + packageName + " not installed for user " + userId);
21805            }
21806        }
21807    }
21808
21809    private List<String> collectAbsoluteCodePaths() {
21810        synchronized (mPackages) {
21811            List<String> codePaths = new ArrayList<>();
21812            final int packageCount = mSettings.mPackages.size();
21813            for (int i = 0; i < packageCount; i++) {
21814                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21815                codePaths.add(ps.codePath.getAbsolutePath());
21816            }
21817            return codePaths;
21818        }
21819    }
21820
21821    /**
21822     * Examine all apps present on given mounted volume, and destroy apps that
21823     * aren't expected, either due to uninstallation or reinstallation on
21824     * another volume.
21825     */
21826    private void reconcileApps(String volumeUuid) {
21827        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21828        List<File> filesToDelete = null;
21829
21830        final File[] files = FileUtils.listFilesOrEmpty(
21831                Environment.getDataAppDirectory(volumeUuid));
21832        for (File file : files) {
21833            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21834                    && !PackageInstallerService.isStageName(file.getName());
21835            if (!isPackage) {
21836                // Ignore entries which are not packages
21837                continue;
21838            }
21839
21840            String absolutePath = file.getAbsolutePath();
21841
21842            boolean pathValid = false;
21843            final int absoluteCodePathCount = absoluteCodePaths.size();
21844            for (int i = 0; i < absoluteCodePathCount; i++) {
21845                String absoluteCodePath = absoluteCodePaths.get(i);
21846                if (absolutePath.startsWith(absoluteCodePath)) {
21847                    pathValid = true;
21848                    break;
21849                }
21850            }
21851
21852            if (!pathValid) {
21853                if (filesToDelete == null) {
21854                    filesToDelete = new ArrayList<>();
21855                }
21856                filesToDelete.add(file);
21857            }
21858        }
21859
21860        if (filesToDelete != null) {
21861            final int fileToDeleteCount = filesToDelete.size();
21862            for (int i = 0; i < fileToDeleteCount; i++) {
21863                File fileToDelete = filesToDelete.get(i);
21864                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21865                synchronized (mInstallLock) {
21866                    removeCodePathLI(fileToDelete);
21867                }
21868            }
21869        }
21870    }
21871
21872    /**
21873     * Reconcile all app data for the given user.
21874     * <p>
21875     * Verifies that directories exist and that ownership and labeling is
21876     * correct for all installed apps on all mounted volumes.
21877     */
21878    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21879        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21880        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21881            final String volumeUuid = vol.getFsUuid();
21882            synchronized (mInstallLock) {
21883                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21884            }
21885        }
21886    }
21887
21888    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21889            boolean migrateAppData) {
21890        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21891    }
21892
21893    /**
21894     * Reconcile all app data on given mounted volume.
21895     * <p>
21896     * Destroys app data that isn't expected, either due to uninstallation or
21897     * reinstallation on another volume.
21898     * <p>
21899     * Verifies that directories exist and that ownership and labeling is
21900     * correct for all installed apps.
21901     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21902     */
21903    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21904            boolean migrateAppData, boolean onlyCoreApps) {
21905        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21906                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21907        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21908
21909        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21910        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21911
21912        // First look for stale data that doesn't belong, and check if things
21913        // have changed since we did our last restorecon
21914        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21915            if (StorageManager.isFileEncryptedNativeOrEmulated()
21916                    && !StorageManager.isUserKeyUnlocked(userId)) {
21917                throw new RuntimeException(
21918                        "Yikes, someone asked us to reconcile CE storage while " + userId
21919                                + " was still locked; this would have caused massive data loss!");
21920            }
21921
21922            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21923            for (File file : files) {
21924                final String packageName = file.getName();
21925                try {
21926                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21927                } catch (PackageManagerException e) {
21928                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21929                    try {
21930                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21931                                StorageManager.FLAG_STORAGE_CE, 0);
21932                    } catch (InstallerException e2) {
21933                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21934                    }
21935                }
21936            }
21937        }
21938        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21939            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21940            for (File file : files) {
21941                final String packageName = file.getName();
21942                try {
21943                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21944                } catch (PackageManagerException e) {
21945                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21946                    try {
21947                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21948                                StorageManager.FLAG_STORAGE_DE, 0);
21949                    } catch (InstallerException e2) {
21950                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21951                    }
21952                }
21953            }
21954        }
21955
21956        // Ensure that data directories are ready to roll for all packages
21957        // installed for this volume and user
21958        final List<PackageSetting> packages;
21959        synchronized (mPackages) {
21960            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21961        }
21962        int preparedCount = 0;
21963        for (PackageSetting ps : packages) {
21964            final String packageName = ps.name;
21965            if (ps.pkg == null) {
21966                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21967                // TODO: might be due to legacy ASEC apps; we should circle back
21968                // and reconcile again once they're scanned
21969                continue;
21970            }
21971            // Skip non-core apps if requested
21972            if (onlyCoreApps && !ps.pkg.coreApp) {
21973                result.add(packageName);
21974                continue;
21975            }
21976
21977            if (ps.getInstalled(userId)) {
21978                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21979                preparedCount++;
21980            }
21981        }
21982
21983        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21984        return result;
21985    }
21986
21987    /**
21988     * Prepare app data for the given app just after it was installed or
21989     * upgraded. This method carefully only touches users that it's installed
21990     * for, and it forces a restorecon to handle any seinfo changes.
21991     * <p>
21992     * Verifies that directories exist and that ownership and labeling is
21993     * correct for all installed apps. If there is an ownership mismatch, it
21994     * will try recovering system apps by wiping data; third-party app data is
21995     * left intact.
21996     * <p>
21997     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21998     */
21999    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22000        final PackageSetting ps;
22001        synchronized (mPackages) {
22002            ps = mSettings.mPackages.get(pkg.packageName);
22003            mSettings.writeKernelMappingLPr(ps);
22004        }
22005
22006        final UserManager um = mContext.getSystemService(UserManager.class);
22007        UserManagerInternal umInternal = getUserManagerInternal();
22008        for (UserInfo user : um.getUsers()) {
22009            final int flags;
22010            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22011                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22012            } else if (umInternal.isUserRunning(user.id)) {
22013                flags = StorageManager.FLAG_STORAGE_DE;
22014            } else {
22015                continue;
22016            }
22017
22018            if (ps.getInstalled(user.id)) {
22019                // TODO: when user data is locked, mark that we're still dirty
22020                prepareAppDataLIF(pkg, user.id, flags);
22021            }
22022        }
22023    }
22024
22025    /**
22026     * Prepare app data for the given app.
22027     * <p>
22028     * Verifies that directories exist and that ownership and labeling is
22029     * correct for all installed apps. If there is an ownership mismatch, this
22030     * will try recovering system apps by wiping data; third-party app data is
22031     * left intact.
22032     */
22033    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22034        if (pkg == null) {
22035            Slog.wtf(TAG, "Package was null!", new Throwable());
22036            return;
22037        }
22038        prepareAppDataLeafLIF(pkg, userId, flags);
22039        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22040        for (int i = 0; i < childCount; i++) {
22041            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22042        }
22043    }
22044
22045    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22046            boolean maybeMigrateAppData) {
22047        prepareAppDataLIF(pkg, userId, flags);
22048
22049        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22050            // We may have just shuffled around app data directories, so
22051            // prepare them one more time
22052            prepareAppDataLIF(pkg, userId, flags);
22053        }
22054    }
22055
22056    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22057        if (DEBUG_APP_DATA) {
22058            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22059                    + Integer.toHexString(flags));
22060        }
22061
22062        final String volumeUuid = pkg.volumeUuid;
22063        final String packageName = pkg.packageName;
22064        final ApplicationInfo app = pkg.applicationInfo;
22065        final int appId = UserHandle.getAppId(app.uid);
22066
22067        Preconditions.checkNotNull(app.seInfo);
22068
22069        long ceDataInode = -1;
22070        try {
22071            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22072                    appId, app.seInfo, app.targetSdkVersion);
22073        } catch (InstallerException e) {
22074            if (app.isSystemApp()) {
22075                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22076                        + ", but trying to recover: " + e);
22077                destroyAppDataLeafLIF(pkg, userId, flags);
22078                try {
22079                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22080                            appId, app.seInfo, app.targetSdkVersion);
22081                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22082                } catch (InstallerException e2) {
22083                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22084                }
22085            } else {
22086                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22087            }
22088        }
22089
22090        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22091            // TODO: mark this structure as dirty so we persist it!
22092            synchronized (mPackages) {
22093                final PackageSetting ps = mSettings.mPackages.get(packageName);
22094                if (ps != null) {
22095                    ps.setCeDataInode(ceDataInode, userId);
22096                }
22097            }
22098        }
22099
22100        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22101    }
22102
22103    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22104        if (pkg == null) {
22105            Slog.wtf(TAG, "Package was null!", new Throwable());
22106            return;
22107        }
22108        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22109        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22110        for (int i = 0; i < childCount; i++) {
22111            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22112        }
22113    }
22114
22115    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22116        final String volumeUuid = pkg.volumeUuid;
22117        final String packageName = pkg.packageName;
22118        final ApplicationInfo app = pkg.applicationInfo;
22119
22120        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22121            // Create a native library symlink only if we have native libraries
22122            // and if the native libraries are 32 bit libraries. We do not provide
22123            // this symlink for 64 bit libraries.
22124            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22125                final String nativeLibPath = app.nativeLibraryDir;
22126                try {
22127                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22128                            nativeLibPath, userId);
22129                } catch (InstallerException e) {
22130                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22131                }
22132            }
22133        }
22134    }
22135
22136    /**
22137     * For system apps on non-FBE devices, this method migrates any existing
22138     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22139     * requested by the app.
22140     */
22141    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22142        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22143                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22144            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22145                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22146            try {
22147                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22148                        storageTarget);
22149            } catch (InstallerException e) {
22150                logCriticalInfo(Log.WARN,
22151                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22152            }
22153            return true;
22154        } else {
22155            return false;
22156        }
22157    }
22158
22159    public PackageFreezer freezePackage(String packageName, String killReason) {
22160        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22161    }
22162
22163    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22164        return new PackageFreezer(packageName, userId, killReason);
22165    }
22166
22167    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22168            String killReason) {
22169        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22170    }
22171
22172    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22173            String killReason) {
22174        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22175            return new PackageFreezer();
22176        } else {
22177            return freezePackage(packageName, userId, killReason);
22178        }
22179    }
22180
22181    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22182            String killReason) {
22183        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22184    }
22185
22186    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22187            String killReason) {
22188        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22189            return new PackageFreezer();
22190        } else {
22191            return freezePackage(packageName, userId, killReason);
22192        }
22193    }
22194
22195    /**
22196     * Class that freezes and kills the given package upon creation, and
22197     * unfreezes it upon closing. This is typically used when doing surgery on
22198     * app code/data to prevent the app from running while you're working.
22199     */
22200    private class PackageFreezer implements AutoCloseable {
22201        private final String mPackageName;
22202        private final PackageFreezer[] mChildren;
22203
22204        private final boolean mWeFroze;
22205
22206        private final AtomicBoolean mClosed = new AtomicBoolean();
22207        private final CloseGuard mCloseGuard = CloseGuard.get();
22208
22209        /**
22210         * Create and return a stub freezer that doesn't actually do anything,
22211         * typically used when someone requested
22212         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22213         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22214         */
22215        public PackageFreezer() {
22216            mPackageName = null;
22217            mChildren = null;
22218            mWeFroze = false;
22219            mCloseGuard.open("close");
22220        }
22221
22222        public PackageFreezer(String packageName, int userId, String killReason) {
22223            synchronized (mPackages) {
22224                mPackageName = packageName;
22225                mWeFroze = mFrozenPackages.add(mPackageName);
22226
22227                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22228                if (ps != null) {
22229                    killApplication(ps.name, ps.appId, userId, killReason);
22230                }
22231
22232                final PackageParser.Package p = mPackages.get(packageName);
22233                if (p != null && p.childPackages != null) {
22234                    final int N = p.childPackages.size();
22235                    mChildren = new PackageFreezer[N];
22236                    for (int i = 0; i < N; i++) {
22237                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22238                                userId, killReason);
22239                    }
22240                } else {
22241                    mChildren = null;
22242                }
22243            }
22244            mCloseGuard.open("close");
22245        }
22246
22247        @Override
22248        protected void finalize() throws Throwable {
22249            try {
22250                mCloseGuard.warnIfOpen();
22251                close();
22252            } finally {
22253                super.finalize();
22254            }
22255        }
22256
22257        @Override
22258        public void close() {
22259            mCloseGuard.close();
22260            if (mClosed.compareAndSet(false, true)) {
22261                synchronized (mPackages) {
22262                    if (mWeFroze) {
22263                        mFrozenPackages.remove(mPackageName);
22264                    }
22265
22266                    if (mChildren != null) {
22267                        for (PackageFreezer freezer : mChildren) {
22268                            freezer.close();
22269                        }
22270                    }
22271                }
22272            }
22273        }
22274    }
22275
22276    /**
22277     * Verify that given package is currently frozen.
22278     */
22279    private void checkPackageFrozen(String packageName) {
22280        synchronized (mPackages) {
22281            if (!mFrozenPackages.contains(packageName)) {
22282                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22283            }
22284        }
22285    }
22286
22287    @Override
22288    public int movePackage(final String packageName, final String volumeUuid) {
22289        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22290
22291        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22292        final int moveId = mNextMoveId.getAndIncrement();
22293        mHandler.post(new Runnable() {
22294            @Override
22295            public void run() {
22296                try {
22297                    movePackageInternal(packageName, volumeUuid, moveId, user);
22298                } catch (PackageManagerException e) {
22299                    Slog.w(TAG, "Failed to move " + packageName, e);
22300                    mMoveCallbacks.notifyStatusChanged(moveId,
22301                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22302                }
22303            }
22304        });
22305        return moveId;
22306    }
22307
22308    private void movePackageInternal(final String packageName, final String volumeUuid,
22309            final int moveId, UserHandle user) throws PackageManagerException {
22310        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22311        final PackageManager pm = mContext.getPackageManager();
22312
22313        final boolean currentAsec;
22314        final String currentVolumeUuid;
22315        final File codeFile;
22316        final String installerPackageName;
22317        final String packageAbiOverride;
22318        final int appId;
22319        final String seinfo;
22320        final String label;
22321        final int targetSdkVersion;
22322        final PackageFreezer freezer;
22323        final int[] installedUserIds;
22324
22325        // reader
22326        synchronized (mPackages) {
22327            final PackageParser.Package pkg = mPackages.get(packageName);
22328            final PackageSetting ps = mSettings.mPackages.get(packageName);
22329            if (pkg == null || ps == null) {
22330                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22331            }
22332
22333            if (pkg.applicationInfo.isSystemApp()) {
22334                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22335                        "Cannot move system application");
22336            }
22337
22338            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22339            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22340                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22341            if (isInternalStorage && !allow3rdPartyOnInternal) {
22342                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22343                        "3rd party apps are not allowed on internal storage");
22344            }
22345
22346            if (pkg.applicationInfo.isExternalAsec()) {
22347                currentAsec = true;
22348                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22349            } else if (pkg.applicationInfo.isForwardLocked()) {
22350                currentAsec = true;
22351                currentVolumeUuid = "forward_locked";
22352            } else {
22353                currentAsec = false;
22354                currentVolumeUuid = ps.volumeUuid;
22355
22356                final File probe = new File(pkg.codePath);
22357                final File probeOat = new File(probe, "oat");
22358                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22359                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22360                            "Move only supported for modern cluster style installs");
22361                }
22362            }
22363
22364            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22365                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22366                        "Package already moved to " + volumeUuid);
22367            }
22368            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22369                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22370                        "Device admin cannot be moved");
22371            }
22372
22373            if (mFrozenPackages.contains(packageName)) {
22374                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22375                        "Failed to move already frozen package");
22376            }
22377
22378            codeFile = new File(pkg.codePath);
22379            installerPackageName = ps.installerPackageName;
22380            packageAbiOverride = ps.cpuAbiOverrideString;
22381            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22382            seinfo = pkg.applicationInfo.seInfo;
22383            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22384            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22385            freezer = freezePackage(packageName, "movePackageInternal");
22386            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22387        }
22388
22389        final Bundle extras = new Bundle();
22390        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22391        extras.putString(Intent.EXTRA_TITLE, label);
22392        mMoveCallbacks.notifyCreated(moveId, extras);
22393
22394        int installFlags;
22395        final boolean moveCompleteApp;
22396        final File measurePath;
22397
22398        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22399            installFlags = INSTALL_INTERNAL;
22400            moveCompleteApp = !currentAsec;
22401            measurePath = Environment.getDataAppDirectory(volumeUuid);
22402        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22403            installFlags = INSTALL_EXTERNAL;
22404            moveCompleteApp = false;
22405            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22406        } else {
22407            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22408            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22409                    || !volume.isMountedWritable()) {
22410                freezer.close();
22411                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22412                        "Move location not mounted private volume");
22413            }
22414
22415            Preconditions.checkState(!currentAsec);
22416
22417            installFlags = INSTALL_INTERNAL;
22418            moveCompleteApp = true;
22419            measurePath = Environment.getDataAppDirectory(volumeUuid);
22420        }
22421
22422        final PackageStats stats = new PackageStats(null, -1);
22423        synchronized (mInstaller) {
22424            for (int userId : installedUserIds) {
22425                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22426                    freezer.close();
22427                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22428                            "Failed to measure package size");
22429                }
22430            }
22431        }
22432
22433        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22434                + stats.dataSize);
22435
22436        final long startFreeBytes = measurePath.getUsableSpace();
22437        final long sizeBytes;
22438        if (moveCompleteApp) {
22439            sizeBytes = stats.codeSize + stats.dataSize;
22440        } else {
22441            sizeBytes = stats.codeSize;
22442        }
22443
22444        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22445            freezer.close();
22446            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22447                    "Not enough free space to move");
22448        }
22449
22450        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22451
22452        final CountDownLatch installedLatch = new CountDownLatch(1);
22453        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22454            @Override
22455            public void onUserActionRequired(Intent intent) throws RemoteException {
22456                throw new IllegalStateException();
22457            }
22458
22459            @Override
22460            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22461                    Bundle extras) throws RemoteException {
22462                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22463                        + PackageManager.installStatusToString(returnCode, msg));
22464
22465                installedLatch.countDown();
22466                freezer.close();
22467
22468                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22469                switch (status) {
22470                    case PackageInstaller.STATUS_SUCCESS:
22471                        mMoveCallbacks.notifyStatusChanged(moveId,
22472                                PackageManager.MOVE_SUCCEEDED);
22473                        break;
22474                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22475                        mMoveCallbacks.notifyStatusChanged(moveId,
22476                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22477                        break;
22478                    default:
22479                        mMoveCallbacks.notifyStatusChanged(moveId,
22480                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22481                        break;
22482                }
22483            }
22484        };
22485
22486        final MoveInfo move;
22487        if (moveCompleteApp) {
22488            // Kick off a thread to report progress estimates
22489            new Thread() {
22490                @Override
22491                public void run() {
22492                    while (true) {
22493                        try {
22494                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22495                                break;
22496                            }
22497                        } catch (InterruptedException ignored) {
22498                        }
22499
22500                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22501                        final int progress = 10 + (int) MathUtils.constrain(
22502                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22503                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22504                    }
22505                }
22506            }.start();
22507
22508            final String dataAppName = codeFile.getName();
22509            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22510                    dataAppName, appId, seinfo, targetSdkVersion);
22511        } else {
22512            move = null;
22513        }
22514
22515        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22516
22517        final Message msg = mHandler.obtainMessage(INIT_COPY);
22518        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22519        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22520                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22521                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22522                PackageManager.INSTALL_REASON_UNKNOWN);
22523        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22524        msg.obj = params;
22525
22526        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22527                System.identityHashCode(msg.obj));
22528        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22529                System.identityHashCode(msg.obj));
22530
22531        mHandler.sendMessage(msg);
22532    }
22533
22534    @Override
22535    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22536        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22537
22538        final int realMoveId = mNextMoveId.getAndIncrement();
22539        final Bundle extras = new Bundle();
22540        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22541        mMoveCallbacks.notifyCreated(realMoveId, extras);
22542
22543        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22544            @Override
22545            public void onCreated(int moveId, Bundle extras) {
22546                // Ignored
22547            }
22548
22549            @Override
22550            public void onStatusChanged(int moveId, int status, long estMillis) {
22551                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22552            }
22553        };
22554
22555        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22556        storage.setPrimaryStorageUuid(volumeUuid, callback);
22557        return realMoveId;
22558    }
22559
22560    @Override
22561    public int getMoveStatus(int moveId) {
22562        mContext.enforceCallingOrSelfPermission(
22563                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22564        return mMoveCallbacks.mLastStatus.get(moveId);
22565    }
22566
22567    @Override
22568    public void registerMoveCallback(IPackageMoveObserver callback) {
22569        mContext.enforceCallingOrSelfPermission(
22570                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22571        mMoveCallbacks.register(callback);
22572    }
22573
22574    @Override
22575    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22576        mContext.enforceCallingOrSelfPermission(
22577                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22578        mMoveCallbacks.unregister(callback);
22579    }
22580
22581    @Override
22582    public boolean setInstallLocation(int loc) {
22583        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22584                null);
22585        if (getInstallLocation() == loc) {
22586            return true;
22587        }
22588        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22589                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22590            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22591                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22592            return true;
22593        }
22594        return false;
22595   }
22596
22597    @Override
22598    public int getInstallLocation() {
22599        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22600                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22601                PackageHelper.APP_INSTALL_AUTO);
22602    }
22603
22604    /** Called by UserManagerService */
22605    void cleanUpUser(UserManagerService userManager, int userHandle) {
22606        synchronized (mPackages) {
22607            mDirtyUsers.remove(userHandle);
22608            mUserNeedsBadging.delete(userHandle);
22609            mSettings.removeUserLPw(userHandle);
22610            mPendingBroadcasts.remove(userHandle);
22611            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22612            removeUnusedPackagesLPw(userManager, userHandle);
22613        }
22614    }
22615
22616    /**
22617     * We're removing userHandle and would like to remove any downloaded packages
22618     * that are no longer in use by any other user.
22619     * @param userHandle the user being removed
22620     */
22621    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22622        final boolean DEBUG_CLEAN_APKS = false;
22623        int [] users = userManager.getUserIds();
22624        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22625        while (psit.hasNext()) {
22626            PackageSetting ps = psit.next();
22627            if (ps.pkg == null) {
22628                continue;
22629            }
22630            final String packageName = ps.pkg.packageName;
22631            // Skip over if system app
22632            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22633                continue;
22634            }
22635            if (DEBUG_CLEAN_APKS) {
22636                Slog.i(TAG, "Checking package " + packageName);
22637            }
22638            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22639            if (keep) {
22640                if (DEBUG_CLEAN_APKS) {
22641                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22642                }
22643            } else {
22644                for (int i = 0; i < users.length; i++) {
22645                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22646                        keep = true;
22647                        if (DEBUG_CLEAN_APKS) {
22648                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22649                                    + users[i]);
22650                        }
22651                        break;
22652                    }
22653                }
22654            }
22655            if (!keep) {
22656                if (DEBUG_CLEAN_APKS) {
22657                    Slog.i(TAG, "  Removing package " + packageName);
22658                }
22659                mHandler.post(new Runnable() {
22660                    public void run() {
22661                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22662                                userHandle, 0);
22663                    } //end run
22664                });
22665            }
22666        }
22667    }
22668
22669    /** Called by UserManagerService */
22670    void createNewUser(int userId, String[] disallowedPackages) {
22671        synchronized (mInstallLock) {
22672            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22673        }
22674        synchronized (mPackages) {
22675            scheduleWritePackageRestrictionsLocked(userId);
22676            scheduleWritePackageListLocked(userId);
22677            applyFactoryDefaultBrowserLPw(userId);
22678            primeDomainVerificationsLPw(userId);
22679        }
22680    }
22681
22682    void onNewUserCreated(final int userId) {
22683        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22684        // If permission review for legacy apps is required, we represent
22685        // dagerous permissions for such apps as always granted runtime
22686        // permissions to keep per user flag state whether review is needed.
22687        // Hence, if a new user is added we have to propagate dangerous
22688        // permission grants for these legacy apps.
22689        if (mPermissionReviewRequired) {
22690            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22691                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22692        }
22693    }
22694
22695    @Override
22696    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22697        mContext.enforceCallingOrSelfPermission(
22698                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22699                "Only package verification agents can read the verifier device identity");
22700
22701        synchronized (mPackages) {
22702            return mSettings.getVerifierDeviceIdentityLPw();
22703        }
22704    }
22705
22706    @Override
22707    public void setPermissionEnforced(String permission, boolean enforced) {
22708        // TODO: Now that we no longer change GID for storage, this should to away.
22709        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22710                "setPermissionEnforced");
22711        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22712            synchronized (mPackages) {
22713                if (mSettings.mReadExternalStorageEnforced == null
22714                        || mSettings.mReadExternalStorageEnforced != enforced) {
22715                    mSettings.mReadExternalStorageEnforced = enforced;
22716                    mSettings.writeLPr();
22717                }
22718            }
22719            // kill any non-foreground processes so we restart them and
22720            // grant/revoke the GID.
22721            final IActivityManager am = ActivityManager.getService();
22722            if (am != null) {
22723                final long token = Binder.clearCallingIdentity();
22724                try {
22725                    am.killProcessesBelowForeground("setPermissionEnforcement");
22726                } catch (RemoteException e) {
22727                } finally {
22728                    Binder.restoreCallingIdentity(token);
22729                }
22730            }
22731        } else {
22732            throw new IllegalArgumentException("No selective enforcement for " + permission);
22733        }
22734    }
22735
22736    @Override
22737    @Deprecated
22738    public boolean isPermissionEnforced(String permission) {
22739        return true;
22740    }
22741
22742    @Override
22743    public boolean isStorageLow() {
22744        final long token = Binder.clearCallingIdentity();
22745        try {
22746            final DeviceStorageMonitorInternal
22747                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22748            if (dsm != null) {
22749                return dsm.isMemoryLow();
22750            } else {
22751                return false;
22752            }
22753        } finally {
22754            Binder.restoreCallingIdentity(token);
22755        }
22756    }
22757
22758    @Override
22759    public IPackageInstaller getPackageInstaller() {
22760        return mInstallerService;
22761    }
22762
22763    private boolean userNeedsBadging(int userId) {
22764        int index = mUserNeedsBadging.indexOfKey(userId);
22765        if (index < 0) {
22766            final UserInfo userInfo;
22767            final long token = Binder.clearCallingIdentity();
22768            try {
22769                userInfo = sUserManager.getUserInfo(userId);
22770            } finally {
22771                Binder.restoreCallingIdentity(token);
22772            }
22773            final boolean b;
22774            if (userInfo != null && userInfo.isManagedProfile()) {
22775                b = true;
22776            } else {
22777                b = false;
22778            }
22779            mUserNeedsBadging.put(userId, b);
22780            return b;
22781        }
22782        return mUserNeedsBadging.valueAt(index);
22783    }
22784
22785    @Override
22786    public KeySet getKeySetByAlias(String packageName, String alias) {
22787        if (packageName == null || alias == null) {
22788            return null;
22789        }
22790        synchronized(mPackages) {
22791            final PackageParser.Package pkg = mPackages.get(packageName);
22792            if (pkg == null) {
22793                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22794                throw new IllegalArgumentException("Unknown package: " + packageName);
22795            }
22796            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22797            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22798        }
22799    }
22800
22801    @Override
22802    public KeySet getSigningKeySet(String packageName) {
22803        if (packageName == null) {
22804            return null;
22805        }
22806        synchronized(mPackages) {
22807            final PackageParser.Package pkg = mPackages.get(packageName);
22808            if (pkg == null) {
22809                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22810                throw new IllegalArgumentException("Unknown package: " + packageName);
22811            }
22812            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22813                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22814                throw new SecurityException("May not access signing KeySet of other apps.");
22815            }
22816            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22817            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22818        }
22819    }
22820
22821    @Override
22822    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22823        if (packageName == null || ks == null) {
22824            return false;
22825        }
22826        synchronized(mPackages) {
22827            final PackageParser.Package pkg = mPackages.get(packageName);
22828            if (pkg == null) {
22829                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22830                throw new IllegalArgumentException("Unknown package: " + packageName);
22831            }
22832            IBinder ksh = ks.getToken();
22833            if (ksh instanceof KeySetHandle) {
22834                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22835                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22836            }
22837            return false;
22838        }
22839    }
22840
22841    @Override
22842    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22843        if (packageName == null || ks == null) {
22844            return false;
22845        }
22846        synchronized(mPackages) {
22847            final PackageParser.Package pkg = mPackages.get(packageName);
22848            if (pkg == null) {
22849                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22850                throw new IllegalArgumentException("Unknown package: " + packageName);
22851            }
22852            IBinder ksh = ks.getToken();
22853            if (ksh instanceof KeySetHandle) {
22854                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22855                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22856            }
22857            return false;
22858        }
22859    }
22860
22861    private void deletePackageIfUnusedLPr(final String packageName) {
22862        PackageSetting ps = mSettings.mPackages.get(packageName);
22863        if (ps == null) {
22864            return;
22865        }
22866        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22867            // TODO Implement atomic delete if package is unused
22868            // It is currently possible that the package will be deleted even if it is installed
22869            // after this method returns.
22870            mHandler.post(new Runnable() {
22871                public void run() {
22872                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22873                            0, PackageManager.DELETE_ALL_USERS);
22874                }
22875            });
22876        }
22877    }
22878
22879    /**
22880     * Check and throw if the given before/after packages would be considered a
22881     * downgrade.
22882     */
22883    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22884            throws PackageManagerException {
22885        if (after.versionCode < before.mVersionCode) {
22886            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22887                    "Update version code " + after.versionCode + " is older than current "
22888                    + before.mVersionCode);
22889        } else if (after.versionCode == before.mVersionCode) {
22890            if (after.baseRevisionCode < before.baseRevisionCode) {
22891                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22892                        "Update base revision code " + after.baseRevisionCode
22893                        + " is older than current " + before.baseRevisionCode);
22894            }
22895
22896            if (!ArrayUtils.isEmpty(after.splitNames)) {
22897                for (int i = 0; i < after.splitNames.length; i++) {
22898                    final String splitName = after.splitNames[i];
22899                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22900                    if (j != -1) {
22901                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22902                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22903                                    "Update split " + splitName + " revision code "
22904                                    + after.splitRevisionCodes[i] + " is older than current "
22905                                    + before.splitRevisionCodes[j]);
22906                        }
22907                    }
22908                }
22909            }
22910        }
22911    }
22912
22913    private static class MoveCallbacks extends Handler {
22914        private static final int MSG_CREATED = 1;
22915        private static final int MSG_STATUS_CHANGED = 2;
22916
22917        private final RemoteCallbackList<IPackageMoveObserver>
22918                mCallbacks = new RemoteCallbackList<>();
22919
22920        private final SparseIntArray mLastStatus = new SparseIntArray();
22921
22922        public MoveCallbacks(Looper looper) {
22923            super(looper);
22924        }
22925
22926        public void register(IPackageMoveObserver callback) {
22927            mCallbacks.register(callback);
22928        }
22929
22930        public void unregister(IPackageMoveObserver callback) {
22931            mCallbacks.unregister(callback);
22932        }
22933
22934        @Override
22935        public void handleMessage(Message msg) {
22936            final SomeArgs args = (SomeArgs) msg.obj;
22937            final int n = mCallbacks.beginBroadcast();
22938            for (int i = 0; i < n; i++) {
22939                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22940                try {
22941                    invokeCallback(callback, msg.what, args);
22942                } catch (RemoteException ignored) {
22943                }
22944            }
22945            mCallbacks.finishBroadcast();
22946            args.recycle();
22947        }
22948
22949        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22950                throws RemoteException {
22951            switch (what) {
22952                case MSG_CREATED: {
22953                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22954                    break;
22955                }
22956                case MSG_STATUS_CHANGED: {
22957                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22958                    break;
22959                }
22960            }
22961        }
22962
22963        private void notifyCreated(int moveId, Bundle extras) {
22964            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22965
22966            final SomeArgs args = SomeArgs.obtain();
22967            args.argi1 = moveId;
22968            args.arg2 = extras;
22969            obtainMessage(MSG_CREATED, args).sendToTarget();
22970        }
22971
22972        private void notifyStatusChanged(int moveId, int status) {
22973            notifyStatusChanged(moveId, status, -1);
22974        }
22975
22976        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22977            Slog.v(TAG, "Move " + moveId + " status " + status);
22978
22979            final SomeArgs args = SomeArgs.obtain();
22980            args.argi1 = moveId;
22981            args.argi2 = status;
22982            args.arg3 = estMillis;
22983            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22984
22985            synchronized (mLastStatus) {
22986                mLastStatus.put(moveId, status);
22987            }
22988        }
22989    }
22990
22991    private final static class OnPermissionChangeListeners extends Handler {
22992        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22993
22994        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22995                new RemoteCallbackList<>();
22996
22997        public OnPermissionChangeListeners(Looper looper) {
22998            super(looper);
22999        }
23000
23001        @Override
23002        public void handleMessage(Message msg) {
23003            switch (msg.what) {
23004                case MSG_ON_PERMISSIONS_CHANGED: {
23005                    final int uid = msg.arg1;
23006                    handleOnPermissionsChanged(uid);
23007                } break;
23008            }
23009        }
23010
23011        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23012            mPermissionListeners.register(listener);
23013
23014        }
23015
23016        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23017            mPermissionListeners.unregister(listener);
23018        }
23019
23020        public void onPermissionsChanged(int uid) {
23021            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23022                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23023            }
23024        }
23025
23026        private void handleOnPermissionsChanged(int uid) {
23027            final int count = mPermissionListeners.beginBroadcast();
23028            try {
23029                for (int i = 0; i < count; i++) {
23030                    IOnPermissionsChangeListener callback = mPermissionListeners
23031                            .getBroadcastItem(i);
23032                    try {
23033                        callback.onPermissionsChanged(uid);
23034                    } catch (RemoteException e) {
23035                        Log.e(TAG, "Permission listener is dead", e);
23036                    }
23037                }
23038            } finally {
23039                mPermissionListeners.finishBroadcast();
23040            }
23041        }
23042    }
23043
23044    private class PackageManagerInternalImpl extends PackageManagerInternal {
23045        @Override
23046        public void setLocationPackagesProvider(PackagesProvider provider) {
23047            synchronized (mPackages) {
23048                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23049            }
23050        }
23051
23052        @Override
23053        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23054            synchronized (mPackages) {
23055                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23056            }
23057        }
23058
23059        @Override
23060        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23061            synchronized (mPackages) {
23062                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23063            }
23064        }
23065
23066        @Override
23067        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23068            synchronized (mPackages) {
23069                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23070            }
23071        }
23072
23073        @Override
23074        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23075            synchronized (mPackages) {
23076                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23077            }
23078        }
23079
23080        @Override
23081        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23082            synchronized (mPackages) {
23083                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23084            }
23085        }
23086
23087        @Override
23088        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23089            synchronized (mPackages) {
23090                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23091                        packageName, userId);
23092            }
23093        }
23094
23095        @Override
23096        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23097            synchronized (mPackages) {
23098                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23099                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23100                        packageName, userId);
23101            }
23102        }
23103
23104        @Override
23105        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23106            synchronized (mPackages) {
23107                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23108                        packageName, userId);
23109            }
23110        }
23111
23112        @Override
23113        public void setKeepUninstalledPackages(final List<String> packageList) {
23114            Preconditions.checkNotNull(packageList);
23115            List<String> removedFromList = null;
23116            synchronized (mPackages) {
23117                if (mKeepUninstalledPackages != null) {
23118                    final int packagesCount = mKeepUninstalledPackages.size();
23119                    for (int i = 0; i < packagesCount; i++) {
23120                        String oldPackage = mKeepUninstalledPackages.get(i);
23121                        if (packageList != null && packageList.contains(oldPackage)) {
23122                            continue;
23123                        }
23124                        if (removedFromList == null) {
23125                            removedFromList = new ArrayList<>();
23126                        }
23127                        removedFromList.add(oldPackage);
23128                    }
23129                }
23130                mKeepUninstalledPackages = new ArrayList<>(packageList);
23131                if (removedFromList != null) {
23132                    final int removedCount = removedFromList.size();
23133                    for (int i = 0; i < removedCount; i++) {
23134                        deletePackageIfUnusedLPr(removedFromList.get(i));
23135                    }
23136                }
23137            }
23138        }
23139
23140        @Override
23141        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23142            synchronized (mPackages) {
23143                // If we do not support permission review, done.
23144                if (!mPermissionReviewRequired) {
23145                    return false;
23146                }
23147
23148                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23149                if (packageSetting == null) {
23150                    return false;
23151                }
23152
23153                // Permission review applies only to apps not supporting the new permission model.
23154                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23155                    return false;
23156                }
23157
23158                // Legacy apps have the permission and get user consent on launch.
23159                PermissionsState permissionsState = packageSetting.getPermissionsState();
23160                return permissionsState.isPermissionReviewRequired(userId);
23161            }
23162        }
23163
23164        @Override
23165        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23166            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23167        }
23168
23169        @Override
23170        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23171                int userId) {
23172            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23173        }
23174
23175        @Override
23176        public void setDeviceAndProfileOwnerPackages(
23177                int deviceOwnerUserId, String deviceOwnerPackage,
23178                SparseArray<String> profileOwnerPackages) {
23179            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23180                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23181        }
23182
23183        @Override
23184        public boolean isPackageDataProtected(int userId, String packageName) {
23185            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23186        }
23187
23188        @Override
23189        public boolean isPackageEphemeral(int userId, String packageName) {
23190            synchronized (mPackages) {
23191                final PackageSetting ps = mSettings.mPackages.get(packageName);
23192                return ps != null ? ps.getInstantApp(userId) : false;
23193            }
23194        }
23195
23196        @Override
23197        public boolean wasPackageEverLaunched(String packageName, int userId) {
23198            synchronized (mPackages) {
23199                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23200            }
23201        }
23202
23203        @Override
23204        public void grantRuntimePermission(String packageName, String name, int userId,
23205                boolean overridePolicy) {
23206            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23207                    overridePolicy);
23208        }
23209
23210        @Override
23211        public void revokeRuntimePermission(String packageName, String name, int userId,
23212                boolean overridePolicy) {
23213            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23214                    overridePolicy);
23215        }
23216
23217        @Override
23218        public String getNameForUid(int uid) {
23219            return PackageManagerService.this.getNameForUid(uid);
23220        }
23221
23222        @Override
23223        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23224                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23225            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23226                    responseObj, origIntent, resolvedType, callingPackage, userId);
23227        }
23228
23229        @Override
23230        public void grantEphemeralAccess(int userId, Intent intent,
23231                int targetAppId, int ephemeralAppId) {
23232            synchronized (mPackages) {
23233                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23234                        targetAppId, ephemeralAppId);
23235            }
23236        }
23237
23238        @Override
23239        public boolean isInstantAppInstallerComponent(ComponentName component) {
23240            synchronized (mPackages) {
23241                return mInstantAppInstallerActivity != null
23242                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23243            }
23244        }
23245
23246        @Override
23247        public void pruneInstantApps() {
23248            synchronized (mPackages) {
23249                mInstantAppRegistry.pruneInstantAppsLPw();
23250            }
23251        }
23252
23253        @Override
23254        public String getSetupWizardPackageName() {
23255            return mSetupWizardPackage;
23256        }
23257
23258        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23259            if (policy != null) {
23260                mExternalSourcesPolicy = policy;
23261            }
23262        }
23263
23264        @Override
23265        public boolean isPackagePersistent(String packageName) {
23266            synchronized (mPackages) {
23267                PackageParser.Package pkg = mPackages.get(packageName);
23268                return pkg != null
23269                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23270                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23271                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23272                        : false;
23273            }
23274        }
23275
23276        @Override
23277        public List<PackageInfo> getOverlayPackages(int userId) {
23278            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23279            synchronized (mPackages) {
23280                for (PackageParser.Package p : mPackages.values()) {
23281                    if (p.mOverlayTarget != null) {
23282                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23283                        if (pkg != null) {
23284                            overlayPackages.add(pkg);
23285                        }
23286                    }
23287                }
23288            }
23289            return overlayPackages;
23290        }
23291
23292        @Override
23293        public List<String> getTargetPackageNames(int userId) {
23294            List<String> targetPackages = new ArrayList<>();
23295            synchronized (mPackages) {
23296                for (PackageParser.Package p : mPackages.values()) {
23297                    if (p.mOverlayTarget == null) {
23298                        targetPackages.add(p.packageName);
23299                    }
23300                }
23301            }
23302            return targetPackages;
23303        }
23304
23305        @Override
23306        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23307                @Nullable List<String> overlayPackageNames) {
23308            synchronized (mPackages) {
23309                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23310                    Slog.e(TAG, "failed to find package " + targetPackageName);
23311                    return false;
23312                }
23313
23314                ArrayList<String> paths = null;
23315                if (overlayPackageNames != null) {
23316                    final int N = overlayPackageNames.size();
23317                    paths = new ArrayList<>(N);
23318                    for (int i = 0; i < N; i++) {
23319                        final String packageName = overlayPackageNames.get(i);
23320                        final PackageParser.Package pkg = mPackages.get(packageName);
23321                        if (pkg == null) {
23322                            Slog.e(TAG, "failed to find package " + packageName);
23323                            return false;
23324                        }
23325                        paths.add(pkg.baseCodePath);
23326                    }
23327                }
23328
23329                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23330                    mEnabledOverlayPaths.get(userId);
23331                if (userSpecificOverlays == null) {
23332                    userSpecificOverlays = new ArrayMap<>();
23333                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23334                }
23335
23336                if (paths != null && paths.size() > 0) {
23337                    userSpecificOverlays.put(targetPackageName, paths);
23338                } else {
23339                    userSpecificOverlays.remove(targetPackageName);
23340                }
23341                return true;
23342            }
23343        }
23344
23345        @Override
23346        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23347                int flags, int userId) {
23348            return resolveIntentInternal(
23349                    intent, resolvedType, flags, userId, true /*includeInstantApps*/);
23350        }
23351
23352        @Override
23353        public ResolveInfo resolveService(Intent intent, String resolvedType,
23354                int flags, int userId, int callingUid) {
23355            return resolveServiceInternal(
23356                    intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/);
23357        }
23358
23359
23360        @Override
23361        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23362            synchronized (mPackages) {
23363                mIsolatedOwners.put(isolatedUid, ownerUid);
23364            }
23365        }
23366
23367        @Override
23368        public void removeIsolatedUid(int isolatedUid) {
23369            synchronized (mPackages) {
23370                mIsolatedOwners.delete(isolatedUid);
23371            }
23372        }
23373    }
23374
23375    @Override
23376    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23377        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23378        synchronized (mPackages) {
23379            final long identity = Binder.clearCallingIdentity();
23380            try {
23381                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23382                        packageNames, userId);
23383            } finally {
23384                Binder.restoreCallingIdentity(identity);
23385            }
23386        }
23387    }
23388
23389    @Override
23390    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23391        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23392        synchronized (mPackages) {
23393            final long identity = Binder.clearCallingIdentity();
23394            try {
23395                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23396                        packageNames, userId);
23397            } finally {
23398                Binder.restoreCallingIdentity(identity);
23399            }
23400        }
23401    }
23402
23403    private static void enforceSystemOrPhoneCaller(String tag) {
23404        int callingUid = Binder.getCallingUid();
23405        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23406            throw new SecurityException(
23407                    "Cannot call " + tag + " from UID " + callingUid);
23408        }
23409    }
23410
23411    boolean isHistoricalPackageUsageAvailable() {
23412        return mPackageUsage.isHistoricalPackageUsageAvailable();
23413    }
23414
23415    /**
23416     * Return a <b>copy</b> of the collection of packages known to the package manager.
23417     * @return A copy of the values of mPackages.
23418     */
23419    Collection<PackageParser.Package> getPackages() {
23420        synchronized (mPackages) {
23421            return new ArrayList<>(mPackages.values());
23422        }
23423    }
23424
23425    /**
23426     * Logs process start information (including base APK hash) to the security log.
23427     * @hide
23428     */
23429    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23430            String apkFile, int pid) {
23431        if (!SecurityLog.isLoggingEnabled()) {
23432            return;
23433        }
23434        Bundle data = new Bundle();
23435        data.putLong("startTimestamp", System.currentTimeMillis());
23436        data.putString("processName", processName);
23437        data.putInt("uid", uid);
23438        data.putString("seinfo", seinfo);
23439        data.putString("apkFile", apkFile);
23440        data.putInt("pid", pid);
23441        Message msg = mProcessLoggingHandler.obtainMessage(
23442                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23443        msg.setData(data);
23444        mProcessLoggingHandler.sendMessage(msg);
23445    }
23446
23447    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23448        return mCompilerStats.getPackageStats(pkgName);
23449    }
23450
23451    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23452        return getOrCreateCompilerPackageStats(pkg.packageName);
23453    }
23454
23455    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23456        return mCompilerStats.getOrCreatePackageStats(pkgName);
23457    }
23458
23459    public void deleteCompilerPackageStats(String pkgName) {
23460        mCompilerStats.deletePackageStats(pkgName);
23461    }
23462
23463    @Override
23464    public int getInstallReason(String packageName, int userId) {
23465        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23466                true /* requireFullPermission */, false /* checkShell */,
23467                "get install reason");
23468        synchronized (mPackages) {
23469            final PackageSetting ps = mSettings.mPackages.get(packageName);
23470            if (ps != null) {
23471                return ps.getInstallReason(userId);
23472            }
23473        }
23474        return PackageManager.INSTALL_REASON_UNKNOWN;
23475    }
23476
23477    @Override
23478    public boolean canRequestPackageInstalls(String packageName, int userId) {
23479        int callingUid = Binder.getCallingUid();
23480        int uid = getPackageUid(packageName, 0, userId);
23481        if (callingUid != uid && callingUid != Process.ROOT_UID
23482                && callingUid != Process.SYSTEM_UID) {
23483            throw new SecurityException(
23484                    "Caller uid " + callingUid + " does not own package " + packageName);
23485        }
23486        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23487        if (info == null) {
23488            return false;
23489        }
23490        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23491            throw new UnsupportedOperationException(
23492                    "Operation only supported on apps targeting Android O or higher");
23493        }
23494        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23495        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23496        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23497            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23498        }
23499        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23500            return false;
23501        }
23502        if (mExternalSourcesPolicy != null) {
23503            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23504            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23505                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23506            }
23507        }
23508        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23509    }
23510
23511    @Override
23512    public ComponentName getInstantAppResolverSettingsComponent() {
23513        return mInstantAppResolverSettingsComponent;
23514    }
23515}
23516