PackageManagerService.java revision 0d277a7b189c8807d142b69dd8d00b17978a49a5
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
96import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
97import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
104
105import android.Manifest;
106import android.annotation.NonNull;
107import android.annotation.Nullable;
108import android.app.ActivityManager;
109import android.app.AppOpsManager;
110import android.app.IActivityManager;
111import android.app.ResourcesManager;
112import android.app.admin.IDevicePolicyManager;
113import android.app.admin.SecurityLog;
114import android.app.backup.IBackupManager;
115import android.content.BroadcastReceiver;
116import android.content.ComponentName;
117import android.content.ContentResolver;
118import android.content.Context;
119import android.content.IIntentReceiver;
120import android.content.Intent;
121import android.content.IntentFilter;
122import android.content.IntentSender;
123import android.content.IntentSender.SendIntentException;
124import android.content.ServiceConnection;
125import android.content.pm.ActivityInfo;
126import android.content.pm.ApplicationInfo;
127import android.content.pm.AppsQueryHelper;
128import android.content.pm.ChangedPackages;
129import android.content.pm.ComponentInfo;
130import android.content.pm.InstantAppRequest;
131import android.content.pm.AuxiliaryResolveInfo;
132import android.content.pm.FallbackCategoryProvider;
133import android.content.pm.FeatureInfo;
134import android.content.pm.IOnPermissionsChangeListener;
135import android.content.pm.IPackageDataObserver;
136import android.content.pm.IPackageDeleteObserver;
137import android.content.pm.IPackageDeleteObserver2;
138import android.content.pm.IPackageInstallObserver2;
139import android.content.pm.IPackageInstaller;
140import android.content.pm.IPackageManager;
141import android.content.pm.IPackageMoveObserver;
142import android.content.pm.IPackageStatsObserver;
143import android.content.pm.InstantAppInfo;
144import android.content.pm.InstantAppResolveInfo;
145import android.content.pm.InstrumentationInfo;
146import android.content.pm.IntentFilterVerificationInfo;
147import android.content.pm.KeySet;
148import android.content.pm.PackageCleanItem;
149import android.content.pm.PackageInfo;
150import android.content.pm.PackageInfoLite;
151import android.content.pm.PackageInstaller;
152import android.content.pm.PackageManager;
153import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
154import android.content.pm.PackageManagerInternal;
155import android.content.pm.PackageParser;
156import android.content.pm.PackageParser.ActivityIntentInfo;
157import android.content.pm.PackageParser.PackageLite;
158import android.content.pm.PackageParser.PackageParserException;
159import android.content.pm.PackageStats;
160import android.content.pm.PackageUserState;
161import android.content.pm.ParceledListSlice;
162import android.content.pm.PermissionGroupInfo;
163import android.content.pm.PermissionInfo;
164import android.content.pm.ProviderInfo;
165import android.content.pm.ResolveInfo;
166import android.content.pm.ServiceInfo;
167import android.content.pm.SharedLibraryInfo;
168import android.content.pm.Signature;
169import android.content.pm.UserInfo;
170import android.content.pm.VerifierDeviceIdentity;
171import android.content.pm.VerifierInfo;
172import android.content.pm.VersionedPackage;
173import android.content.res.Resources;
174import android.database.ContentObserver;
175import android.graphics.Bitmap;
176import android.hardware.display.DisplayManager;
177import android.net.Uri;
178import android.os.Binder;
179import android.os.Build;
180import android.os.Bundle;
181import android.os.Debug;
182import android.os.Environment;
183import android.os.Environment.UserEnvironment;
184import android.os.FileUtils;
185import android.os.Handler;
186import android.os.IBinder;
187import android.os.Looper;
188import android.os.Message;
189import android.os.Parcel;
190import android.os.ParcelFileDescriptor;
191import android.os.PatternMatcher;
192import android.os.Process;
193import android.os.RemoteCallbackList;
194import android.os.RemoteException;
195import android.os.ResultReceiver;
196import android.os.SELinux;
197import android.os.ServiceManager;
198import android.os.ShellCallback;
199import android.os.SystemClock;
200import android.os.SystemProperties;
201import android.os.Trace;
202import android.os.UserHandle;
203import android.os.UserManager;
204import android.os.UserManagerInternal;
205import android.os.storage.IStorageManager;
206import android.os.storage.StorageEventListener;
207import android.os.storage.StorageManager;
208import android.os.storage.StorageManagerInternal;
209import android.os.storage.VolumeInfo;
210import android.os.storage.VolumeRecord;
211import android.provider.Settings.Global;
212import android.provider.Settings.Secure;
213import android.security.KeyStore;
214import android.security.SystemKeyStore;
215import android.service.pm.PackageServiceDumpProto;
216import android.system.ErrnoException;
217import android.system.Os;
218import android.text.TextUtils;
219import android.text.format.DateUtils;
220import android.util.ArrayMap;
221import android.util.ArraySet;
222import android.util.Base64;
223import android.util.BootTimingsTraceLog;
224import android.util.DisplayMetrics;
225import android.util.EventLog;
226import android.util.ExceptionUtils;
227import android.util.Log;
228import android.util.LogPrinter;
229import android.util.MathUtils;
230import android.util.PackageUtils;
231import android.util.Pair;
232import android.util.PrintStreamPrinter;
233import android.util.Slog;
234import android.util.SparseArray;
235import android.util.SparseBooleanArray;
236import android.util.SparseIntArray;
237import android.util.Xml;
238import android.util.jar.StrictJarFile;
239import android.util.proto.ProtoOutputStream;
240import android.view.Display;
241
242import com.android.internal.R;
243import com.android.internal.annotations.GuardedBy;
244import com.android.internal.app.IMediaContainerService;
245import com.android.internal.app.ResolverActivity;
246import com.android.internal.content.NativeLibraryHelper;
247import com.android.internal.content.PackageHelper;
248import com.android.internal.logging.MetricsLogger;
249import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
250import com.android.internal.os.IParcelFileDescriptorFactory;
251import com.android.internal.os.RoSystemProperties;
252import com.android.internal.os.SomeArgs;
253import com.android.internal.os.Zygote;
254import com.android.internal.telephony.CarrierAppUtils;
255import com.android.internal.util.ArrayUtils;
256import com.android.internal.util.ConcurrentUtils;
257import com.android.internal.util.DumpUtils;
258import com.android.internal.util.FastPrintWriter;
259import com.android.internal.util.FastXmlSerializer;
260import com.android.internal.util.IndentingPrintWriter;
261import com.android.internal.util.Preconditions;
262import com.android.internal.util.XmlUtils;
263import com.android.server.AttributeCache;
264import com.android.server.DeviceIdleController;
265import com.android.server.EventLogTags;
266import com.android.server.FgThread;
267import com.android.server.IntentResolver;
268import com.android.server.LocalServices;
269import com.android.server.LockGuard;
270import com.android.server.ServiceThread;
271import com.android.server.SystemConfig;
272import com.android.server.SystemServerInitThreadPool;
273import com.android.server.Watchdog;
274import com.android.server.net.NetworkPolicyManagerInternal;
275import com.android.server.pm.Installer.InstallerException;
276import com.android.server.pm.PermissionsState.PermissionState;
277import com.android.server.pm.Settings.DatabaseVersion;
278import com.android.server.pm.Settings.VersionInfo;
279import com.android.server.pm.dex.DexManager;
280import com.android.server.storage.DeviceStorageMonitorInternal;
281
282import dalvik.system.CloseGuard;
283import dalvik.system.DexFile;
284import dalvik.system.VMRuntime;
285
286import libcore.io.IoUtils;
287import libcore.util.EmptyArray;
288
289import org.xmlpull.v1.XmlPullParser;
290import org.xmlpull.v1.XmlPullParserException;
291import org.xmlpull.v1.XmlSerializer;
292
293import java.io.BufferedOutputStream;
294import java.io.BufferedReader;
295import java.io.ByteArrayInputStream;
296import java.io.ByteArrayOutputStream;
297import java.io.File;
298import java.io.FileDescriptor;
299import java.io.FileInputStream;
300import java.io.FileOutputStream;
301import java.io.FileReader;
302import java.io.FilenameFilter;
303import java.io.IOException;
304import java.io.PrintWriter;
305import java.nio.charset.StandardCharsets;
306import java.security.DigestInputStream;
307import java.security.MessageDigest;
308import java.security.NoSuchAlgorithmException;
309import java.security.PublicKey;
310import java.security.SecureRandom;
311import java.security.cert.Certificate;
312import java.security.cert.CertificateEncodingException;
313import java.security.cert.CertificateException;
314import java.text.SimpleDateFormat;
315import java.util.ArrayList;
316import java.util.Arrays;
317import java.util.Collection;
318import java.util.Collections;
319import java.util.Comparator;
320import java.util.Date;
321import java.util.HashMap;
322import java.util.HashSet;
323import java.util.Iterator;
324import java.util.List;
325import java.util.Map;
326import java.util.Objects;
327import java.util.Set;
328import java.util.concurrent.CountDownLatch;
329import java.util.concurrent.Future;
330import java.util.concurrent.TimeUnit;
331import java.util.concurrent.atomic.AtomicBoolean;
332import java.util.concurrent.atomic.AtomicInteger;
333
334/**
335 * Keep track of all those APKs everywhere.
336 * <p>
337 * Internally there are two important locks:
338 * <ul>
339 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
340 * and other related state. It is a fine-grained lock that should only be held
341 * momentarily, as it's one of the most contended locks in the system.
342 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
343 * operations typically involve heavy lifting of application data on disk. Since
344 * {@code installd} is single-threaded, and it's operations can often be slow,
345 * this lock should never be acquired while already holding {@link #mPackages}.
346 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
347 * holding {@link #mInstallLock}.
348 * </ul>
349 * Many internal methods rely on the caller to hold the appropriate locks, and
350 * this contract is expressed through method name suffixes:
351 * <ul>
352 * <li>fooLI(): the caller must hold {@link #mInstallLock}
353 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
354 * being modified must be frozen
355 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
356 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
357 * </ul>
358 * <p>
359 * Because this class is very central to the platform's security; please run all
360 * CTS and unit tests whenever making modifications:
361 *
362 * <pre>
363 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
364 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
365 * </pre>
366 */
367public class PackageManagerService extends IPackageManager.Stub
368        implements PackageSender {
369    static final String TAG = "PackageManager";
370    static final boolean DEBUG_SETTINGS = false;
371    static final boolean DEBUG_PREFERRED = false;
372    static final boolean DEBUG_UPGRADE = false;
373    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
374    private static final boolean DEBUG_BACKUP = false;
375    private static final boolean DEBUG_INSTALL = false;
376    private static final boolean DEBUG_REMOVE = false;
377    private static final boolean DEBUG_BROADCASTS = false;
378    private static final boolean DEBUG_SHOW_INFO = false;
379    private static final boolean DEBUG_PACKAGE_INFO = false;
380    private static final boolean DEBUG_INTENT_MATCHING = false;
381    private static final boolean DEBUG_PACKAGE_SCANNING = false;
382    private static final boolean DEBUG_VERIFY = false;
383    private static final boolean DEBUG_FILTERS = false;
384
385    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
386    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
387    // user, but by default initialize to this.
388    public static final boolean DEBUG_DEXOPT = false;
389
390    private static final boolean DEBUG_ABI_SELECTION = false;
391    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
392    private static final boolean DEBUG_TRIAGED_MISSING = false;
393    private static final boolean DEBUG_APP_DATA = false;
394
395    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
396    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
397
398    private static final boolean HIDE_EPHEMERAL_APIS = false;
399
400    private static final boolean ENABLE_FREE_CACHE_V2 =
401            SystemProperties.getBoolean("fw.free_cache_v2", true);
402
403    private static final int RADIO_UID = Process.PHONE_UID;
404    private static final int LOG_UID = Process.LOG_UID;
405    private static final int NFC_UID = Process.NFC_UID;
406    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
407    private static final int SHELL_UID = Process.SHELL_UID;
408
409    // Cap the size of permission trees that 3rd party apps can define
410    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
411
412    // Suffix used during package installation when copying/moving
413    // package apks to install directory.
414    private static final String INSTALL_PACKAGE_SUFFIX = "-";
415
416    static final int SCAN_NO_DEX = 1<<1;
417    static final int SCAN_FORCE_DEX = 1<<2;
418    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
419    static final int SCAN_NEW_INSTALL = 1<<4;
420    static final int SCAN_UPDATE_TIME = 1<<5;
421    static final int SCAN_BOOTING = 1<<6;
422    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
423    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
424    static final int SCAN_REPLACING = 1<<9;
425    static final int SCAN_REQUIRE_KNOWN = 1<<10;
426    static final int SCAN_MOVE = 1<<11;
427    static final int SCAN_INITIAL = 1<<12;
428    static final int SCAN_CHECK_ONLY = 1<<13;
429    static final int SCAN_DONT_KILL_APP = 1<<14;
430    static final int SCAN_IGNORE_FROZEN = 1<<15;
431    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
432    static final int SCAN_AS_INSTANT_APP = 1<<17;
433    static final int SCAN_AS_FULL_APP = 1<<18;
434    /** Should not be with the scan flags */
435    static final int FLAGS_REMOVE_CHATTY = 1<<31;
436
437    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
438
439    private static final int[] EMPTY_INT_ARRAY = new int[0];
440
441    /**
442     * Timeout (in milliseconds) after which the watchdog should declare that
443     * our handler thread is wedged.  The usual default for such things is one
444     * minute but we sometimes do very lengthy I/O operations on this thread,
445     * such as installing multi-gigabyte applications, so ours needs to be longer.
446     */
447    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
448
449    /**
450     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
451     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
452     * settings entry if available, otherwise we use the hardcoded default.  If it's been
453     * more than this long since the last fstrim, we force one during the boot sequence.
454     *
455     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
456     * one gets run at the next available charging+idle time.  This final mandatory
457     * no-fstrim check kicks in only of the other scheduling criteria is never met.
458     */
459    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
460
461    /**
462     * Whether verification is enabled by default.
463     */
464    private static final boolean DEFAULT_VERIFY_ENABLE = true;
465
466    /**
467     * The default maximum time to wait for the verification agent to return in
468     * milliseconds.
469     */
470    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
471
472    /**
473     * The default response for package verification timeout.
474     *
475     * This can be either PackageManager.VERIFICATION_ALLOW or
476     * PackageManager.VERIFICATION_REJECT.
477     */
478    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
479
480    static final String PLATFORM_PACKAGE_NAME = "android";
481
482    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
483
484    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
485            DEFAULT_CONTAINER_PACKAGE,
486            "com.android.defcontainer.DefaultContainerService");
487
488    private static final String KILL_APP_REASON_GIDS_CHANGED =
489            "permission grant or revoke changed gids";
490
491    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
492            "permissions revoked";
493
494    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
495
496    private static final String PACKAGE_SCHEME = "package";
497
498    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
499
500    /** Permission grant: not grant the permission. */
501    private static final int GRANT_DENIED = 1;
502
503    /** Permission grant: grant the permission as an install permission. */
504    private static final int GRANT_INSTALL = 2;
505
506    /** Permission grant: grant the permission as a runtime one. */
507    private static final int GRANT_RUNTIME = 3;
508
509    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
510    private static final int GRANT_UPGRADE = 4;
511
512    /** Canonical intent used to identify what counts as a "web browser" app */
513    private static final Intent sBrowserIntent;
514    static {
515        sBrowserIntent = new Intent();
516        sBrowserIntent.setAction(Intent.ACTION_VIEW);
517        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
518        sBrowserIntent.setData(Uri.parse("http:"));
519    }
520
521    /**
522     * The set of all protected actions [i.e. those actions for which a high priority
523     * intent filter is disallowed].
524     */
525    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
526    static {
527        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
528        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
530        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
531    }
532
533    // Compilation reasons.
534    public static final int REASON_FIRST_BOOT = 0;
535    public static final int REASON_BOOT = 1;
536    public static final int REASON_INSTALL = 2;
537    public static final int REASON_BACKGROUND_DEXOPT = 3;
538    public static final int REASON_AB_OTA = 4;
539    public static final int REASON_FORCED_DEXOPT = 5;
540
541    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
542
543    /** All dangerous permission names in the same order as the events in MetricsEvent */
544    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
545            Manifest.permission.READ_CALENDAR,
546            Manifest.permission.WRITE_CALENDAR,
547            Manifest.permission.CAMERA,
548            Manifest.permission.READ_CONTACTS,
549            Manifest.permission.WRITE_CONTACTS,
550            Manifest.permission.GET_ACCOUNTS,
551            Manifest.permission.ACCESS_FINE_LOCATION,
552            Manifest.permission.ACCESS_COARSE_LOCATION,
553            Manifest.permission.RECORD_AUDIO,
554            Manifest.permission.READ_PHONE_STATE,
555            Manifest.permission.CALL_PHONE,
556            Manifest.permission.READ_CALL_LOG,
557            Manifest.permission.WRITE_CALL_LOG,
558            Manifest.permission.ADD_VOICEMAIL,
559            Manifest.permission.USE_SIP,
560            Manifest.permission.PROCESS_OUTGOING_CALLS,
561            Manifest.permission.READ_CELL_BROADCASTS,
562            Manifest.permission.BODY_SENSORS,
563            Manifest.permission.SEND_SMS,
564            Manifest.permission.RECEIVE_SMS,
565            Manifest.permission.READ_SMS,
566            Manifest.permission.RECEIVE_WAP_PUSH,
567            Manifest.permission.RECEIVE_MMS,
568            Manifest.permission.READ_EXTERNAL_STORAGE,
569            Manifest.permission.WRITE_EXTERNAL_STORAGE,
570            Manifest.permission.READ_PHONE_NUMBERS,
571            Manifest.permission.ANSWER_PHONE_CALLS);
572
573
574    /**
575     * Version number for the package parser cache. Increment this whenever the format or
576     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
577     */
578    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
579
580    /**
581     * Whether the package parser cache is enabled.
582     */
583    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
584
585    final ServiceThread mHandlerThread;
586
587    final PackageHandler mHandler;
588
589    private final ProcessLoggingHandler mProcessLoggingHandler;
590
591    /**
592     * Messages for {@link #mHandler} that need to wait for system ready before
593     * being dispatched.
594     */
595    private ArrayList<Message> mPostSystemReadyMessages;
596
597    final int mSdkVersion = Build.VERSION.SDK_INT;
598
599    final Context mContext;
600    final boolean mFactoryTest;
601    final boolean mOnlyCore;
602    final DisplayMetrics mMetrics;
603    final int mDefParseFlags;
604    final String[] mSeparateProcesses;
605    final boolean mIsUpgrade;
606    final boolean mIsPreNUpgrade;
607    final boolean mIsPreNMR1Upgrade;
608
609    // Have we told the Activity Manager to whitelist the default container service by uid yet?
610    @GuardedBy("mPackages")
611    boolean mDefaultContainerWhitelisted = false;
612
613    @GuardedBy("mPackages")
614    private boolean mDexOptDialogShown;
615
616    /** The location for ASEC container files on internal storage. */
617    final String mAsecInternalPath;
618
619    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
620    // LOCK HELD.  Can be called with mInstallLock held.
621    @GuardedBy("mInstallLock")
622    final Installer mInstaller;
623
624    /** Directory where installed third-party apps stored */
625    final File mAppInstallDir;
626
627    /**
628     * Directory to which applications installed internally have their
629     * 32 bit native libraries copied.
630     */
631    private File mAppLib32InstallDir;
632
633    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
634    // apps.
635    final File mDrmAppPrivateInstallDir;
636
637    // ----------------------------------------------------------------
638
639    // Lock for state used when installing and doing other long running
640    // operations.  Methods that must be called with this lock held have
641    // the suffix "LI".
642    final Object mInstallLock = new Object();
643
644    // ----------------------------------------------------------------
645
646    // Keys are String (package name), values are Package.  This also serves
647    // as the lock for the global state.  Methods that must be called with
648    // this lock held have the prefix "LP".
649    @GuardedBy("mPackages")
650    final ArrayMap<String, PackageParser.Package> mPackages =
651            new ArrayMap<String, PackageParser.Package>();
652
653    final ArrayMap<String, Set<String>> mKnownCodebase =
654            new ArrayMap<String, Set<String>>();
655
656    // Keys are isolated uids and values are the uid of the application
657    // that created the isolated proccess.
658    @GuardedBy("mPackages")
659    final SparseIntArray mIsolatedOwners = new SparseIntArray();
660
661    // List of APK paths to load for each user and package. This data is never
662    // persisted by the package manager. Instead, the overlay manager will
663    // ensure the data is up-to-date in runtime.
664    @GuardedBy("mPackages")
665    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
666        new SparseArray<ArrayMap<String, ArrayList<String>>>();
667
668    /**
669     * Tracks new system packages [received in an OTA] that we expect to
670     * find updated user-installed versions. Keys are package name, values
671     * are package location.
672     */
673    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
674    /**
675     * Tracks high priority intent filters for protected actions. During boot, certain
676     * filter actions are protected and should never be allowed to have a high priority
677     * intent filter for them. However, there is one, and only one exception -- the
678     * setup wizard. It must be able to define a high priority intent filter for these
679     * actions to ensure there are no escapes from the wizard. We need to delay processing
680     * of these during boot as we need to look at all of the system packages in order
681     * to know which component is the setup wizard.
682     */
683    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
684    /**
685     * Whether or not processing protected filters should be deferred.
686     */
687    private boolean mDeferProtectedFilters = true;
688
689    /**
690     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
691     */
692    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
693    /**
694     * Whether or not system app permissions should be promoted from install to runtime.
695     */
696    boolean mPromoteSystemApps;
697
698    @GuardedBy("mPackages")
699    final Settings mSettings;
700
701    /**
702     * Set of package names that are currently "frozen", which means active
703     * surgery is being done on the code/data for that package. The platform
704     * will refuse to launch frozen packages to avoid race conditions.
705     *
706     * @see PackageFreezer
707     */
708    @GuardedBy("mPackages")
709    final ArraySet<String> mFrozenPackages = new ArraySet<>();
710
711    final ProtectedPackages mProtectedPackages;
712
713    boolean mFirstBoot;
714
715    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
716
717    // System configuration read by SystemConfig.
718    final int[] mGlobalGids;
719    final SparseArray<ArraySet<String>> mSystemPermissions;
720    @GuardedBy("mAvailableFeatures")
721    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
722
723    // If mac_permissions.xml was found for seinfo labeling.
724    boolean mFoundPolicyFile;
725
726    private final InstantAppRegistry mInstantAppRegistry;
727
728    @GuardedBy("mPackages")
729    int mChangedPackagesSequenceNumber;
730    /**
731     * List of changed [installed, removed or updated] packages.
732     * mapping from user id -> sequence number -> package name
733     */
734    @GuardedBy("mPackages")
735    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
736    /**
737     * The sequence number of the last change to a package.
738     * mapping from user id -> package name -> sequence number
739     */
740    @GuardedBy("mPackages")
741    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
742
743    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
744        @Override public boolean hasFeature(String feature) {
745            return PackageManagerService.this.hasSystemFeature(feature, 0);
746        }
747    };
748
749    public static final class SharedLibraryEntry {
750        public final String path;
751        public final String apk;
752        public final SharedLibraryInfo info;
753
754        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
755                String declaringPackageName, int declaringPackageVersionCode) {
756            path = _path;
757            apk = _apk;
758            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
759                    declaringPackageName, declaringPackageVersionCode), null);
760        }
761    }
762
763    // Currently known shared libraries.
764    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
765    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
766            new ArrayMap<>();
767
768    // All available activities, for your resolving pleasure.
769    final ActivityIntentResolver mActivities =
770            new ActivityIntentResolver();
771
772    // All available receivers, for your resolving pleasure.
773    final ActivityIntentResolver mReceivers =
774            new ActivityIntentResolver();
775
776    // All available services, for your resolving pleasure.
777    final ServiceIntentResolver mServices = new ServiceIntentResolver();
778
779    // All available providers, for your resolving pleasure.
780    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
781
782    // Mapping from provider base names (first directory in content URI codePath)
783    // to the provider information.
784    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
785            new ArrayMap<String, PackageParser.Provider>();
786
787    // Mapping from instrumentation class names to info about them.
788    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
789            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
790
791    // Mapping from permission names to info about them.
792    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
793            new ArrayMap<String, PackageParser.PermissionGroup>();
794
795    // Packages whose data we have transfered into another package, thus
796    // should no longer exist.
797    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
798
799    // Broadcast actions that are only available to the system.
800    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
801
802    /** List of packages waiting for verification. */
803    final SparseArray<PackageVerificationState> mPendingVerification
804            = new SparseArray<PackageVerificationState>();
805
806    /** Set of packages associated with each app op permission. */
807    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
808
809    final PackageInstallerService mInstallerService;
810
811    private final PackageDexOptimizer mPackageDexOptimizer;
812    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
813    // is used by other apps).
814    private final DexManager mDexManager;
815
816    private AtomicInteger mNextMoveId = new AtomicInteger();
817    private final MoveCallbacks mMoveCallbacks;
818
819    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
820
821    // Cache of users who need badging.
822    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
823
824    /** Token for keys in mPendingVerification. */
825    private int mPendingVerificationToken = 0;
826
827    volatile boolean mSystemReady;
828    volatile boolean mSafeMode;
829    volatile boolean mHasSystemUidErrors;
830    private volatile boolean mEphemeralAppsDisabled;
831
832    ApplicationInfo mAndroidApplication;
833    final ActivityInfo mResolveActivity = new ActivityInfo();
834    final ResolveInfo mResolveInfo = new ResolveInfo();
835    ComponentName mResolveComponentName;
836    PackageParser.Package mPlatformPackage;
837    ComponentName mCustomResolverComponentName;
838
839    boolean mResolverReplaced = false;
840
841    private final @Nullable ComponentName mIntentFilterVerifierComponent;
842    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
843
844    private int mIntentFilterVerificationToken = 0;
845
846    /** The service connection to the ephemeral resolver */
847    final EphemeralResolverConnection mInstantAppResolverConnection;
848    /** Component used to show resolver settings for Instant Apps */
849    final ComponentName mInstantAppResolverSettingsComponent;
850
851    /** Activity used to install instant applications */
852    ActivityInfo mInstantAppInstallerActivity;
853    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
854
855    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
856            = new SparseArray<IntentFilterVerificationState>();
857
858    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
859
860    // List of packages names to keep cached, even if they are uninstalled for all users
861    private List<String> mKeepUninstalledPackages;
862
863    private UserManagerInternal mUserManagerInternal;
864
865    private DeviceIdleController.LocalService mDeviceIdleController;
866
867    private File mCacheDir;
868
869    private ArraySet<String> mPrivappPermissionsViolations;
870
871    private Future<?> mPrepareAppDataFuture;
872
873    private static class IFVerificationParams {
874        PackageParser.Package pkg;
875        boolean replacing;
876        int userId;
877        int verifierUid;
878
879        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
880                int _userId, int _verifierUid) {
881            pkg = _pkg;
882            replacing = _replacing;
883            userId = _userId;
884            replacing = _replacing;
885            verifierUid = _verifierUid;
886        }
887    }
888
889    private interface IntentFilterVerifier<T extends IntentFilter> {
890        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
891                                               T filter, String packageName);
892        void startVerifications(int userId);
893        void receiveVerificationResponse(int verificationId);
894    }
895
896    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
897        private Context mContext;
898        private ComponentName mIntentFilterVerifierComponent;
899        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
900
901        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
902            mContext = context;
903            mIntentFilterVerifierComponent = verifierComponent;
904        }
905
906        private String getDefaultScheme() {
907            return IntentFilter.SCHEME_HTTPS;
908        }
909
910        @Override
911        public void startVerifications(int userId) {
912            // Launch verifications requests
913            int count = mCurrentIntentFilterVerifications.size();
914            for (int n=0; n<count; n++) {
915                int verificationId = mCurrentIntentFilterVerifications.get(n);
916                final IntentFilterVerificationState ivs =
917                        mIntentFilterVerificationStates.get(verificationId);
918
919                String packageName = ivs.getPackageName();
920
921                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
922                final int filterCount = filters.size();
923                ArraySet<String> domainsSet = new ArraySet<>();
924                for (int m=0; m<filterCount; m++) {
925                    PackageParser.ActivityIntentInfo filter = filters.get(m);
926                    domainsSet.addAll(filter.getHostsList());
927                }
928                synchronized (mPackages) {
929                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
930                            packageName, domainsSet) != null) {
931                        scheduleWriteSettingsLocked();
932                    }
933                }
934                sendVerificationRequest(userId, verificationId, ivs);
935            }
936            mCurrentIntentFilterVerifications.clear();
937        }
938
939        private void sendVerificationRequest(int userId, int verificationId,
940                IntentFilterVerificationState ivs) {
941
942            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
943            verificationIntent.putExtra(
944                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
945                    verificationId);
946            verificationIntent.putExtra(
947                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
948                    getDefaultScheme());
949            verificationIntent.putExtra(
950                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
951                    ivs.getHostsString());
952            verificationIntent.putExtra(
953                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
954                    ivs.getPackageName());
955            verificationIntent.setComponent(mIntentFilterVerifierComponent);
956            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
957
958            UserHandle user = new UserHandle(userId);
959            mContext.sendBroadcastAsUser(verificationIntent, user);
960            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
961                    "Sending IntentFilter verification broadcast");
962        }
963
964        public void receiveVerificationResponse(int verificationId) {
965            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
966
967            final boolean verified = ivs.isVerified();
968
969            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
970            final int count = filters.size();
971            if (DEBUG_DOMAIN_VERIFICATION) {
972                Slog.i(TAG, "Received verification response " + verificationId
973                        + " for " + count + " filters, verified=" + verified);
974            }
975            for (int n=0; n<count; n++) {
976                PackageParser.ActivityIntentInfo filter = filters.get(n);
977                filter.setVerified(verified);
978
979                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
980                        + " verified with result:" + verified + " and hosts:"
981                        + ivs.getHostsString());
982            }
983
984            mIntentFilterVerificationStates.remove(verificationId);
985
986            final String packageName = ivs.getPackageName();
987            IntentFilterVerificationInfo ivi = null;
988
989            synchronized (mPackages) {
990                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
991            }
992            if (ivi == null) {
993                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
994                        + verificationId + " packageName:" + packageName);
995                return;
996            }
997            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
998                    "Updating IntentFilterVerificationInfo for package " + packageName
999                            +" verificationId:" + verificationId);
1000
1001            synchronized (mPackages) {
1002                if (verified) {
1003                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1004                } else {
1005                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1006                }
1007                scheduleWriteSettingsLocked();
1008
1009                final int userId = ivs.getUserId();
1010                if (userId != UserHandle.USER_ALL) {
1011                    final int userStatus =
1012                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1013
1014                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1015                    boolean needUpdate = false;
1016
1017                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1018                    // already been set by the User thru the Disambiguation dialog
1019                    switch (userStatus) {
1020                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1021                            if (verified) {
1022                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1023                            } else {
1024                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1025                            }
1026                            needUpdate = true;
1027                            break;
1028
1029                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1030                            if (verified) {
1031                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1032                                needUpdate = true;
1033                            }
1034                            break;
1035
1036                        default:
1037                            // Nothing to do
1038                    }
1039
1040                    if (needUpdate) {
1041                        mSettings.updateIntentFilterVerificationStatusLPw(
1042                                packageName, updatedStatus, userId);
1043                        scheduleWritePackageRestrictionsLocked(userId);
1044                    }
1045                }
1046            }
1047        }
1048
1049        @Override
1050        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1051                    ActivityIntentInfo filter, String packageName) {
1052            if (!hasValidDomains(filter)) {
1053                return false;
1054            }
1055            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1056            if (ivs == null) {
1057                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1058                        packageName);
1059            }
1060            if (DEBUG_DOMAIN_VERIFICATION) {
1061                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1062            }
1063            ivs.addFilter(filter);
1064            return true;
1065        }
1066
1067        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1068                int userId, int verificationId, String packageName) {
1069            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1070                    verifierUid, userId, packageName);
1071            ivs.setPendingState();
1072            synchronized (mPackages) {
1073                mIntentFilterVerificationStates.append(verificationId, ivs);
1074                mCurrentIntentFilterVerifications.add(verificationId);
1075            }
1076            return ivs;
1077        }
1078    }
1079
1080    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1081        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1082                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1083                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1084    }
1085
1086    // Set of pending broadcasts for aggregating enable/disable of components.
1087    static class PendingPackageBroadcasts {
1088        // for each user id, a map of <package name -> components within that package>
1089        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1090
1091        public PendingPackageBroadcasts() {
1092            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1093        }
1094
1095        public ArrayList<String> get(int userId, String packageName) {
1096            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1097            return packages.get(packageName);
1098        }
1099
1100        public void put(int userId, String packageName, ArrayList<String> components) {
1101            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1102            packages.put(packageName, components);
1103        }
1104
1105        public void remove(int userId, String packageName) {
1106            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1107            if (packages != null) {
1108                packages.remove(packageName);
1109            }
1110        }
1111
1112        public void remove(int userId) {
1113            mUidMap.remove(userId);
1114        }
1115
1116        public int userIdCount() {
1117            return mUidMap.size();
1118        }
1119
1120        public int userIdAt(int n) {
1121            return mUidMap.keyAt(n);
1122        }
1123
1124        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1125            return mUidMap.get(userId);
1126        }
1127
1128        public int size() {
1129            // total number of pending broadcast entries across all userIds
1130            int num = 0;
1131            for (int i = 0; i< mUidMap.size(); i++) {
1132                num += mUidMap.valueAt(i).size();
1133            }
1134            return num;
1135        }
1136
1137        public void clear() {
1138            mUidMap.clear();
1139        }
1140
1141        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1142            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1143            if (map == null) {
1144                map = new ArrayMap<String, ArrayList<String>>();
1145                mUidMap.put(userId, map);
1146            }
1147            return map;
1148        }
1149    }
1150    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1151
1152    // Service Connection to remote media container service to copy
1153    // package uri's from external media onto secure containers
1154    // or internal storage.
1155    private IMediaContainerService mContainerService = null;
1156
1157    static final int SEND_PENDING_BROADCAST = 1;
1158    static final int MCS_BOUND = 3;
1159    static final int END_COPY = 4;
1160    static final int INIT_COPY = 5;
1161    static final int MCS_UNBIND = 6;
1162    static final int START_CLEANING_PACKAGE = 7;
1163    static final int FIND_INSTALL_LOC = 8;
1164    static final int POST_INSTALL = 9;
1165    static final int MCS_RECONNECT = 10;
1166    static final int MCS_GIVE_UP = 11;
1167    static final int UPDATED_MEDIA_STATUS = 12;
1168    static final int WRITE_SETTINGS = 13;
1169    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1170    static final int PACKAGE_VERIFIED = 15;
1171    static final int CHECK_PENDING_VERIFICATION = 16;
1172    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1173    static final int INTENT_FILTER_VERIFIED = 18;
1174    static final int WRITE_PACKAGE_LIST = 19;
1175    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1176
1177    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1178
1179    // Delay time in millisecs
1180    static final int BROADCAST_DELAY = 10 * 1000;
1181
1182    static UserManagerService sUserManager;
1183
1184    // Stores a list of users whose package restrictions file needs to be updated
1185    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1186
1187    final private DefaultContainerConnection mDefContainerConn =
1188            new DefaultContainerConnection();
1189    class DefaultContainerConnection implements ServiceConnection {
1190        public void onServiceConnected(ComponentName name, IBinder service) {
1191            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1192            final IMediaContainerService imcs = IMediaContainerService.Stub
1193                    .asInterface(Binder.allowBlocking(service));
1194            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1195        }
1196
1197        public void onServiceDisconnected(ComponentName name) {
1198            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1199        }
1200    }
1201
1202    // Recordkeeping of restore-after-install operations that are currently in flight
1203    // between the Package Manager and the Backup Manager
1204    static class PostInstallData {
1205        public InstallArgs args;
1206        public PackageInstalledInfo res;
1207
1208        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1209            args = _a;
1210            res = _r;
1211        }
1212    }
1213
1214    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1215    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1216
1217    // XML tags for backup/restore of various bits of state
1218    private static final String TAG_PREFERRED_BACKUP = "pa";
1219    private static final String TAG_DEFAULT_APPS = "da";
1220    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1221
1222    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1223    private static final String TAG_ALL_GRANTS = "rt-grants";
1224    private static final String TAG_GRANT = "grant";
1225    private static final String ATTR_PACKAGE_NAME = "pkg";
1226
1227    private static final String TAG_PERMISSION = "perm";
1228    private static final String ATTR_PERMISSION_NAME = "name";
1229    private static final String ATTR_IS_GRANTED = "g";
1230    private static final String ATTR_USER_SET = "set";
1231    private static final String ATTR_USER_FIXED = "fixed";
1232    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1233
1234    // System/policy permission grants are not backed up
1235    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1236            FLAG_PERMISSION_POLICY_FIXED
1237            | FLAG_PERMISSION_SYSTEM_FIXED
1238            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1239
1240    // And we back up these user-adjusted states
1241    private static final int USER_RUNTIME_GRANT_MASK =
1242            FLAG_PERMISSION_USER_SET
1243            | FLAG_PERMISSION_USER_FIXED
1244            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1245
1246    final @Nullable String mRequiredVerifierPackage;
1247    final @NonNull String mRequiredInstallerPackage;
1248    final @NonNull String mRequiredUninstallerPackage;
1249    final @Nullable String mSetupWizardPackage;
1250    final @Nullable String mStorageManagerPackage;
1251    final @NonNull String mServicesSystemSharedLibraryPackageName;
1252    final @NonNull String mSharedSystemSharedLibraryPackageName;
1253
1254    final boolean mPermissionReviewRequired;
1255
1256    private final PackageUsage mPackageUsage = new PackageUsage();
1257    private final CompilerStats mCompilerStats = new CompilerStats();
1258
1259    class PackageHandler extends Handler {
1260        private boolean mBound = false;
1261        final ArrayList<HandlerParams> mPendingInstalls =
1262            new ArrayList<HandlerParams>();
1263
1264        private boolean connectToService() {
1265            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1266                    " DefaultContainerService");
1267            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1268            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1269            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1270                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1271                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1272                mBound = true;
1273                return true;
1274            }
1275            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1276            return false;
1277        }
1278
1279        private void disconnectService() {
1280            mContainerService = null;
1281            mBound = false;
1282            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1283            mContext.unbindService(mDefContainerConn);
1284            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1285        }
1286
1287        PackageHandler(Looper looper) {
1288            super(looper);
1289        }
1290
1291        public void handleMessage(Message msg) {
1292            try {
1293                doHandleMessage(msg);
1294            } finally {
1295                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1296            }
1297        }
1298
1299        void doHandleMessage(Message msg) {
1300            switch (msg.what) {
1301                case INIT_COPY: {
1302                    HandlerParams params = (HandlerParams) msg.obj;
1303                    int idx = mPendingInstalls.size();
1304                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1305                    // If a bind was already initiated we dont really
1306                    // need to do anything. The pending install
1307                    // will be processed later on.
1308                    if (!mBound) {
1309                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1310                                System.identityHashCode(mHandler));
1311                        // If this is the only one pending we might
1312                        // have to bind to the service again.
1313                        if (!connectToService()) {
1314                            Slog.e(TAG, "Failed to bind to media container service");
1315                            params.serviceError();
1316                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1317                                    System.identityHashCode(mHandler));
1318                            if (params.traceMethod != null) {
1319                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1320                                        params.traceCookie);
1321                            }
1322                            return;
1323                        } else {
1324                            // Once we bind to the service, the first
1325                            // pending request will be processed.
1326                            mPendingInstalls.add(idx, params);
1327                        }
1328                    } else {
1329                        mPendingInstalls.add(idx, params);
1330                        // Already bound to the service. Just make
1331                        // sure we trigger off processing the first request.
1332                        if (idx == 0) {
1333                            mHandler.sendEmptyMessage(MCS_BOUND);
1334                        }
1335                    }
1336                    break;
1337                }
1338                case MCS_BOUND: {
1339                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1340                    if (msg.obj != null) {
1341                        mContainerService = (IMediaContainerService) msg.obj;
1342                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1343                                System.identityHashCode(mHandler));
1344                    }
1345                    if (mContainerService == null) {
1346                        if (!mBound) {
1347                            // Something seriously wrong since we are not bound and we are not
1348                            // waiting for connection. Bail out.
1349                            Slog.e(TAG, "Cannot bind to media container service");
1350                            for (HandlerParams params : mPendingInstalls) {
1351                                // Indicate service bind error
1352                                params.serviceError();
1353                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1354                                        System.identityHashCode(params));
1355                                if (params.traceMethod != null) {
1356                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1357                                            params.traceMethod, params.traceCookie);
1358                                }
1359                                return;
1360                            }
1361                            mPendingInstalls.clear();
1362                        } else {
1363                            Slog.w(TAG, "Waiting to connect to media container service");
1364                        }
1365                    } else if (mPendingInstalls.size() > 0) {
1366                        HandlerParams params = mPendingInstalls.get(0);
1367                        if (params != null) {
1368                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1369                                    System.identityHashCode(params));
1370                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1371                            if (params.startCopy()) {
1372                                // We are done...  look for more work or to
1373                                // go idle.
1374                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1375                                        "Checking for more work or unbind...");
1376                                // Delete pending install
1377                                if (mPendingInstalls.size() > 0) {
1378                                    mPendingInstalls.remove(0);
1379                                }
1380                                if (mPendingInstalls.size() == 0) {
1381                                    if (mBound) {
1382                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1383                                                "Posting delayed MCS_UNBIND");
1384                                        removeMessages(MCS_UNBIND);
1385                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1386                                        // Unbind after a little delay, to avoid
1387                                        // continual thrashing.
1388                                        sendMessageDelayed(ubmsg, 10000);
1389                                    }
1390                                } else {
1391                                    // There are more pending requests in queue.
1392                                    // Just post MCS_BOUND message to trigger processing
1393                                    // of next pending install.
1394                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1395                                            "Posting MCS_BOUND for next work");
1396                                    mHandler.sendEmptyMessage(MCS_BOUND);
1397                                }
1398                            }
1399                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1400                        }
1401                    } else {
1402                        // Should never happen ideally.
1403                        Slog.w(TAG, "Empty queue");
1404                    }
1405                    break;
1406                }
1407                case MCS_RECONNECT: {
1408                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1409                    if (mPendingInstalls.size() > 0) {
1410                        if (mBound) {
1411                            disconnectService();
1412                        }
1413                        if (!connectToService()) {
1414                            Slog.e(TAG, "Failed to bind to media container service");
1415                            for (HandlerParams params : mPendingInstalls) {
1416                                // Indicate service bind error
1417                                params.serviceError();
1418                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1419                                        System.identityHashCode(params));
1420                            }
1421                            mPendingInstalls.clear();
1422                        }
1423                    }
1424                    break;
1425                }
1426                case MCS_UNBIND: {
1427                    // If there is no actual work left, then time to unbind.
1428                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1429
1430                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1431                        if (mBound) {
1432                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1433
1434                            disconnectService();
1435                        }
1436                    } else if (mPendingInstalls.size() > 0) {
1437                        // There are more pending requests in queue.
1438                        // Just post MCS_BOUND message to trigger processing
1439                        // of next pending install.
1440                        mHandler.sendEmptyMessage(MCS_BOUND);
1441                    }
1442
1443                    break;
1444                }
1445                case MCS_GIVE_UP: {
1446                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1447                    HandlerParams params = mPendingInstalls.remove(0);
1448                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1449                            System.identityHashCode(params));
1450                    break;
1451                }
1452                case SEND_PENDING_BROADCAST: {
1453                    String packages[];
1454                    ArrayList<String> components[];
1455                    int size = 0;
1456                    int uids[];
1457                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1458                    synchronized (mPackages) {
1459                        if (mPendingBroadcasts == null) {
1460                            return;
1461                        }
1462                        size = mPendingBroadcasts.size();
1463                        if (size <= 0) {
1464                            // Nothing to be done. Just return
1465                            return;
1466                        }
1467                        packages = new String[size];
1468                        components = new ArrayList[size];
1469                        uids = new int[size];
1470                        int i = 0;  // filling out the above arrays
1471
1472                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1473                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1474                            Iterator<Map.Entry<String, ArrayList<String>>> it
1475                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1476                                            .entrySet().iterator();
1477                            while (it.hasNext() && i < size) {
1478                                Map.Entry<String, ArrayList<String>> ent = it.next();
1479                                packages[i] = ent.getKey();
1480                                components[i] = ent.getValue();
1481                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1482                                uids[i] = (ps != null)
1483                                        ? UserHandle.getUid(packageUserId, ps.appId)
1484                                        : -1;
1485                                i++;
1486                            }
1487                        }
1488                        size = i;
1489                        mPendingBroadcasts.clear();
1490                    }
1491                    // Send broadcasts
1492                    for (int i = 0; i < size; i++) {
1493                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1494                    }
1495                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1496                    break;
1497                }
1498                case START_CLEANING_PACKAGE: {
1499                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1500                    final String packageName = (String)msg.obj;
1501                    final int userId = msg.arg1;
1502                    final boolean andCode = msg.arg2 != 0;
1503                    synchronized (mPackages) {
1504                        if (userId == UserHandle.USER_ALL) {
1505                            int[] users = sUserManager.getUserIds();
1506                            for (int user : users) {
1507                                mSettings.addPackageToCleanLPw(
1508                                        new PackageCleanItem(user, packageName, andCode));
1509                            }
1510                        } else {
1511                            mSettings.addPackageToCleanLPw(
1512                                    new PackageCleanItem(userId, packageName, andCode));
1513                        }
1514                    }
1515                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1516                    startCleaningPackages();
1517                } break;
1518                case POST_INSTALL: {
1519                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1520
1521                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1522                    final boolean didRestore = (msg.arg2 != 0);
1523                    mRunningInstalls.delete(msg.arg1);
1524
1525                    if (data != null) {
1526                        InstallArgs args = data.args;
1527                        PackageInstalledInfo parentRes = data.res;
1528
1529                        final boolean grantPermissions = (args.installFlags
1530                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1531                        final boolean killApp = (args.installFlags
1532                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1533                        final String[] grantedPermissions = args.installGrantPermissions;
1534
1535                        // Handle the parent package
1536                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1537                                grantedPermissions, didRestore, args.installerPackageName,
1538                                args.observer);
1539
1540                        // Handle the child packages
1541                        final int childCount = (parentRes.addedChildPackages != null)
1542                                ? parentRes.addedChildPackages.size() : 0;
1543                        for (int i = 0; i < childCount; i++) {
1544                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1545                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1546                                    grantedPermissions, false, args.installerPackageName,
1547                                    args.observer);
1548                        }
1549
1550                        // Log tracing if needed
1551                        if (args.traceMethod != null) {
1552                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1553                                    args.traceCookie);
1554                        }
1555                    } else {
1556                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1557                    }
1558
1559                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1560                } break;
1561                case UPDATED_MEDIA_STATUS: {
1562                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1563                    boolean reportStatus = msg.arg1 == 1;
1564                    boolean doGc = msg.arg2 == 1;
1565                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1566                    if (doGc) {
1567                        // Force a gc to clear up stale containers.
1568                        Runtime.getRuntime().gc();
1569                    }
1570                    if (msg.obj != null) {
1571                        @SuppressWarnings("unchecked")
1572                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1573                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1574                        // Unload containers
1575                        unloadAllContainers(args);
1576                    }
1577                    if (reportStatus) {
1578                        try {
1579                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1580                                    "Invoking StorageManagerService call back");
1581                            PackageHelper.getStorageManager().finishMediaUpdate();
1582                        } catch (RemoteException e) {
1583                            Log.e(TAG, "StorageManagerService not running?");
1584                        }
1585                    }
1586                } break;
1587                case WRITE_SETTINGS: {
1588                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1589                    synchronized (mPackages) {
1590                        removeMessages(WRITE_SETTINGS);
1591                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1592                        mSettings.writeLPr();
1593                        mDirtyUsers.clear();
1594                    }
1595                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1596                } break;
1597                case WRITE_PACKAGE_RESTRICTIONS: {
1598                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1599                    synchronized (mPackages) {
1600                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1601                        for (int userId : mDirtyUsers) {
1602                            mSettings.writePackageRestrictionsLPr(userId);
1603                        }
1604                        mDirtyUsers.clear();
1605                    }
1606                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1607                } break;
1608                case WRITE_PACKAGE_LIST: {
1609                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1610                    synchronized (mPackages) {
1611                        removeMessages(WRITE_PACKAGE_LIST);
1612                        mSettings.writePackageListLPr(msg.arg1);
1613                    }
1614                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1615                } break;
1616                case CHECK_PENDING_VERIFICATION: {
1617                    final int verificationId = msg.arg1;
1618                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1619
1620                    if ((state != null) && !state.timeoutExtended()) {
1621                        final InstallArgs args = state.getInstallArgs();
1622                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1623
1624                        Slog.i(TAG, "Verification timed out for " + originUri);
1625                        mPendingVerification.remove(verificationId);
1626
1627                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1628
1629                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1630                            Slog.i(TAG, "Continuing with installation of " + originUri);
1631                            state.setVerifierResponse(Binder.getCallingUid(),
1632                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1633                            broadcastPackageVerified(verificationId, originUri,
1634                                    PackageManager.VERIFICATION_ALLOW,
1635                                    state.getInstallArgs().getUser());
1636                            try {
1637                                ret = args.copyApk(mContainerService, true);
1638                            } catch (RemoteException e) {
1639                                Slog.e(TAG, "Could not contact the ContainerService");
1640                            }
1641                        } else {
1642                            broadcastPackageVerified(verificationId, originUri,
1643                                    PackageManager.VERIFICATION_REJECT,
1644                                    state.getInstallArgs().getUser());
1645                        }
1646
1647                        Trace.asyncTraceEnd(
1648                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1649
1650                        processPendingInstall(args, ret);
1651                        mHandler.sendEmptyMessage(MCS_UNBIND);
1652                    }
1653                    break;
1654                }
1655                case PACKAGE_VERIFIED: {
1656                    final int verificationId = msg.arg1;
1657
1658                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1659                    if (state == null) {
1660                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1661                        break;
1662                    }
1663
1664                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1665
1666                    state.setVerifierResponse(response.callerUid, response.code);
1667
1668                    if (state.isVerificationComplete()) {
1669                        mPendingVerification.remove(verificationId);
1670
1671                        final InstallArgs args = state.getInstallArgs();
1672                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1673
1674                        int ret;
1675                        if (state.isInstallAllowed()) {
1676                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1677                            broadcastPackageVerified(verificationId, originUri,
1678                                    response.code, state.getInstallArgs().getUser());
1679                            try {
1680                                ret = args.copyApk(mContainerService, true);
1681                            } catch (RemoteException e) {
1682                                Slog.e(TAG, "Could not contact the ContainerService");
1683                            }
1684                        } else {
1685                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1686                        }
1687
1688                        Trace.asyncTraceEnd(
1689                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1690
1691                        processPendingInstall(args, ret);
1692                        mHandler.sendEmptyMessage(MCS_UNBIND);
1693                    }
1694
1695                    break;
1696                }
1697                case START_INTENT_FILTER_VERIFICATIONS: {
1698                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1699                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1700                            params.replacing, params.pkg);
1701                    break;
1702                }
1703                case INTENT_FILTER_VERIFIED: {
1704                    final int verificationId = msg.arg1;
1705
1706                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1707                            verificationId);
1708                    if (state == null) {
1709                        Slog.w(TAG, "Invalid IntentFilter verification token "
1710                                + verificationId + " received");
1711                        break;
1712                    }
1713
1714                    final int userId = state.getUserId();
1715
1716                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1717                            "Processing IntentFilter verification with token:"
1718                            + verificationId + " and userId:" + userId);
1719
1720                    final IntentFilterVerificationResponse response =
1721                            (IntentFilterVerificationResponse) msg.obj;
1722
1723                    state.setVerifierResponse(response.callerUid, response.code);
1724
1725                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1726                            "IntentFilter verification with token:" + verificationId
1727                            + " and userId:" + userId
1728                            + " is settings verifier response with response code:"
1729                            + response.code);
1730
1731                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1732                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1733                                + response.getFailedDomainsString());
1734                    }
1735
1736                    if (state.isVerificationComplete()) {
1737                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1738                    } else {
1739                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1740                                "IntentFilter verification with token:" + verificationId
1741                                + " was not said to be complete");
1742                    }
1743
1744                    break;
1745                }
1746                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1747                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1748                            mInstantAppResolverConnection,
1749                            (InstantAppRequest) msg.obj,
1750                            mInstantAppInstallerActivity,
1751                            mHandler);
1752                }
1753            }
1754        }
1755    }
1756
1757    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1758            boolean killApp, String[] grantedPermissions,
1759            boolean launchedForRestore, String installerPackage,
1760            IPackageInstallObserver2 installObserver) {
1761        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1762            // Send the removed broadcasts
1763            if (res.removedInfo != null) {
1764                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1765            }
1766
1767            // Now that we successfully installed the package, grant runtime
1768            // permissions if requested before broadcasting the install. Also
1769            // for legacy apps in permission review mode we clear the permission
1770            // review flag which is used to emulate runtime permissions for
1771            // legacy apps.
1772            if (grantPermissions) {
1773                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1774            }
1775
1776            final boolean update = res.removedInfo != null
1777                    && res.removedInfo.removedPackage != null;
1778
1779            // If this is the first time we have child packages for a disabled privileged
1780            // app that had no children, we grant requested runtime permissions to the new
1781            // children if the parent on the system image had them already granted.
1782            if (res.pkg.parentPackage != null) {
1783                synchronized (mPackages) {
1784                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1785                }
1786            }
1787
1788            synchronized (mPackages) {
1789                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1790            }
1791
1792            final String packageName = res.pkg.applicationInfo.packageName;
1793
1794            // Determine the set of users who are adding this package for
1795            // the first time vs. those who are seeing an update.
1796            int[] firstUsers = EMPTY_INT_ARRAY;
1797            int[] updateUsers = EMPTY_INT_ARRAY;
1798            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1799            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1800            for (int newUser : res.newUsers) {
1801                if (ps.getInstantApp(newUser)) {
1802                    continue;
1803                }
1804                if (allNewUsers) {
1805                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1806                    continue;
1807                }
1808                boolean isNew = true;
1809                for (int origUser : res.origUsers) {
1810                    if (origUser == newUser) {
1811                        isNew = false;
1812                        break;
1813                    }
1814                }
1815                if (isNew) {
1816                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1817                } else {
1818                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1819                }
1820            }
1821
1822            // Send installed broadcasts if the package is not a static shared lib.
1823            if (res.pkg.staticSharedLibName == null) {
1824                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1825
1826                // Send added for users that see the package for the first time
1827                // sendPackageAddedForNewUsers also deals with system apps
1828                int appId = UserHandle.getAppId(res.uid);
1829                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1830                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1831
1832                // Send added for users that don't see the package for the first time
1833                Bundle extras = new Bundle(1);
1834                extras.putInt(Intent.EXTRA_UID, res.uid);
1835                if (update) {
1836                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1837                } else {
1838                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_ADDED, packageName,
1839                            extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
1840                            null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1841                }
1842                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1843                        extras, 0 /*flags*/, null /*targetPackage*/,
1844                        null /*finishedReceiver*/, updateUsers);
1845
1846                // Send replaced for users that don't see the package for the first time
1847                if (update) {
1848                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1849                            packageName, extras, 0 /*flags*/,
1850                            null /*targetPackage*/, null /*finishedReceiver*/,
1851                            updateUsers);
1852                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1853                            null /*package*/, null /*extras*/, 0 /*flags*/,
1854                            packageName /*targetPackage*/,
1855                            null /*finishedReceiver*/, updateUsers);
1856                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1857                    // First-install and we did a restore, so we're responsible for the
1858                    // first-launch broadcast.
1859                    if (DEBUG_BACKUP) {
1860                        Slog.i(TAG, "Post-restore of " + packageName
1861                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1862                    }
1863                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1864                }
1865
1866                // Send broadcast package appeared if forward locked/external for all users
1867                // treat asec-hosted packages like removable media on upgrade
1868                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1869                    if (DEBUG_INSTALL) {
1870                        Slog.i(TAG, "upgrading pkg " + res.pkg
1871                                + " is ASEC-hosted -> AVAILABLE");
1872                    }
1873                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1874                    ArrayList<String> pkgList = new ArrayList<>(1);
1875                    pkgList.add(packageName);
1876                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1877                }
1878            }
1879
1880            // Work that needs to happen on first install within each user
1881            if (firstUsers != null && firstUsers.length > 0) {
1882                synchronized (mPackages) {
1883                    for (int userId : firstUsers) {
1884                        // If this app is a browser and it's newly-installed for some
1885                        // users, clear any default-browser state in those users. The
1886                        // app's nature doesn't depend on the user, so we can just check
1887                        // its browser nature in any user and generalize.
1888                        if (packageIsBrowser(packageName, userId)) {
1889                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1890                        }
1891
1892                        // We may also need to apply pending (restored) runtime
1893                        // permission grants within these users.
1894                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1895                    }
1896                }
1897            }
1898
1899            // Log current value of "unknown sources" setting
1900            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1901                    getUnknownSourcesSettings());
1902
1903            // Force a gc to clear up things
1904            Runtime.getRuntime().gc();
1905
1906            // Remove the replaced package's older resources safely now
1907            // We delete after a gc for applications  on sdcard.
1908            if (res.removedInfo != null && res.removedInfo.args != null) {
1909                synchronized (mInstallLock) {
1910                    res.removedInfo.args.doPostDeleteLI(true);
1911                }
1912            }
1913
1914            // Notify DexManager that the package was installed for new users.
1915            // The updated users should already be indexed and the package code paths
1916            // should not change.
1917            // Don't notify the manager for ephemeral apps as they are not expected to
1918            // survive long enough to benefit of background optimizations.
1919            for (int userId : firstUsers) {
1920                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1921                // There's a race currently where some install events may interleave with an uninstall.
1922                // This can lead to package info being null (b/36642664).
1923                if (info != null) {
1924                    mDexManager.notifyPackageInstalled(info, userId);
1925                }
1926            }
1927        }
1928
1929        // If someone is watching installs - notify them
1930        if (installObserver != null) {
1931            try {
1932                Bundle extras = extrasForInstallResult(res);
1933                installObserver.onPackageInstalled(res.name, res.returnCode,
1934                        res.returnMsg, extras);
1935            } catch (RemoteException e) {
1936                Slog.i(TAG, "Observer no longer exists.");
1937            }
1938        }
1939    }
1940
1941    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1942            PackageParser.Package pkg) {
1943        if (pkg.parentPackage == null) {
1944            return;
1945        }
1946        if (pkg.requestedPermissions == null) {
1947            return;
1948        }
1949        final PackageSetting disabledSysParentPs = mSettings
1950                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1951        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1952                || !disabledSysParentPs.isPrivileged()
1953                || (disabledSysParentPs.childPackageNames != null
1954                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1955            return;
1956        }
1957        final int[] allUserIds = sUserManager.getUserIds();
1958        final int permCount = pkg.requestedPermissions.size();
1959        for (int i = 0; i < permCount; i++) {
1960            String permission = pkg.requestedPermissions.get(i);
1961            BasePermission bp = mSettings.mPermissions.get(permission);
1962            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1963                continue;
1964            }
1965            for (int userId : allUserIds) {
1966                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1967                        permission, userId)) {
1968                    grantRuntimePermission(pkg.packageName, permission, userId);
1969                }
1970            }
1971        }
1972    }
1973
1974    private StorageEventListener mStorageListener = new StorageEventListener() {
1975        @Override
1976        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1977            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1978                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1979                    final String volumeUuid = vol.getFsUuid();
1980
1981                    // Clean up any users or apps that were removed or recreated
1982                    // while this volume was missing
1983                    sUserManager.reconcileUsers(volumeUuid);
1984                    reconcileApps(volumeUuid);
1985
1986                    // Clean up any install sessions that expired or were
1987                    // cancelled while this volume was missing
1988                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1989
1990                    loadPrivatePackages(vol);
1991
1992                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1993                    unloadPrivatePackages(vol);
1994                }
1995            }
1996
1997            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1998                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1999                    updateExternalMediaStatus(true, false);
2000                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2001                    updateExternalMediaStatus(false, false);
2002                }
2003            }
2004        }
2005
2006        @Override
2007        public void onVolumeForgotten(String fsUuid) {
2008            if (TextUtils.isEmpty(fsUuid)) {
2009                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2010                return;
2011            }
2012
2013            // Remove any apps installed on the forgotten volume
2014            synchronized (mPackages) {
2015                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2016                for (PackageSetting ps : packages) {
2017                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2018                    deletePackageVersioned(new VersionedPackage(ps.name,
2019                            PackageManager.VERSION_CODE_HIGHEST),
2020                            new LegacyPackageDeleteObserver(null).getBinder(),
2021                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2022                    // Try very hard to release any references to this package
2023                    // so we don't risk the system server being killed due to
2024                    // open FDs
2025                    AttributeCache.instance().removePackage(ps.name);
2026                }
2027
2028                mSettings.onVolumeForgotten(fsUuid);
2029                mSettings.writeLPr();
2030            }
2031        }
2032    };
2033
2034    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2035            String[] grantedPermissions) {
2036        for (int userId : userIds) {
2037            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2038        }
2039    }
2040
2041    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2042            String[] grantedPermissions) {
2043        SettingBase sb = (SettingBase) pkg.mExtras;
2044        if (sb == null) {
2045            return;
2046        }
2047
2048        PermissionsState permissionsState = sb.getPermissionsState();
2049
2050        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2051                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2052
2053        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2054                >= Build.VERSION_CODES.M;
2055
2056        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2057
2058        for (String permission : pkg.requestedPermissions) {
2059            final BasePermission bp;
2060            synchronized (mPackages) {
2061                bp = mSettings.mPermissions.get(permission);
2062            }
2063            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2064                    && (!instantApp || bp.isInstant())
2065                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2066                    && (grantedPermissions == null
2067                           || ArrayUtils.contains(grantedPermissions, permission))) {
2068                final int flags = permissionsState.getPermissionFlags(permission, userId);
2069                if (supportsRuntimePermissions) {
2070                    // Installer cannot change immutable permissions.
2071                    if ((flags & immutableFlags) == 0) {
2072                        grantRuntimePermission(pkg.packageName, permission, userId);
2073                    }
2074                } else if (mPermissionReviewRequired) {
2075                    // In permission review mode we clear the review flag when we
2076                    // are asked to install the app with all permissions granted.
2077                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2078                        updatePermissionFlags(permission, pkg.packageName,
2079                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2080                    }
2081                }
2082            }
2083        }
2084    }
2085
2086    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2087        Bundle extras = null;
2088        switch (res.returnCode) {
2089            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2090                extras = new Bundle();
2091                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2092                        res.origPermission);
2093                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2094                        res.origPackage);
2095                break;
2096            }
2097            case PackageManager.INSTALL_SUCCEEDED: {
2098                extras = new Bundle();
2099                extras.putBoolean(Intent.EXTRA_REPLACING,
2100                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2101                break;
2102            }
2103        }
2104        return extras;
2105    }
2106
2107    void scheduleWriteSettingsLocked() {
2108        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2109            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2110        }
2111    }
2112
2113    void scheduleWritePackageListLocked(int userId) {
2114        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2115            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2116            msg.arg1 = userId;
2117            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2118        }
2119    }
2120
2121    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2122        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2123        scheduleWritePackageRestrictionsLocked(userId);
2124    }
2125
2126    void scheduleWritePackageRestrictionsLocked(int userId) {
2127        final int[] userIds = (userId == UserHandle.USER_ALL)
2128                ? sUserManager.getUserIds() : new int[]{userId};
2129        for (int nextUserId : userIds) {
2130            if (!sUserManager.exists(nextUserId)) return;
2131            mDirtyUsers.add(nextUserId);
2132            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2133                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2134            }
2135        }
2136    }
2137
2138    public static PackageManagerService main(Context context, Installer installer,
2139            boolean factoryTest, boolean onlyCore) {
2140        // Self-check for initial settings.
2141        PackageManagerServiceCompilerMapping.checkProperties();
2142
2143        PackageManagerService m = new PackageManagerService(context, installer,
2144                factoryTest, onlyCore);
2145        m.enableSystemUserPackages();
2146        ServiceManager.addService("package", m);
2147        return m;
2148    }
2149
2150    private void enableSystemUserPackages() {
2151        if (!UserManager.isSplitSystemUser()) {
2152            return;
2153        }
2154        // For system user, enable apps based on the following conditions:
2155        // - app is whitelisted or belong to one of these groups:
2156        //   -- system app which has no launcher icons
2157        //   -- system app which has INTERACT_ACROSS_USERS permission
2158        //   -- system IME app
2159        // - app is not in the blacklist
2160        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2161        Set<String> enableApps = new ArraySet<>();
2162        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2163                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2164                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2165        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2166        enableApps.addAll(wlApps);
2167        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2168                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2169        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2170        enableApps.removeAll(blApps);
2171        Log.i(TAG, "Applications installed for system user: " + enableApps);
2172        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2173                UserHandle.SYSTEM);
2174        final int allAppsSize = allAps.size();
2175        synchronized (mPackages) {
2176            for (int i = 0; i < allAppsSize; i++) {
2177                String pName = allAps.get(i);
2178                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2179                // Should not happen, but we shouldn't be failing if it does
2180                if (pkgSetting == null) {
2181                    continue;
2182                }
2183                boolean install = enableApps.contains(pName);
2184                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2185                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2186                            + " for system user");
2187                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2188                }
2189            }
2190            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2191        }
2192    }
2193
2194    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2195        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2196                Context.DISPLAY_SERVICE);
2197        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2198    }
2199
2200    /**
2201     * Requests that files preopted on a secondary system partition be copied to the data partition
2202     * if possible.  Note that the actual copying of the files is accomplished by init for security
2203     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2204     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2205     */
2206    private static void requestCopyPreoptedFiles() {
2207        final int WAIT_TIME_MS = 100;
2208        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2209        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2210            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2211            // We will wait for up to 100 seconds.
2212            final long timeStart = SystemClock.uptimeMillis();
2213            final long timeEnd = timeStart + 100 * 1000;
2214            long timeNow = timeStart;
2215            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2216                try {
2217                    Thread.sleep(WAIT_TIME_MS);
2218                } catch (InterruptedException e) {
2219                    // Do nothing
2220                }
2221                timeNow = SystemClock.uptimeMillis();
2222                if (timeNow > timeEnd) {
2223                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2224                    Slog.wtf(TAG, "cppreopt did not finish!");
2225                    break;
2226                }
2227            }
2228
2229            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2230        }
2231    }
2232
2233    public PackageManagerService(Context context, Installer installer,
2234            boolean factoryTest, boolean onlyCore) {
2235        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2236        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2237        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2238                SystemClock.uptimeMillis());
2239
2240        if (mSdkVersion <= 0) {
2241            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2242        }
2243
2244        mContext = context;
2245
2246        mPermissionReviewRequired = context.getResources().getBoolean(
2247                R.bool.config_permissionReviewRequired);
2248
2249        mFactoryTest = factoryTest;
2250        mOnlyCore = onlyCore;
2251        mMetrics = new DisplayMetrics();
2252        mSettings = new Settings(mPackages);
2253        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2254                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2255        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2256                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2257        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2258                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2259        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2260                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2261        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2262                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2263        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2264                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2265
2266        String separateProcesses = SystemProperties.get("debug.separate_processes");
2267        if (separateProcesses != null && separateProcesses.length() > 0) {
2268            if ("*".equals(separateProcesses)) {
2269                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2270                mSeparateProcesses = null;
2271                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2272            } else {
2273                mDefParseFlags = 0;
2274                mSeparateProcesses = separateProcesses.split(",");
2275                Slog.w(TAG, "Running with debug.separate_processes: "
2276                        + separateProcesses);
2277            }
2278        } else {
2279            mDefParseFlags = 0;
2280            mSeparateProcesses = null;
2281        }
2282
2283        mInstaller = installer;
2284        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2285                "*dexopt*");
2286        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2287        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2288
2289        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2290                FgThread.get().getLooper());
2291
2292        getDefaultDisplayMetrics(context, mMetrics);
2293
2294        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2295        SystemConfig systemConfig = SystemConfig.getInstance();
2296        mGlobalGids = systemConfig.getGlobalGids();
2297        mSystemPermissions = systemConfig.getSystemPermissions();
2298        mAvailableFeatures = systemConfig.getAvailableFeatures();
2299        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2300
2301        mProtectedPackages = new ProtectedPackages(mContext);
2302
2303        synchronized (mInstallLock) {
2304        // writer
2305        synchronized (mPackages) {
2306            mHandlerThread = new ServiceThread(TAG,
2307                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2308            mHandlerThread.start();
2309            mHandler = new PackageHandler(mHandlerThread.getLooper());
2310            mProcessLoggingHandler = new ProcessLoggingHandler();
2311            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2312
2313            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2314            mInstantAppRegistry = new InstantAppRegistry(this);
2315
2316            File dataDir = Environment.getDataDirectory();
2317            mAppInstallDir = new File(dataDir, "app");
2318            mAppLib32InstallDir = new File(dataDir, "app-lib");
2319            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2320            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2321            sUserManager = new UserManagerService(context, this,
2322                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2323
2324            // Propagate permission configuration in to package manager.
2325            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2326                    = systemConfig.getPermissions();
2327            for (int i=0; i<permConfig.size(); i++) {
2328                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2329                BasePermission bp = mSettings.mPermissions.get(perm.name);
2330                if (bp == null) {
2331                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2332                    mSettings.mPermissions.put(perm.name, bp);
2333                }
2334                if (perm.gids != null) {
2335                    bp.setGids(perm.gids, perm.perUser);
2336                }
2337            }
2338
2339            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2340            final int builtInLibCount = libConfig.size();
2341            for (int i = 0; i < builtInLibCount; i++) {
2342                String name = libConfig.keyAt(i);
2343                String path = libConfig.valueAt(i);
2344                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2345                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2346            }
2347
2348            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2349
2350            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2351            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2352            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2353
2354            // Clean up orphaned packages for which the code path doesn't exist
2355            // and they are an update to a system app - caused by bug/32321269
2356            final int packageSettingCount = mSettings.mPackages.size();
2357            for (int i = packageSettingCount - 1; i >= 0; i--) {
2358                PackageSetting ps = mSettings.mPackages.valueAt(i);
2359                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2360                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2361                    mSettings.mPackages.removeAt(i);
2362                    mSettings.enableSystemPackageLPw(ps.name);
2363                }
2364            }
2365
2366            if (mFirstBoot) {
2367                requestCopyPreoptedFiles();
2368            }
2369
2370            String customResolverActivity = Resources.getSystem().getString(
2371                    R.string.config_customResolverActivity);
2372            if (TextUtils.isEmpty(customResolverActivity)) {
2373                customResolverActivity = null;
2374            } else {
2375                mCustomResolverComponentName = ComponentName.unflattenFromString(
2376                        customResolverActivity);
2377            }
2378
2379            long startTime = SystemClock.uptimeMillis();
2380
2381            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2382                    startTime);
2383
2384            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2385            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2386
2387            if (bootClassPath == null) {
2388                Slog.w(TAG, "No BOOTCLASSPATH found!");
2389            }
2390
2391            if (systemServerClassPath == null) {
2392                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2393            }
2394
2395            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2396
2397            final VersionInfo ver = mSettings.getInternalVersion();
2398            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2399            if (mIsUpgrade) {
2400                logCriticalInfo(Log.INFO,
2401                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2402            }
2403
2404            // when upgrading from pre-M, promote system app permissions from install to runtime
2405            mPromoteSystemApps =
2406                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2407
2408            // When upgrading from pre-N, we need to handle package extraction like first boot,
2409            // as there is no profiling data available.
2410            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2411
2412            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2413
2414            // save off the names of pre-existing system packages prior to scanning; we don't
2415            // want to automatically grant runtime permissions for new system apps
2416            if (mPromoteSystemApps) {
2417                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2418                while (pkgSettingIter.hasNext()) {
2419                    PackageSetting ps = pkgSettingIter.next();
2420                    if (isSystemApp(ps)) {
2421                        mExistingSystemPackages.add(ps.name);
2422                    }
2423                }
2424            }
2425
2426            mCacheDir = preparePackageParserCache(mIsUpgrade);
2427
2428            // Set flag to monitor and not change apk file paths when
2429            // scanning install directories.
2430            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2431
2432            if (mIsUpgrade || mFirstBoot) {
2433                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2434            }
2435
2436            // Collect vendor overlay packages. (Do this before scanning any apps.)
2437            // For security and version matching reason, only consider
2438            // overlay packages if they reside in the right directory.
2439            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2440                    | PackageParser.PARSE_IS_SYSTEM
2441                    | PackageParser.PARSE_IS_SYSTEM_DIR
2442                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2443
2444            // Find base frameworks (resource packages without code).
2445            scanDirTracedLI(frameworkDir, mDefParseFlags
2446                    | PackageParser.PARSE_IS_SYSTEM
2447                    | PackageParser.PARSE_IS_SYSTEM_DIR
2448                    | PackageParser.PARSE_IS_PRIVILEGED,
2449                    scanFlags | SCAN_NO_DEX, 0);
2450
2451            // Collected privileged system packages.
2452            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2453            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2454                    | PackageParser.PARSE_IS_SYSTEM
2455                    | PackageParser.PARSE_IS_SYSTEM_DIR
2456                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2457
2458            // Collect ordinary system packages.
2459            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2460            scanDirTracedLI(systemAppDir, mDefParseFlags
2461                    | PackageParser.PARSE_IS_SYSTEM
2462                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2463
2464            // Collect all vendor packages.
2465            File vendorAppDir = new File("/vendor/app");
2466            try {
2467                vendorAppDir = vendorAppDir.getCanonicalFile();
2468            } catch (IOException e) {
2469                // failed to look up canonical path, continue with original one
2470            }
2471            scanDirTracedLI(vendorAppDir, mDefParseFlags
2472                    | PackageParser.PARSE_IS_SYSTEM
2473                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2474
2475            // Collect all OEM packages.
2476            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2477            scanDirTracedLI(oemAppDir, mDefParseFlags
2478                    | PackageParser.PARSE_IS_SYSTEM
2479                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2480
2481            // Prune any system packages that no longer exist.
2482            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2483            if (!mOnlyCore) {
2484                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2485                while (psit.hasNext()) {
2486                    PackageSetting ps = psit.next();
2487
2488                    /*
2489                     * If this is not a system app, it can't be a
2490                     * disable system app.
2491                     */
2492                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2493                        continue;
2494                    }
2495
2496                    /*
2497                     * If the package is scanned, it's not erased.
2498                     */
2499                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2500                    if (scannedPkg != null) {
2501                        /*
2502                         * If the system app is both scanned and in the
2503                         * disabled packages list, then it must have been
2504                         * added via OTA. Remove it from the currently
2505                         * scanned package so the previously user-installed
2506                         * application can be scanned.
2507                         */
2508                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2509                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2510                                    + ps.name + "; removing system app.  Last known codePath="
2511                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2512                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2513                                    + scannedPkg.mVersionCode);
2514                            removePackageLI(scannedPkg, true);
2515                            mExpectingBetter.put(ps.name, ps.codePath);
2516                        }
2517
2518                        continue;
2519                    }
2520
2521                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2522                        psit.remove();
2523                        logCriticalInfo(Log.WARN, "System package " + ps.name
2524                                + " no longer exists; it's data will be wiped");
2525                        // Actual deletion of code and data will be handled by later
2526                        // reconciliation step
2527                    } else {
2528                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2529                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2530                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2531                        }
2532                    }
2533                }
2534            }
2535
2536            //look for any incomplete package installations
2537            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2538            for (int i = 0; i < deletePkgsList.size(); i++) {
2539                // Actual deletion of code and data will be handled by later
2540                // reconciliation step
2541                final String packageName = deletePkgsList.get(i).name;
2542                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2543                synchronized (mPackages) {
2544                    mSettings.removePackageLPw(packageName);
2545                }
2546            }
2547
2548            //delete tmp files
2549            deleteTempPackageFiles();
2550
2551            // Remove any shared userIDs that have no associated packages
2552            mSettings.pruneSharedUsersLPw();
2553
2554            if (!mOnlyCore) {
2555                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2556                        SystemClock.uptimeMillis());
2557                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2558
2559                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2560                        | PackageParser.PARSE_FORWARD_LOCK,
2561                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2562
2563                /**
2564                 * Remove disable package settings for any updated system
2565                 * apps that were removed via an OTA. If they're not a
2566                 * previously-updated app, remove them completely.
2567                 * Otherwise, just revoke their system-level permissions.
2568                 */
2569                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2570                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2571                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2572
2573                    String msg;
2574                    if (deletedPkg == null) {
2575                        msg = "Updated system package " + deletedAppName
2576                                + " no longer exists; it's data will be wiped";
2577                        // Actual deletion of code and data will be handled by later
2578                        // reconciliation step
2579                    } else {
2580                        msg = "Updated system app + " + deletedAppName
2581                                + " no longer present; removing system privileges for "
2582                                + deletedAppName;
2583
2584                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2585
2586                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2587                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2588                    }
2589                    logCriticalInfo(Log.WARN, msg);
2590                }
2591
2592                /**
2593                 * Make sure all system apps that we expected to appear on
2594                 * the userdata partition actually showed up. If they never
2595                 * appeared, crawl back and revive the system version.
2596                 */
2597                for (int i = 0; i < mExpectingBetter.size(); i++) {
2598                    final String packageName = mExpectingBetter.keyAt(i);
2599                    if (!mPackages.containsKey(packageName)) {
2600                        final File scanFile = mExpectingBetter.valueAt(i);
2601
2602                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2603                                + " but never showed up; reverting to system");
2604
2605                        int reparseFlags = mDefParseFlags;
2606                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2607                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2608                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2609                                    | PackageParser.PARSE_IS_PRIVILEGED;
2610                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2611                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2612                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2613                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2614                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2615                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2616                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2617                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2618                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2619                        } else {
2620                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2621                            continue;
2622                        }
2623
2624                        mSettings.enableSystemPackageLPw(packageName);
2625
2626                        try {
2627                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2628                        } catch (PackageManagerException e) {
2629                            Slog.e(TAG, "Failed to parse original system package: "
2630                                    + e.getMessage());
2631                        }
2632                    }
2633                }
2634            }
2635            mExpectingBetter.clear();
2636
2637            // Resolve the storage manager.
2638            mStorageManagerPackage = getStorageManagerPackageName();
2639
2640            // Resolve protected action filters. Only the setup wizard is allowed to
2641            // have a high priority filter for these actions.
2642            mSetupWizardPackage = getSetupWizardPackageName();
2643            if (mProtectedFilters.size() > 0) {
2644                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2645                    Slog.i(TAG, "No setup wizard;"
2646                        + " All protected intents capped to priority 0");
2647                }
2648                for (ActivityIntentInfo filter : mProtectedFilters) {
2649                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2650                        if (DEBUG_FILTERS) {
2651                            Slog.i(TAG, "Found setup wizard;"
2652                                + " allow priority " + filter.getPriority() + ";"
2653                                + " package: " + filter.activity.info.packageName
2654                                + " activity: " + filter.activity.className
2655                                + " priority: " + filter.getPriority());
2656                        }
2657                        // skip setup wizard; allow it to keep the high priority filter
2658                        continue;
2659                    }
2660                    Slog.w(TAG, "Protected action; cap priority to 0;"
2661                            + " package: " + filter.activity.info.packageName
2662                            + " activity: " + filter.activity.className
2663                            + " origPrio: " + filter.getPriority());
2664                    filter.setPriority(0);
2665                }
2666            }
2667            mDeferProtectedFilters = false;
2668            mProtectedFilters.clear();
2669
2670            // Now that we know all of the shared libraries, update all clients to have
2671            // the correct library paths.
2672            updateAllSharedLibrariesLPw(null);
2673
2674            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2675                // NOTE: We ignore potential failures here during a system scan (like
2676                // the rest of the commands above) because there's precious little we
2677                // can do about it. A settings error is reported, though.
2678                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2679            }
2680
2681            // Now that we know all the packages we are keeping,
2682            // read and update their last usage times.
2683            mPackageUsage.read(mPackages);
2684            mCompilerStats.read();
2685
2686            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2687                    SystemClock.uptimeMillis());
2688            Slog.i(TAG, "Time to scan packages: "
2689                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2690                    + " seconds");
2691
2692            // If the platform SDK has changed since the last time we booted,
2693            // we need to re-grant app permission to catch any new ones that
2694            // appear.  This is really a hack, and means that apps can in some
2695            // cases get permissions that the user didn't initially explicitly
2696            // allow...  it would be nice to have some better way to handle
2697            // this situation.
2698            int updateFlags = UPDATE_PERMISSIONS_ALL;
2699            if (ver.sdkVersion != mSdkVersion) {
2700                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2701                        + mSdkVersion + "; regranting permissions for internal storage");
2702                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2703            }
2704            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2705            ver.sdkVersion = mSdkVersion;
2706
2707            // If this is the first boot or an update from pre-M, and it is a normal
2708            // boot, then we need to initialize the default preferred apps across
2709            // all defined users.
2710            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2711                for (UserInfo user : sUserManager.getUsers(true)) {
2712                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2713                    applyFactoryDefaultBrowserLPw(user.id);
2714                    primeDomainVerificationsLPw(user.id);
2715                }
2716            }
2717
2718            // Prepare storage for system user really early during boot,
2719            // since core system apps like SettingsProvider and SystemUI
2720            // can't wait for user to start
2721            final int storageFlags;
2722            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2723                storageFlags = StorageManager.FLAG_STORAGE_DE;
2724            } else {
2725                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2726            }
2727            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2728                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2729                    true /* onlyCoreApps */);
2730            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2731                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2732                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2733                traceLog.traceBegin("AppDataFixup");
2734                try {
2735                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2736                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2737                } catch (InstallerException e) {
2738                    Slog.w(TAG, "Trouble fixing GIDs", e);
2739                }
2740                traceLog.traceEnd();
2741
2742                traceLog.traceBegin("AppDataPrepare");
2743                if (deferPackages == null || deferPackages.isEmpty()) {
2744                    return;
2745                }
2746                int count = 0;
2747                for (String pkgName : deferPackages) {
2748                    PackageParser.Package pkg = null;
2749                    synchronized (mPackages) {
2750                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2751                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2752                            pkg = ps.pkg;
2753                        }
2754                    }
2755                    if (pkg != null) {
2756                        synchronized (mInstallLock) {
2757                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2758                                    true /* maybeMigrateAppData */);
2759                        }
2760                        count++;
2761                    }
2762                }
2763                traceLog.traceEnd();
2764                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2765            }, "prepareAppData");
2766
2767            // If this is first boot after an OTA, and a normal boot, then
2768            // we need to clear code cache directories.
2769            // Note that we do *not* clear the application profiles. These remain valid
2770            // across OTAs and are used to drive profile verification (post OTA) and
2771            // profile compilation (without waiting to collect a fresh set of profiles).
2772            if (mIsUpgrade && !onlyCore) {
2773                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2774                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2775                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2776                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2777                        // No apps are running this early, so no need to freeze
2778                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2779                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2780                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2781                    }
2782                }
2783                ver.fingerprint = Build.FINGERPRINT;
2784            }
2785
2786            checkDefaultBrowser();
2787
2788            // clear only after permissions and other defaults have been updated
2789            mExistingSystemPackages.clear();
2790            mPromoteSystemApps = false;
2791
2792            // All the changes are done during package scanning.
2793            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2794
2795            // can downgrade to reader
2796            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2797            mSettings.writeLPr();
2798            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2799
2800            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2801                    SystemClock.uptimeMillis());
2802
2803            if (!mOnlyCore) {
2804                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2805                mRequiredInstallerPackage = getRequiredInstallerLPr();
2806                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2807                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2808                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2809                        mIntentFilterVerifierComponent);
2810                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2811                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2812                        SharedLibraryInfo.VERSION_UNDEFINED);
2813                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2814                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2815                        SharedLibraryInfo.VERSION_UNDEFINED);
2816            } else {
2817                mRequiredVerifierPackage = null;
2818                mRequiredInstallerPackage = null;
2819                mRequiredUninstallerPackage = null;
2820                mIntentFilterVerifierComponent = null;
2821                mIntentFilterVerifier = null;
2822                mServicesSystemSharedLibraryPackageName = null;
2823                mSharedSystemSharedLibraryPackageName = null;
2824            }
2825
2826            mInstallerService = new PackageInstallerService(context, this);
2827            final Pair<ComponentName, String> instantAppResolverComponent =
2828                    getInstantAppResolverLPr();
2829            if (instantAppResolverComponent != null) {
2830                if (DEBUG_EPHEMERAL) {
2831                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2832                }
2833                mInstantAppResolverConnection = new EphemeralResolverConnection(
2834                        mContext, instantAppResolverComponent.first,
2835                        instantAppResolverComponent.second);
2836                mInstantAppResolverSettingsComponent =
2837                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2838            } else {
2839                mInstantAppResolverConnection = null;
2840                mInstantAppResolverSettingsComponent = null;
2841            }
2842            updateInstantAppInstallerLocked(null);
2843
2844            // Read and update the usage of dex files.
2845            // Do this at the end of PM init so that all the packages have their
2846            // data directory reconciled.
2847            // At this point we know the code paths of the packages, so we can validate
2848            // the disk file and build the internal cache.
2849            // The usage file is expected to be small so loading and verifying it
2850            // should take a fairly small time compare to the other activities (e.g. package
2851            // scanning).
2852            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2853            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2854            for (int userId : currentUserIds) {
2855                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2856            }
2857            mDexManager.load(userPackages);
2858        } // synchronized (mPackages)
2859        } // synchronized (mInstallLock)
2860
2861        // Now after opening every single application zip, make sure they
2862        // are all flushed.  Not really needed, but keeps things nice and
2863        // tidy.
2864        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2865        Runtime.getRuntime().gc();
2866        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2867
2868        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2869        FallbackCategoryProvider.loadFallbacks();
2870        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2871
2872        // The initial scanning above does many calls into installd while
2873        // holding the mPackages lock, but we're mostly interested in yelling
2874        // once we have a booted system.
2875        mInstaller.setWarnIfHeld(mPackages);
2876
2877        // Expose private service for system components to use.
2878        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2879        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2880    }
2881
2882    private void updateInstantAppInstallerLocked(String modifiedPackage) {
2883        // we're only interested in updating the installer appliction when 1) it's not
2884        // already set or 2) the modified package is the installer
2885        if (mInstantAppInstallerActivity != null
2886                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
2887                        .equals(modifiedPackage)) {
2888            return;
2889        }
2890        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
2891    }
2892
2893    private static File preparePackageParserCache(boolean isUpgrade) {
2894        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2895            return null;
2896        }
2897
2898        // Disable package parsing on eng builds to allow for faster incremental development.
2899        if ("eng".equals(Build.TYPE)) {
2900            return null;
2901        }
2902
2903        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2904            Slog.i(TAG, "Disabling package parser cache due to system property.");
2905            return null;
2906        }
2907
2908        // The base directory for the package parser cache lives under /data/system/.
2909        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2910                "package_cache");
2911        if (cacheBaseDir == null) {
2912            return null;
2913        }
2914
2915        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2916        // This also serves to "GC" unused entries when the package cache version changes (which
2917        // can only happen during upgrades).
2918        if (isUpgrade) {
2919            FileUtils.deleteContents(cacheBaseDir);
2920        }
2921
2922
2923        // Return the versioned package cache directory. This is something like
2924        // "/data/system/package_cache/1"
2925        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2926
2927        // The following is a workaround to aid development on non-numbered userdebug
2928        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2929        // the system partition is newer.
2930        //
2931        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2932        // that starts with "eng." to signify that this is an engineering build and not
2933        // destined for release.
2934        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2935            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2936
2937            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2938            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2939            // in general and should not be used for production changes. In this specific case,
2940            // we know that they will work.
2941            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2942            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2943                FileUtils.deleteContents(cacheBaseDir);
2944                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2945            }
2946        }
2947
2948        return cacheDir;
2949    }
2950
2951    @Override
2952    public boolean isFirstBoot() {
2953        return mFirstBoot;
2954    }
2955
2956    @Override
2957    public boolean isOnlyCoreApps() {
2958        return mOnlyCore;
2959    }
2960
2961    @Override
2962    public boolean isUpgrade() {
2963        return mIsUpgrade;
2964    }
2965
2966    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2967        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2968
2969        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2970                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2971                UserHandle.USER_SYSTEM);
2972        if (matches.size() == 1) {
2973            return matches.get(0).getComponentInfo().packageName;
2974        } else if (matches.size() == 0) {
2975            Log.e(TAG, "There should probably be a verifier, but, none were found");
2976            return null;
2977        }
2978        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2979    }
2980
2981    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2982        synchronized (mPackages) {
2983            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2984            if (libraryEntry == null) {
2985                throw new IllegalStateException("Missing required shared library:" + name);
2986            }
2987            return libraryEntry.apk;
2988        }
2989    }
2990
2991    private @NonNull String getRequiredInstallerLPr() {
2992        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2993        intent.addCategory(Intent.CATEGORY_DEFAULT);
2994        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2995
2996        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2997                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2998                UserHandle.USER_SYSTEM);
2999        if (matches.size() == 1) {
3000            ResolveInfo resolveInfo = matches.get(0);
3001            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3002                throw new RuntimeException("The installer must be a privileged app");
3003            }
3004            return matches.get(0).getComponentInfo().packageName;
3005        } else {
3006            throw new RuntimeException("There must be exactly one installer; found " + matches);
3007        }
3008    }
3009
3010    private @NonNull String getRequiredUninstallerLPr() {
3011        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3012        intent.addCategory(Intent.CATEGORY_DEFAULT);
3013        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3014
3015        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3016                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3017                UserHandle.USER_SYSTEM);
3018        if (resolveInfo == null ||
3019                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3020            throw new RuntimeException("There must be exactly one uninstaller; found "
3021                    + resolveInfo);
3022        }
3023        return resolveInfo.getComponentInfo().packageName;
3024    }
3025
3026    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3027        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3028
3029        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3030                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3031                UserHandle.USER_SYSTEM);
3032        ResolveInfo best = null;
3033        final int N = matches.size();
3034        for (int i = 0; i < N; i++) {
3035            final ResolveInfo cur = matches.get(i);
3036            final String packageName = cur.getComponentInfo().packageName;
3037            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3038                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3039                continue;
3040            }
3041
3042            if (best == null || cur.priority > best.priority) {
3043                best = cur;
3044            }
3045        }
3046
3047        if (best != null) {
3048            return best.getComponentInfo().getComponentName();
3049        } else {
3050            throw new RuntimeException("There must be at least one intent filter verifier");
3051        }
3052    }
3053
3054    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3055        final String[] packageArray =
3056                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3057        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3058            if (DEBUG_EPHEMERAL) {
3059                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3060            }
3061            return null;
3062        }
3063
3064        final int callingUid = Binder.getCallingUid();
3065        final int resolveFlags =
3066                MATCH_DIRECT_BOOT_AWARE
3067                | MATCH_DIRECT_BOOT_UNAWARE
3068                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3069        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3070        final Intent resolverIntent = new Intent(actionName);
3071        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3072                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3073        // temporarily look for the old action
3074        if (resolvers.size() == 0) {
3075            if (DEBUG_EPHEMERAL) {
3076                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3077            }
3078            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3079            resolverIntent.setAction(actionName);
3080            resolvers = queryIntentServicesInternal(resolverIntent, null,
3081                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3082        }
3083        final int N = resolvers.size();
3084        if (N == 0) {
3085            if (DEBUG_EPHEMERAL) {
3086                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3087            }
3088            return null;
3089        }
3090
3091        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3092        for (int i = 0; i < N; i++) {
3093            final ResolveInfo info = resolvers.get(i);
3094
3095            if (info.serviceInfo == null) {
3096                continue;
3097            }
3098
3099            final String packageName = info.serviceInfo.packageName;
3100            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3101                if (DEBUG_EPHEMERAL) {
3102                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3103                            + " pkg: " + packageName + ", info:" + info);
3104                }
3105                continue;
3106            }
3107
3108            if (DEBUG_EPHEMERAL) {
3109                Slog.v(TAG, "Ephemeral resolver found;"
3110                        + " pkg: " + packageName + ", info:" + info);
3111            }
3112            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3113        }
3114        if (DEBUG_EPHEMERAL) {
3115            Slog.v(TAG, "Ephemeral resolver NOT found");
3116        }
3117        return null;
3118    }
3119
3120    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3121        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3122        intent.addCategory(Intent.CATEGORY_DEFAULT);
3123        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3124
3125        final int resolveFlags =
3126                MATCH_DIRECT_BOOT_AWARE
3127                | MATCH_DIRECT_BOOT_UNAWARE
3128                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3129        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3130                resolveFlags, UserHandle.USER_SYSTEM);
3131        // temporarily look for the old action
3132        if (matches.isEmpty()) {
3133            if (DEBUG_EPHEMERAL) {
3134                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3135            }
3136            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3137            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3138                    resolveFlags, UserHandle.USER_SYSTEM);
3139        }
3140        Iterator<ResolveInfo> iter = matches.iterator();
3141        while (iter.hasNext()) {
3142            final ResolveInfo rInfo = iter.next();
3143            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3144            if (ps != null) {
3145                final PermissionsState permissionsState = ps.getPermissionsState();
3146                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3147                    continue;
3148                }
3149            }
3150            iter.remove();
3151        }
3152        if (matches.size() == 0) {
3153            return null;
3154        } else if (matches.size() == 1) {
3155            return (ActivityInfo) matches.get(0).getComponentInfo();
3156        } else {
3157            throw new RuntimeException(
3158                    "There must be at most one ephemeral installer; found " + matches);
3159        }
3160    }
3161
3162    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3163            @NonNull ComponentName resolver) {
3164        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3165                .addCategory(Intent.CATEGORY_DEFAULT)
3166                .setPackage(resolver.getPackageName());
3167        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3168        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3169                UserHandle.USER_SYSTEM);
3170        // temporarily look for the old action
3171        if (matches.isEmpty()) {
3172            if (DEBUG_EPHEMERAL) {
3173                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3174            }
3175            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3176            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3177                    UserHandle.USER_SYSTEM);
3178        }
3179        if (matches.isEmpty()) {
3180            return null;
3181        }
3182        return matches.get(0).getComponentInfo().getComponentName();
3183    }
3184
3185    private void primeDomainVerificationsLPw(int userId) {
3186        if (DEBUG_DOMAIN_VERIFICATION) {
3187            Slog.d(TAG, "Priming domain verifications in user " + userId);
3188        }
3189
3190        SystemConfig systemConfig = SystemConfig.getInstance();
3191        ArraySet<String> packages = systemConfig.getLinkedApps();
3192
3193        for (String packageName : packages) {
3194            PackageParser.Package pkg = mPackages.get(packageName);
3195            if (pkg != null) {
3196                if (!pkg.isSystemApp()) {
3197                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3198                    continue;
3199                }
3200
3201                ArraySet<String> domains = null;
3202                for (PackageParser.Activity a : pkg.activities) {
3203                    for (ActivityIntentInfo filter : a.intents) {
3204                        if (hasValidDomains(filter)) {
3205                            if (domains == null) {
3206                                domains = new ArraySet<String>();
3207                            }
3208                            domains.addAll(filter.getHostsList());
3209                        }
3210                    }
3211                }
3212
3213                if (domains != null && domains.size() > 0) {
3214                    if (DEBUG_DOMAIN_VERIFICATION) {
3215                        Slog.v(TAG, "      + " + packageName);
3216                    }
3217                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3218                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3219                    // and then 'always' in the per-user state actually used for intent resolution.
3220                    final IntentFilterVerificationInfo ivi;
3221                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3222                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3223                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3224                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3225                } else {
3226                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3227                            + "' does not handle web links");
3228                }
3229            } else {
3230                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3231            }
3232        }
3233
3234        scheduleWritePackageRestrictionsLocked(userId);
3235        scheduleWriteSettingsLocked();
3236    }
3237
3238    private void applyFactoryDefaultBrowserLPw(int userId) {
3239        // The default browser app's package name is stored in a string resource,
3240        // with a product-specific overlay used for vendor customization.
3241        String browserPkg = mContext.getResources().getString(
3242                com.android.internal.R.string.default_browser);
3243        if (!TextUtils.isEmpty(browserPkg)) {
3244            // non-empty string => required to be a known package
3245            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3246            if (ps == null) {
3247                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3248                browserPkg = null;
3249            } else {
3250                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3251            }
3252        }
3253
3254        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3255        // default.  If there's more than one, just leave everything alone.
3256        if (browserPkg == null) {
3257            calculateDefaultBrowserLPw(userId);
3258        }
3259    }
3260
3261    private void calculateDefaultBrowserLPw(int userId) {
3262        List<String> allBrowsers = resolveAllBrowserApps(userId);
3263        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3264        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3265    }
3266
3267    private List<String> resolveAllBrowserApps(int userId) {
3268        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3269        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3270                PackageManager.MATCH_ALL, userId);
3271
3272        final int count = list.size();
3273        List<String> result = new ArrayList<String>(count);
3274        for (int i=0; i<count; i++) {
3275            ResolveInfo info = list.get(i);
3276            if (info.activityInfo == null
3277                    || !info.handleAllWebDataURI
3278                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3279                    || result.contains(info.activityInfo.packageName)) {
3280                continue;
3281            }
3282            result.add(info.activityInfo.packageName);
3283        }
3284
3285        return result;
3286    }
3287
3288    private boolean packageIsBrowser(String packageName, int userId) {
3289        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3290                PackageManager.MATCH_ALL, userId);
3291        final int N = list.size();
3292        for (int i = 0; i < N; i++) {
3293            ResolveInfo info = list.get(i);
3294            if (packageName.equals(info.activityInfo.packageName)) {
3295                return true;
3296            }
3297        }
3298        return false;
3299    }
3300
3301    private void checkDefaultBrowser() {
3302        final int myUserId = UserHandle.myUserId();
3303        final String packageName = getDefaultBrowserPackageName(myUserId);
3304        if (packageName != null) {
3305            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3306            if (info == null) {
3307                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3308                synchronized (mPackages) {
3309                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3310                }
3311            }
3312        }
3313    }
3314
3315    @Override
3316    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3317            throws RemoteException {
3318        try {
3319            return super.onTransact(code, data, reply, flags);
3320        } catch (RuntimeException e) {
3321            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3322                Slog.wtf(TAG, "Package Manager Crash", e);
3323            }
3324            throw e;
3325        }
3326    }
3327
3328    static int[] appendInts(int[] cur, int[] add) {
3329        if (add == null) return cur;
3330        if (cur == null) return add;
3331        final int N = add.length;
3332        for (int i=0; i<N; i++) {
3333            cur = appendInt(cur, add[i]);
3334        }
3335        return cur;
3336    }
3337
3338    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3339        if (!sUserManager.exists(userId)) return null;
3340        if (ps == null) {
3341            return null;
3342        }
3343        final PackageParser.Package p = ps.pkg;
3344        if (p == null) {
3345            return null;
3346        }
3347        // Filter out ephemeral app metadata:
3348        //   * The system/shell/root can see metadata for any app
3349        //   * An installed app can see metadata for 1) other installed apps
3350        //     and 2) ephemeral apps that have explicitly interacted with it
3351        //   * Ephemeral apps can only see their own data and exposed installed apps
3352        //   * Holding a signature permission allows seeing instant apps
3353        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3354        if (callingAppId != Process.SYSTEM_UID
3355                && callingAppId != Process.SHELL_UID
3356                && callingAppId != Process.ROOT_UID
3357                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3358                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3359            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3360            if (instantAppPackageName != null) {
3361                // ephemeral apps can only get information on themselves or
3362                // installed apps that are exposed.
3363                if (!instantAppPackageName.equals(p.packageName)
3364                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3365                    return null;
3366                }
3367            } else {
3368                if (ps.getInstantApp(userId)) {
3369                    // only get access to the ephemeral app if we've been granted access
3370                    if (!mInstantAppRegistry.isInstantAccessGranted(
3371                            userId, callingAppId, ps.appId)) {
3372                        return null;
3373                    }
3374                }
3375            }
3376        }
3377
3378        final PermissionsState permissionsState = ps.getPermissionsState();
3379
3380        // Compute GIDs only if requested
3381        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3382                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3383        // Compute granted permissions only if package has requested permissions
3384        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3385                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3386        final PackageUserState state = ps.readUserState(userId);
3387
3388        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3389                && ps.isSystem()) {
3390            flags |= MATCH_ANY_USER;
3391        }
3392
3393        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3394                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3395
3396        if (packageInfo == null) {
3397            return null;
3398        }
3399
3400        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3401
3402        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3403                resolveExternalPackageNameLPr(p);
3404
3405        return packageInfo;
3406    }
3407
3408    @Override
3409    public void checkPackageStartable(String packageName, int userId) {
3410        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3411
3412        synchronized (mPackages) {
3413            final PackageSetting ps = mSettings.mPackages.get(packageName);
3414            if (ps == null) {
3415                throw new SecurityException("Package " + packageName + " was not found!");
3416            }
3417
3418            if (!ps.getInstalled(userId)) {
3419                throw new SecurityException(
3420                        "Package " + packageName + " was not installed for user " + userId + "!");
3421            }
3422
3423            if (mSafeMode && !ps.isSystem()) {
3424                throw new SecurityException("Package " + packageName + " not a system app!");
3425            }
3426
3427            if (mFrozenPackages.contains(packageName)) {
3428                throw new SecurityException("Package " + packageName + " is currently frozen!");
3429            }
3430
3431            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3432                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3433                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3434            }
3435        }
3436    }
3437
3438    @Override
3439    public boolean isPackageAvailable(String packageName, int userId) {
3440        if (!sUserManager.exists(userId)) return false;
3441        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3442                false /* requireFullPermission */, false /* checkShell */, "is package available");
3443        synchronized (mPackages) {
3444            PackageParser.Package p = mPackages.get(packageName);
3445            if (p != null) {
3446                final PackageSetting ps = (PackageSetting) p.mExtras;
3447                if (ps != null) {
3448                    final PackageUserState state = ps.readUserState(userId);
3449                    if (state != null) {
3450                        return PackageParser.isAvailable(state);
3451                    }
3452                }
3453            }
3454        }
3455        return false;
3456    }
3457
3458    @Override
3459    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3460        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3461                flags, userId);
3462    }
3463
3464    @Override
3465    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3466            int flags, int userId) {
3467        return getPackageInfoInternal(versionedPackage.getPackageName(),
3468                // TODO: We will change version code to long, so in the new API it is long
3469                (int) versionedPackage.getVersionCode(), flags, userId);
3470    }
3471
3472    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3473            int flags, int userId) {
3474        if (!sUserManager.exists(userId)) return null;
3475        flags = updateFlagsForPackage(flags, userId, packageName);
3476        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3477                false /* requireFullPermission */, false /* checkShell */, "get package info");
3478
3479        // reader
3480        synchronized (mPackages) {
3481            // Normalize package name to handle renamed packages and static libs
3482            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3483
3484            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3485            if (matchFactoryOnly) {
3486                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3487                if (ps != null) {
3488                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3489                        return null;
3490                    }
3491                    return generatePackageInfo(ps, flags, userId);
3492                }
3493            }
3494
3495            PackageParser.Package p = mPackages.get(packageName);
3496            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3497                return null;
3498            }
3499            if (DEBUG_PACKAGE_INFO)
3500                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3501            if (p != null) {
3502                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3503                        Binder.getCallingUid(), userId)) {
3504                    return null;
3505                }
3506                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3507            }
3508            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3509                final PackageSetting ps = mSettings.mPackages.get(packageName);
3510                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3511                    return null;
3512                }
3513                return generatePackageInfo(ps, flags, userId);
3514            }
3515        }
3516        return null;
3517    }
3518
3519
3520    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3521        // System/shell/root get to see all static libs
3522        final int appId = UserHandle.getAppId(uid);
3523        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3524                || appId == Process.ROOT_UID) {
3525            return false;
3526        }
3527
3528        // No package means no static lib as it is always on internal storage
3529        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3530            return false;
3531        }
3532
3533        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3534                ps.pkg.staticSharedLibVersion);
3535        if (libEntry == null) {
3536            return false;
3537        }
3538
3539        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3540        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3541        if (uidPackageNames == null) {
3542            return true;
3543        }
3544
3545        for (String uidPackageName : uidPackageNames) {
3546            if (ps.name.equals(uidPackageName)) {
3547                return false;
3548            }
3549            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3550            if (uidPs != null) {
3551                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3552                        libEntry.info.getName());
3553                if (index < 0) {
3554                    continue;
3555                }
3556                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3557                    return false;
3558                }
3559            }
3560        }
3561        return true;
3562    }
3563
3564    @Override
3565    public String[] currentToCanonicalPackageNames(String[] names) {
3566        String[] out = new String[names.length];
3567        // reader
3568        synchronized (mPackages) {
3569            for (int i=names.length-1; i>=0; i--) {
3570                PackageSetting ps = mSettings.mPackages.get(names[i]);
3571                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3572            }
3573        }
3574        return out;
3575    }
3576
3577    @Override
3578    public String[] canonicalToCurrentPackageNames(String[] names) {
3579        String[] out = new String[names.length];
3580        // reader
3581        synchronized (mPackages) {
3582            for (int i=names.length-1; i>=0; i--) {
3583                String cur = mSettings.getRenamedPackageLPr(names[i]);
3584                out[i] = cur != null ? cur : names[i];
3585            }
3586        }
3587        return out;
3588    }
3589
3590    @Override
3591    public int getPackageUid(String packageName, int flags, int userId) {
3592        if (!sUserManager.exists(userId)) return -1;
3593        flags = updateFlagsForPackage(flags, userId, packageName);
3594        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3595                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3596
3597        // reader
3598        synchronized (mPackages) {
3599            final PackageParser.Package p = mPackages.get(packageName);
3600            if (p != null && p.isMatch(flags)) {
3601                return UserHandle.getUid(userId, p.applicationInfo.uid);
3602            }
3603            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3604                final PackageSetting ps = mSettings.mPackages.get(packageName);
3605                if (ps != null && ps.isMatch(flags)) {
3606                    return UserHandle.getUid(userId, ps.appId);
3607                }
3608            }
3609        }
3610
3611        return -1;
3612    }
3613
3614    @Override
3615    public int[] getPackageGids(String packageName, int flags, int userId) {
3616        if (!sUserManager.exists(userId)) return null;
3617        flags = updateFlagsForPackage(flags, userId, packageName);
3618        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3619                false /* requireFullPermission */, false /* checkShell */,
3620                "getPackageGids");
3621
3622        // reader
3623        synchronized (mPackages) {
3624            final PackageParser.Package p = mPackages.get(packageName);
3625            if (p != null && p.isMatch(flags)) {
3626                PackageSetting ps = (PackageSetting) p.mExtras;
3627                // TODO: Shouldn't this be checking for package installed state for userId and
3628                // return null?
3629                return ps.getPermissionsState().computeGids(userId);
3630            }
3631            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3632                final PackageSetting ps = mSettings.mPackages.get(packageName);
3633                if (ps != null && ps.isMatch(flags)) {
3634                    return ps.getPermissionsState().computeGids(userId);
3635                }
3636            }
3637        }
3638
3639        return null;
3640    }
3641
3642    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3643        if (bp.perm != null) {
3644            return PackageParser.generatePermissionInfo(bp.perm, flags);
3645        }
3646        PermissionInfo pi = new PermissionInfo();
3647        pi.name = bp.name;
3648        pi.packageName = bp.sourcePackage;
3649        pi.nonLocalizedLabel = bp.name;
3650        pi.protectionLevel = bp.protectionLevel;
3651        return pi;
3652    }
3653
3654    @Override
3655    public PermissionInfo getPermissionInfo(String name, int flags) {
3656        // reader
3657        synchronized (mPackages) {
3658            final BasePermission p = mSettings.mPermissions.get(name);
3659            if (p != null) {
3660                return generatePermissionInfo(p, flags);
3661            }
3662            return null;
3663        }
3664    }
3665
3666    @Override
3667    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3668            int flags) {
3669        // reader
3670        synchronized (mPackages) {
3671            if (group != null && !mPermissionGroups.containsKey(group)) {
3672                // This is thrown as NameNotFoundException
3673                return null;
3674            }
3675
3676            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3677            for (BasePermission p : mSettings.mPermissions.values()) {
3678                if (group == null) {
3679                    if (p.perm == null || p.perm.info.group == null) {
3680                        out.add(generatePermissionInfo(p, flags));
3681                    }
3682                } else {
3683                    if (p.perm != null && group.equals(p.perm.info.group)) {
3684                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3685                    }
3686                }
3687            }
3688            return new ParceledListSlice<>(out);
3689        }
3690    }
3691
3692    @Override
3693    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3694        // reader
3695        synchronized (mPackages) {
3696            return PackageParser.generatePermissionGroupInfo(
3697                    mPermissionGroups.get(name), flags);
3698        }
3699    }
3700
3701    @Override
3702    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3703        // reader
3704        synchronized (mPackages) {
3705            final int N = mPermissionGroups.size();
3706            ArrayList<PermissionGroupInfo> out
3707                    = new ArrayList<PermissionGroupInfo>(N);
3708            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3709                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3710            }
3711            return new ParceledListSlice<>(out);
3712        }
3713    }
3714
3715    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3716            int uid, int userId) {
3717        if (!sUserManager.exists(userId)) return null;
3718        PackageSetting ps = mSettings.mPackages.get(packageName);
3719        if (ps != null) {
3720            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3721                return null;
3722            }
3723            if (ps.pkg == null) {
3724                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3725                if (pInfo != null) {
3726                    return pInfo.applicationInfo;
3727                }
3728                return null;
3729            }
3730            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3731                    ps.readUserState(userId), userId);
3732            if (ai != null) {
3733                rebaseEnabledOverlays(ai, userId);
3734                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3735            }
3736            return ai;
3737        }
3738        return null;
3739    }
3740
3741    @Override
3742    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3743        if (!sUserManager.exists(userId)) return null;
3744        flags = updateFlagsForApplication(flags, userId, packageName);
3745        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3746                false /* requireFullPermission */, false /* checkShell */, "get application info");
3747
3748        // writer
3749        synchronized (mPackages) {
3750            // Normalize package name to handle renamed packages and static libs
3751            packageName = resolveInternalPackageNameLPr(packageName,
3752                    PackageManager.VERSION_CODE_HIGHEST);
3753
3754            PackageParser.Package p = mPackages.get(packageName);
3755            if (DEBUG_PACKAGE_INFO) Log.v(
3756                    TAG, "getApplicationInfo " + packageName
3757                    + ": " + p);
3758            if (p != null) {
3759                PackageSetting ps = mSettings.mPackages.get(packageName);
3760                if (ps == null) return null;
3761                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3762                    return null;
3763                }
3764                // Note: isEnabledLP() does not apply here - always return info
3765                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3766                        p, flags, ps.readUserState(userId), userId);
3767                if (ai != null) {
3768                    rebaseEnabledOverlays(ai, userId);
3769                    ai.packageName = resolveExternalPackageNameLPr(p);
3770                }
3771                return ai;
3772            }
3773            if ("android".equals(packageName)||"system".equals(packageName)) {
3774                return mAndroidApplication;
3775            }
3776            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3777                // Already generates the external package name
3778                return generateApplicationInfoFromSettingsLPw(packageName,
3779                        Binder.getCallingUid(), flags, userId);
3780            }
3781        }
3782        return null;
3783    }
3784
3785    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3786        List<String> paths = new ArrayList<>();
3787        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3788            mEnabledOverlayPaths.get(userId);
3789        if (userSpecificOverlays != null) {
3790            if (!"android".equals(ai.packageName)) {
3791                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3792                if (frameworkOverlays != null) {
3793                    paths.addAll(frameworkOverlays);
3794                }
3795            }
3796
3797            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3798            if (appOverlays != null) {
3799                paths.addAll(appOverlays);
3800            }
3801        }
3802        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3803    }
3804
3805    private String normalizePackageNameLPr(String packageName) {
3806        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3807        return normalizedPackageName != null ? normalizedPackageName : packageName;
3808    }
3809
3810    @Override
3811    public void deletePreloadsFileCache() {
3812        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3813            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3814        }
3815        File dir = Environment.getDataPreloadsFileCacheDirectory();
3816        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3817        FileUtils.deleteContents(dir);
3818    }
3819
3820    @Override
3821    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3822            final IPackageDataObserver observer) {
3823        mContext.enforceCallingOrSelfPermission(
3824                android.Manifest.permission.CLEAR_APP_CACHE, null);
3825        mHandler.post(() -> {
3826            boolean success = false;
3827            try {
3828                freeStorage(volumeUuid, freeStorageSize, 0);
3829                success = true;
3830            } catch (IOException e) {
3831                Slog.w(TAG, e);
3832            }
3833            if (observer != null) {
3834                try {
3835                    observer.onRemoveCompleted(null, success);
3836                } catch (RemoteException e) {
3837                    Slog.w(TAG, e);
3838                }
3839            }
3840        });
3841    }
3842
3843    @Override
3844    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3845            final IntentSender pi) {
3846        mContext.enforceCallingOrSelfPermission(
3847                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3848        mHandler.post(() -> {
3849            boolean success = false;
3850            try {
3851                freeStorage(volumeUuid, freeStorageSize, 0);
3852                success = true;
3853            } catch (IOException e) {
3854                Slog.w(TAG, e);
3855            }
3856            if (pi != null) {
3857                try {
3858                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3859                } catch (SendIntentException e) {
3860                    Slog.w(TAG, e);
3861                }
3862            }
3863        });
3864    }
3865
3866    /**
3867     * Blocking call to clear various types of cached data across the system
3868     * until the requested bytes are available.
3869     */
3870    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3871        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3872        final File file = storage.findPathForUuid(volumeUuid);
3873        if (file.getUsableSpace() >= bytes) return;
3874
3875        if (ENABLE_FREE_CACHE_V2) {
3876            final boolean aggressive = (storageFlags
3877                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3878            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
3879                    volumeUuid);
3880
3881            // 1. Pre-flight to determine if we have any chance to succeed
3882            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3883            if (internalVolume && (aggressive || SystemProperties
3884                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
3885                deletePreloadsFileCache();
3886                if (file.getUsableSpace() >= bytes) return;
3887            }
3888
3889            // 3. Consider parsed APK data (aggressive only)
3890            if (internalVolume && aggressive) {
3891                FileUtils.deleteContents(mCacheDir);
3892                if (file.getUsableSpace() >= bytes) return;
3893            }
3894
3895            // 4. Consider cached app data (above quotas)
3896            try {
3897                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3898            } catch (InstallerException ignored) {
3899            }
3900            if (file.getUsableSpace() >= bytes) return;
3901
3902            // 5. Consider shared libraries with refcount=0 and age>2h
3903            // 6. Consider dexopt output (aggressive only)
3904            // 7. Consider ephemeral apps not used in last week
3905
3906            // 8. Consider cached app data (below quotas)
3907            try {
3908                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3909                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3910            } catch (InstallerException ignored) {
3911            }
3912            if (file.getUsableSpace() >= bytes) return;
3913
3914            // 9. Consider DropBox entries
3915            // 10. Consider ephemeral cookies
3916
3917        } else {
3918            try {
3919                mInstaller.freeCache(volumeUuid, bytes, 0);
3920            } catch (InstallerException ignored) {
3921            }
3922            if (file.getUsableSpace() >= bytes) return;
3923        }
3924
3925        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3926    }
3927
3928    /**
3929     * Update given flags based on encryption status of current user.
3930     */
3931    private int updateFlags(int flags, int userId) {
3932        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3933                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3934            // Caller expressed an explicit opinion about what encryption
3935            // aware/unaware components they want to see, so fall through and
3936            // give them what they want
3937        } else {
3938            // Caller expressed no opinion, so match based on user state
3939            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3940                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3941            } else {
3942                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3943            }
3944        }
3945        return flags;
3946    }
3947
3948    private UserManagerInternal getUserManagerInternal() {
3949        if (mUserManagerInternal == null) {
3950            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3951        }
3952        return mUserManagerInternal;
3953    }
3954
3955    private DeviceIdleController.LocalService getDeviceIdleController() {
3956        if (mDeviceIdleController == null) {
3957            mDeviceIdleController =
3958                    LocalServices.getService(DeviceIdleController.LocalService.class);
3959        }
3960        return mDeviceIdleController;
3961    }
3962
3963    /**
3964     * Update given flags when being used to request {@link PackageInfo}.
3965     */
3966    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3967        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3968        boolean triaged = true;
3969        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3970                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3971            // Caller is asking for component details, so they'd better be
3972            // asking for specific encryption matching behavior, or be triaged
3973            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3974                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3975                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3976                triaged = false;
3977            }
3978        }
3979        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3980                | PackageManager.MATCH_SYSTEM_ONLY
3981                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3982            triaged = false;
3983        }
3984        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3985            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3986                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3987                    + Debug.getCallers(5));
3988        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3989                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3990            // If the caller wants all packages and has a restricted profile associated with it,
3991            // then match all users. This is to make sure that launchers that need to access work
3992            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3993            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3994            flags |= PackageManager.MATCH_ANY_USER;
3995        }
3996        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3997            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3998                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3999        }
4000        return updateFlags(flags, userId);
4001    }
4002
4003    /**
4004     * Update given flags when being used to request {@link ApplicationInfo}.
4005     */
4006    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4007        return updateFlagsForPackage(flags, userId, cookie);
4008    }
4009
4010    /**
4011     * Update given flags when being used to request {@link ComponentInfo}.
4012     */
4013    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4014        if (cookie instanceof Intent) {
4015            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4016                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4017            }
4018        }
4019
4020        boolean triaged = true;
4021        // Caller is asking for component details, so they'd better be
4022        // asking for specific encryption matching behavior, or be triaged
4023        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4024                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4025                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4026            triaged = false;
4027        }
4028        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4029            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4030                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4031        }
4032
4033        return updateFlags(flags, userId);
4034    }
4035
4036    /**
4037     * Update given intent when being used to request {@link ResolveInfo}.
4038     */
4039    private Intent updateIntentForResolve(Intent intent) {
4040        if (intent.getSelector() != null) {
4041            intent = intent.getSelector();
4042        }
4043        if (DEBUG_PREFERRED) {
4044            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4045        }
4046        return intent;
4047    }
4048
4049    /**
4050     * Update given flags when being used to request {@link ResolveInfo}.
4051     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4052     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4053     * flag set. However, this flag is only honoured in three circumstances:
4054     * <ul>
4055     * <li>when called from a system process</li>
4056     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4057     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4058     * action and a {@code android.intent.category.BROWSABLE} category</li>
4059     * </ul>
4060     */
4061    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4062            boolean includeInstantApps) {
4063        // Safe mode means we shouldn't match any third-party components
4064        if (mSafeMode) {
4065            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4066        }
4067        if (getInstantAppPackageName(callingUid) != null) {
4068            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4069            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4070            flags |= PackageManager.MATCH_INSTANT;
4071        } else {
4072            // Otherwise, prevent leaking ephemeral components
4073            final boolean isSpecialProcess =
4074                    callingUid == Process.SYSTEM_UID
4075                    || callingUid == Process.SHELL_UID
4076                    || callingUid == 0;
4077            final boolean allowMatchInstant =
4078                    (includeInstantApps
4079                            && Intent.ACTION_VIEW.equals(intent.getAction())
4080                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4081                            && hasWebURI(intent))
4082                    || isSpecialProcess
4083                    || mContext.checkCallingOrSelfPermission(
4084                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4085            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4086            if (!allowMatchInstant) {
4087                flags &= ~PackageManager.MATCH_INSTANT;
4088            }
4089        }
4090        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4091    }
4092
4093    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4094            int userId) {
4095        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4096        if (ret != null) {
4097            rebaseEnabledOverlays(ret.applicationInfo, userId);
4098        }
4099        return ret;
4100    }
4101
4102    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4103            PackageUserState state, int userId) {
4104        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4105        if (ai != null) {
4106            rebaseEnabledOverlays(ai.applicationInfo, userId);
4107        }
4108        return ai;
4109    }
4110
4111    @Override
4112    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4113        if (!sUserManager.exists(userId)) return null;
4114        flags = updateFlagsForComponent(flags, userId, component);
4115        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4116                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4117        synchronized (mPackages) {
4118            PackageParser.Activity a = mActivities.mActivities.get(component);
4119
4120            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4121            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4122                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4123                if (ps == null) return null;
4124                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4125            }
4126            if (mResolveComponentName.equals(component)) {
4127                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4128                        userId);
4129            }
4130        }
4131        return null;
4132    }
4133
4134    @Override
4135    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4136            String resolvedType) {
4137        synchronized (mPackages) {
4138            if (component.equals(mResolveComponentName)) {
4139                // The resolver supports EVERYTHING!
4140                return true;
4141            }
4142            PackageParser.Activity a = mActivities.mActivities.get(component);
4143            if (a == null) {
4144                return false;
4145            }
4146            for (int i=0; i<a.intents.size(); i++) {
4147                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4148                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4149                    return true;
4150                }
4151            }
4152            return false;
4153        }
4154    }
4155
4156    @Override
4157    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4158        if (!sUserManager.exists(userId)) return null;
4159        flags = updateFlagsForComponent(flags, userId, component);
4160        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4161                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4162        synchronized (mPackages) {
4163            PackageParser.Activity a = mReceivers.mActivities.get(component);
4164            if (DEBUG_PACKAGE_INFO) Log.v(
4165                TAG, "getReceiverInfo " + component + ": " + a);
4166            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4167                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4168                if (ps == null) return null;
4169                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4170            }
4171        }
4172        return null;
4173    }
4174
4175    @Override
4176    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4177        if (!sUserManager.exists(userId)) return null;
4178        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4179
4180        flags = updateFlagsForPackage(flags, userId, null);
4181
4182        final boolean canSeeStaticLibraries =
4183                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4184                        == PERMISSION_GRANTED
4185                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4186                        == PERMISSION_GRANTED
4187                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4188                        == PERMISSION_GRANTED
4189                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4190                        == PERMISSION_GRANTED;
4191
4192        synchronized (mPackages) {
4193            List<SharedLibraryInfo> result = null;
4194
4195            final int libCount = mSharedLibraries.size();
4196            for (int i = 0; i < libCount; i++) {
4197                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4198                if (versionedLib == null) {
4199                    continue;
4200                }
4201
4202                final int versionCount = versionedLib.size();
4203                for (int j = 0; j < versionCount; j++) {
4204                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4205                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4206                        break;
4207                    }
4208                    final long identity = Binder.clearCallingIdentity();
4209                    try {
4210                        // TODO: We will change version code to long, so in the new API it is long
4211                        PackageInfo packageInfo = getPackageInfoVersioned(
4212                                libInfo.getDeclaringPackage(), flags, userId);
4213                        if (packageInfo == null) {
4214                            continue;
4215                        }
4216                    } finally {
4217                        Binder.restoreCallingIdentity(identity);
4218                    }
4219
4220                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4221                            // TODO: Remove cast for lib version once internally we support longs.
4222                            (int) libInfo.getVersion(), libInfo.getType(),
4223                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4224                            flags, userId));
4225
4226                    if (result == null) {
4227                        result = new ArrayList<>();
4228                    }
4229                    result.add(resLibInfo);
4230                }
4231            }
4232
4233            return result != null ? new ParceledListSlice<>(result) : null;
4234        }
4235    }
4236
4237    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4238            SharedLibraryInfo libInfo, int flags, int userId) {
4239        List<VersionedPackage> versionedPackages = null;
4240        final int packageCount = mSettings.mPackages.size();
4241        for (int i = 0; i < packageCount; i++) {
4242            PackageSetting ps = mSettings.mPackages.valueAt(i);
4243
4244            if (ps == null) {
4245                continue;
4246            }
4247
4248            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4249                continue;
4250            }
4251
4252            final String libName = libInfo.getName();
4253            if (libInfo.isStatic()) {
4254                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4255                if (libIdx < 0) {
4256                    continue;
4257                }
4258                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4259                    continue;
4260                }
4261                if (versionedPackages == null) {
4262                    versionedPackages = new ArrayList<>();
4263                }
4264                // If the dependent is a static shared lib, use the public package name
4265                String dependentPackageName = ps.name;
4266                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4267                    dependentPackageName = ps.pkg.manifestPackageName;
4268                }
4269                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4270            } else if (ps.pkg != null) {
4271                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4272                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4273                    if (versionedPackages == null) {
4274                        versionedPackages = new ArrayList<>();
4275                    }
4276                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4277                }
4278            }
4279        }
4280
4281        return versionedPackages;
4282    }
4283
4284    @Override
4285    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4286        if (!sUserManager.exists(userId)) return null;
4287        flags = updateFlagsForComponent(flags, userId, component);
4288        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4289                false /* requireFullPermission */, false /* checkShell */, "get service info");
4290        synchronized (mPackages) {
4291            PackageParser.Service s = mServices.mServices.get(component);
4292            if (DEBUG_PACKAGE_INFO) Log.v(
4293                TAG, "getServiceInfo " + component + ": " + s);
4294            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4295                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4296                if (ps == null) return null;
4297                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4298                        ps.readUserState(userId), userId);
4299                if (si != null) {
4300                    rebaseEnabledOverlays(si.applicationInfo, userId);
4301                }
4302                return si;
4303            }
4304        }
4305        return null;
4306    }
4307
4308    @Override
4309    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4310        if (!sUserManager.exists(userId)) return null;
4311        flags = updateFlagsForComponent(flags, userId, component);
4312        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4313                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4314        synchronized (mPackages) {
4315            PackageParser.Provider p = mProviders.mProviders.get(component);
4316            if (DEBUG_PACKAGE_INFO) Log.v(
4317                TAG, "getProviderInfo " + component + ": " + p);
4318            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4319                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4320                if (ps == null) return null;
4321                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4322                        ps.readUserState(userId), userId);
4323                if (pi != null) {
4324                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4325                }
4326                return pi;
4327            }
4328        }
4329        return null;
4330    }
4331
4332    @Override
4333    public String[] getSystemSharedLibraryNames() {
4334        synchronized (mPackages) {
4335            Set<String> libs = null;
4336            final int libCount = mSharedLibraries.size();
4337            for (int i = 0; i < libCount; i++) {
4338                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4339                if (versionedLib == null) {
4340                    continue;
4341                }
4342                final int versionCount = versionedLib.size();
4343                for (int j = 0; j < versionCount; j++) {
4344                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4345                    if (!libEntry.info.isStatic()) {
4346                        if (libs == null) {
4347                            libs = new ArraySet<>();
4348                        }
4349                        libs.add(libEntry.info.getName());
4350                        break;
4351                    }
4352                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4353                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4354                            UserHandle.getUserId(Binder.getCallingUid()))) {
4355                        if (libs == null) {
4356                            libs = new ArraySet<>();
4357                        }
4358                        libs.add(libEntry.info.getName());
4359                        break;
4360                    }
4361                }
4362            }
4363
4364            if (libs != null) {
4365                String[] libsArray = new String[libs.size()];
4366                libs.toArray(libsArray);
4367                return libsArray;
4368            }
4369
4370            return null;
4371        }
4372    }
4373
4374    @Override
4375    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4376        synchronized (mPackages) {
4377            return mServicesSystemSharedLibraryPackageName;
4378        }
4379    }
4380
4381    @Override
4382    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4383        synchronized (mPackages) {
4384            return mSharedSystemSharedLibraryPackageName;
4385        }
4386    }
4387
4388    private void updateSequenceNumberLP(String packageName, int[] userList) {
4389        for (int i = userList.length - 1; i >= 0; --i) {
4390            final int userId = userList[i];
4391            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4392            if (changedPackages == null) {
4393                changedPackages = new SparseArray<>();
4394                mChangedPackages.put(userId, changedPackages);
4395            }
4396            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4397            if (sequenceNumbers == null) {
4398                sequenceNumbers = new HashMap<>();
4399                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4400            }
4401            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4402            if (sequenceNumber != null) {
4403                changedPackages.remove(sequenceNumber);
4404            }
4405            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4406            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4407        }
4408        mChangedPackagesSequenceNumber++;
4409    }
4410
4411    @Override
4412    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4413        synchronized (mPackages) {
4414            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4415                return null;
4416            }
4417            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4418            if (changedPackages == null) {
4419                return null;
4420            }
4421            final List<String> packageNames =
4422                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4423            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4424                final String packageName = changedPackages.get(i);
4425                if (packageName != null) {
4426                    packageNames.add(packageName);
4427                }
4428            }
4429            return packageNames.isEmpty()
4430                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4431        }
4432    }
4433
4434    @Override
4435    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4436        ArrayList<FeatureInfo> res;
4437        synchronized (mAvailableFeatures) {
4438            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4439            res.addAll(mAvailableFeatures.values());
4440        }
4441        final FeatureInfo fi = new FeatureInfo();
4442        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4443                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4444        res.add(fi);
4445
4446        return new ParceledListSlice<>(res);
4447    }
4448
4449    @Override
4450    public boolean hasSystemFeature(String name, int version) {
4451        synchronized (mAvailableFeatures) {
4452            final FeatureInfo feat = mAvailableFeatures.get(name);
4453            if (feat == null) {
4454                return false;
4455            } else {
4456                return feat.version >= version;
4457            }
4458        }
4459    }
4460
4461    @Override
4462    public int checkPermission(String permName, String pkgName, int userId) {
4463        if (!sUserManager.exists(userId)) {
4464            return PackageManager.PERMISSION_DENIED;
4465        }
4466
4467        synchronized (mPackages) {
4468            final PackageParser.Package p = mPackages.get(pkgName);
4469            if (p != null && p.mExtras != null) {
4470                final PackageSetting ps = (PackageSetting) p.mExtras;
4471                final PermissionsState permissionsState = ps.getPermissionsState();
4472                if (permissionsState.hasPermission(permName, userId)) {
4473                    return PackageManager.PERMISSION_GRANTED;
4474                }
4475                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4476                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4477                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4478                    return PackageManager.PERMISSION_GRANTED;
4479                }
4480            }
4481        }
4482
4483        return PackageManager.PERMISSION_DENIED;
4484    }
4485
4486    @Override
4487    public int checkUidPermission(String permName, int uid) {
4488        final int userId = UserHandle.getUserId(uid);
4489
4490        if (!sUserManager.exists(userId)) {
4491            return PackageManager.PERMISSION_DENIED;
4492        }
4493
4494        synchronized (mPackages) {
4495            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4496            if (obj != null) {
4497                final SettingBase ps = (SettingBase) obj;
4498                final PermissionsState permissionsState = ps.getPermissionsState();
4499                if (permissionsState.hasPermission(permName, userId)) {
4500                    return PackageManager.PERMISSION_GRANTED;
4501                }
4502                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4503                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4504                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4505                    return PackageManager.PERMISSION_GRANTED;
4506                }
4507            } else {
4508                ArraySet<String> perms = mSystemPermissions.get(uid);
4509                if (perms != null) {
4510                    if (perms.contains(permName)) {
4511                        return PackageManager.PERMISSION_GRANTED;
4512                    }
4513                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4514                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4515                        return PackageManager.PERMISSION_GRANTED;
4516                    }
4517                }
4518            }
4519        }
4520
4521        return PackageManager.PERMISSION_DENIED;
4522    }
4523
4524    @Override
4525    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4526        if (UserHandle.getCallingUserId() != userId) {
4527            mContext.enforceCallingPermission(
4528                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4529                    "isPermissionRevokedByPolicy for user " + userId);
4530        }
4531
4532        if (checkPermission(permission, packageName, userId)
4533                == PackageManager.PERMISSION_GRANTED) {
4534            return false;
4535        }
4536
4537        final long identity = Binder.clearCallingIdentity();
4538        try {
4539            final int flags = getPermissionFlags(permission, packageName, userId);
4540            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4541        } finally {
4542            Binder.restoreCallingIdentity(identity);
4543        }
4544    }
4545
4546    @Override
4547    public String getPermissionControllerPackageName() {
4548        synchronized (mPackages) {
4549            return mRequiredInstallerPackage;
4550        }
4551    }
4552
4553    /**
4554     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4555     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4556     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4557     * @param message the message to log on security exception
4558     */
4559    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4560            boolean checkShell, String message) {
4561        if (userId < 0) {
4562            throw new IllegalArgumentException("Invalid userId " + userId);
4563        }
4564        if (checkShell) {
4565            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4566        }
4567        if (userId == UserHandle.getUserId(callingUid)) return;
4568        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4569            if (requireFullPermission) {
4570                mContext.enforceCallingOrSelfPermission(
4571                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4572            } else {
4573                try {
4574                    mContext.enforceCallingOrSelfPermission(
4575                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4576                } catch (SecurityException se) {
4577                    mContext.enforceCallingOrSelfPermission(
4578                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4579                }
4580            }
4581        }
4582    }
4583
4584    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4585        if (callingUid == Process.SHELL_UID) {
4586            if (userHandle >= 0
4587                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4588                throw new SecurityException("Shell does not have permission to access user "
4589                        + userHandle);
4590            } else if (userHandle < 0) {
4591                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4592                        + Debug.getCallers(3));
4593            }
4594        }
4595    }
4596
4597    private BasePermission findPermissionTreeLP(String permName) {
4598        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4599            if (permName.startsWith(bp.name) &&
4600                    permName.length() > bp.name.length() &&
4601                    permName.charAt(bp.name.length()) == '.') {
4602                return bp;
4603            }
4604        }
4605        return null;
4606    }
4607
4608    private BasePermission checkPermissionTreeLP(String permName) {
4609        if (permName != null) {
4610            BasePermission bp = findPermissionTreeLP(permName);
4611            if (bp != null) {
4612                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4613                    return bp;
4614                }
4615                throw new SecurityException("Calling uid "
4616                        + Binder.getCallingUid()
4617                        + " is not allowed to add to permission tree "
4618                        + bp.name + " owned by uid " + bp.uid);
4619            }
4620        }
4621        throw new SecurityException("No permission tree found for " + permName);
4622    }
4623
4624    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4625        if (s1 == null) {
4626            return s2 == null;
4627        }
4628        if (s2 == null) {
4629            return false;
4630        }
4631        if (s1.getClass() != s2.getClass()) {
4632            return false;
4633        }
4634        return s1.equals(s2);
4635    }
4636
4637    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4638        if (pi1.icon != pi2.icon) return false;
4639        if (pi1.logo != pi2.logo) return false;
4640        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4641        if (!compareStrings(pi1.name, pi2.name)) return false;
4642        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4643        // We'll take care of setting this one.
4644        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4645        // These are not currently stored in settings.
4646        //if (!compareStrings(pi1.group, pi2.group)) return false;
4647        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4648        //if (pi1.labelRes != pi2.labelRes) return false;
4649        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4650        return true;
4651    }
4652
4653    int permissionInfoFootprint(PermissionInfo info) {
4654        int size = info.name.length();
4655        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4656        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4657        return size;
4658    }
4659
4660    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4661        int size = 0;
4662        for (BasePermission perm : mSettings.mPermissions.values()) {
4663            if (perm.uid == tree.uid) {
4664                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4665            }
4666        }
4667        return size;
4668    }
4669
4670    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4671        // We calculate the max size of permissions defined by this uid and throw
4672        // if that plus the size of 'info' would exceed our stated maximum.
4673        if (tree.uid != Process.SYSTEM_UID) {
4674            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4675            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4676                throw new SecurityException("Permission tree size cap exceeded");
4677            }
4678        }
4679    }
4680
4681    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4682        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4683            throw new SecurityException("Label must be specified in permission");
4684        }
4685        BasePermission tree = checkPermissionTreeLP(info.name);
4686        BasePermission bp = mSettings.mPermissions.get(info.name);
4687        boolean added = bp == null;
4688        boolean changed = true;
4689        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4690        if (added) {
4691            enforcePermissionCapLocked(info, tree);
4692            bp = new BasePermission(info.name, tree.sourcePackage,
4693                    BasePermission.TYPE_DYNAMIC);
4694        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4695            throw new SecurityException(
4696                    "Not allowed to modify non-dynamic permission "
4697                    + info.name);
4698        } else {
4699            if (bp.protectionLevel == fixedLevel
4700                    && bp.perm.owner.equals(tree.perm.owner)
4701                    && bp.uid == tree.uid
4702                    && comparePermissionInfos(bp.perm.info, info)) {
4703                changed = false;
4704            }
4705        }
4706        bp.protectionLevel = fixedLevel;
4707        info = new PermissionInfo(info);
4708        info.protectionLevel = fixedLevel;
4709        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4710        bp.perm.info.packageName = tree.perm.info.packageName;
4711        bp.uid = tree.uid;
4712        if (added) {
4713            mSettings.mPermissions.put(info.name, bp);
4714        }
4715        if (changed) {
4716            if (!async) {
4717                mSettings.writeLPr();
4718            } else {
4719                scheduleWriteSettingsLocked();
4720            }
4721        }
4722        return added;
4723    }
4724
4725    @Override
4726    public boolean addPermission(PermissionInfo info) {
4727        synchronized (mPackages) {
4728            return addPermissionLocked(info, false);
4729        }
4730    }
4731
4732    @Override
4733    public boolean addPermissionAsync(PermissionInfo info) {
4734        synchronized (mPackages) {
4735            return addPermissionLocked(info, true);
4736        }
4737    }
4738
4739    @Override
4740    public void removePermission(String name) {
4741        synchronized (mPackages) {
4742            checkPermissionTreeLP(name);
4743            BasePermission bp = mSettings.mPermissions.get(name);
4744            if (bp != null) {
4745                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4746                    throw new SecurityException(
4747                            "Not allowed to modify non-dynamic permission "
4748                            + name);
4749                }
4750                mSettings.mPermissions.remove(name);
4751                mSettings.writeLPr();
4752            }
4753        }
4754    }
4755
4756    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4757            BasePermission bp) {
4758        int index = pkg.requestedPermissions.indexOf(bp.name);
4759        if (index == -1) {
4760            throw new SecurityException("Package " + pkg.packageName
4761                    + " has not requested permission " + bp.name);
4762        }
4763        if (!bp.isRuntime() && !bp.isDevelopment()) {
4764            throw new SecurityException("Permission " + bp.name
4765                    + " is not a changeable permission type");
4766        }
4767    }
4768
4769    @Override
4770    public void grantRuntimePermission(String packageName, String name, final int userId) {
4771        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4772    }
4773
4774    private void grantRuntimePermission(String packageName, String name, final int userId,
4775            boolean overridePolicy) {
4776        if (!sUserManager.exists(userId)) {
4777            Log.e(TAG, "No such user:" + userId);
4778            return;
4779        }
4780
4781        mContext.enforceCallingOrSelfPermission(
4782                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4783                "grantRuntimePermission");
4784
4785        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4786                true /* requireFullPermission */, true /* checkShell */,
4787                "grantRuntimePermission");
4788
4789        final int uid;
4790        final SettingBase sb;
4791
4792        synchronized (mPackages) {
4793            final PackageParser.Package pkg = mPackages.get(packageName);
4794            if (pkg == null) {
4795                throw new IllegalArgumentException("Unknown package: " + packageName);
4796            }
4797
4798            final BasePermission bp = mSettings.mPermissions.get(name);
4799            if (bp == null) {
4800                throw new IllegalArgumentException("Unknown permission: " + name);
4801            }
4802
4803            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4804
4805            // If a permission review is required for legacy apps we represent
4806            // their permissions as always granted runtime ones since we need
4807            // to keep the review required permission flag per user while an
4808            // install permission's state is shared across all users.
4809            if (mPermissionReviewRequired
4810                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4811                    && bp.isRuntime()) {
4812                return;
4813            }
4814
4815            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4816            sb = (SettingBase) pkg.mExtras;
4817            if (sb == null) {
4818                throw new IllegalArgumentException("Unknown package: " + packageName);
4819            }
4820
4821            final PermissionsState permissionsState = sb.getPermissionsState();
4822
4823            final int flags = permissionsState.getPermissionFlags(name, userId);
4824            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4825                throw new SecurityException("Cannot grant system fixed permission "
4826                        + name + " for package " + packageName);
4827            }
4828            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4829                throw new SecurityException("Cannot grant policy fixed permission "
4830                        + name + " for package " + packageName);
4831            }
4832
4833            if (bp.isDevelopment()) {
4834                // Development permissions must be handled specially, since they are not
4835                // normal runtime permissions.  For now they apply to all users.
4836                if (permissionsState.grantInstallPermission(bp) !=
4837                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4838                    scheduleWriteSettingsLocked();
4839                }
4840                return;
4841            }
4842
4843            final PackageSetting ps = mSettings.mPackages.get(packageName);
4844            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4845                throw new SecurityException("Cannot grant non-ephemeral permission"
4846                        + name + " for package " + packageName);
4847            }
4848
4849            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4850                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4851                return;
4852            }
4853
4854            final int result = permissionsState.grantRuntimePermission(bp, userId);
4855            switch (result) {
4856                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4857                    return;
4858                }
4859
4860                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4861                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4862                    mHandler.post(new Runnable() {
4863                        @Override
4864                        public void run() {
4865                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4866                        }
4867                    });
4868                }
4869                break;
4870            }
4871
4872            if (bp.isRuntime()) {
4873                logPermissionGranted(mContext, name, packageName);
4874            }
4875
4876            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4877
4878            // Not critical if that is lost - app has to request again.
4879            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4880        }
4881
4882        // Only need to do this if user is initialized. Otherwise it's a new user
4883        // and there are no processes running as the user yet and there's no need
4884        // to make an expensive call to remount processes for the changed permissions.
4885        if (READ_EXTERNAL_STORAGE.equals(name)
4886                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4887            final long token = Binder.clearCallingIdentity();
4888            try {
4889                if (sUserManager.isInitialized(userId)) {
4890                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4891                            StorageManagerInternal.class);
4892                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4893                }
4894            } finally {
4895                Binder.restoreCallingIdentity(token);
4896            }
4897        }
4898    }
4899
4900    @Override
4901    public void revokeRuntimePermission(String packageName, String name, int userId) {
4902        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4903    }
4904
4905    private void revokeRuntimePermission(String packageName, String name, int userId,
4906            boolean overridePolicy) {
4907        if (!sUserManager.exists(userId)) {
4908            Log.e(TAG, "No such user:" + userId);
4909            return;
4910        }
4911
4912        mContext.enforceCallingOrSelfPermission(
4913                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4914                "revokeRuntimePermission");
4915
4916        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4917                true /* requireFullPermission */, true /* checkShell */,
4918                "revokeRuntimePermission");
4919
4920        final int appId;
4921
4922        synchronized (mPackages) {
4923            final PackageParser.Package pkg = mPackages.get(packageName);
4924            if (pkg == null) {
4925                throw new IllegalArgumentException("Unknown package: " + packageName);
4926            }
4927
4928            final BasePermission bp = mSettings.mPermissions.get(name);
4929            if (bp == null) {
4930                throw new IllegalArgumentException("Unknown permission: " + name);
4931            }
4932
4933            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4934
4935            // If a permission review is required for legacy apps we represent
4936            // their permissions as always granted runtime ones since we need
4937            // to keep the review required permission flag per user while an
4938            // install permission's state is shared across all users.
4939            if (mPermissionReviewRequired
4940                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4941                    && bp.isRuntime()) {
4942                return;
4943            }
4944
4945            SettingBase sb = (SettingBase) pkg.mExtras;
4946            if (sb == null) {
4947                throw new IllegalArgumentException("Unknown package: " + packageName);
4948            }
4949
4950            final PermissionsState permissionsState = sb.getPermissionsState();
4951
4952            final int flags = permissionsState.getPermissionFlags(name, userId);
4953            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4954                throw new SecurityException("Cannot revoke system fixed permission "
4955                        + name + " for package " + packageName);
4956            }
4957            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4958                throw new SecurityException("Cannot revoke policy fixed permission "
4959                        + name + " for package " + packageName);
4960            }
4961
4962            if (bp.isDevelopment()) {
4963                // Development permissions must be handled specially, since they are not
4964                // normal runtime permissions.  For now they apply to all users.
4965                if (permissionsState.revokeInstallPermission(bp) !=
4966                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4967                    scheduleWriteSettingsLocked();
4968                }
4969                return;
4970            }
4971
4972            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4973                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4974                return;
4975            }
4976
4977            if (bp.isRuntime()) {
4978                logPermissionRevoked(mContext, name, packageName);
4979            }
4980
4981            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4982
4983            // Critical, after this call app should never have the permission.
4984            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4985
4986            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4987        }
4988
4989        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4990    }
4991
4992    /**
4993     * Get the first event id for the permission.
4994     *
4995     * <p>There are four events for each permission: <ul>
4996     *     <li>Request permission: first id + 0</li>
4997     *     <li>Grant permission: first id + 1</li>
4998     *     <li>Request for permission denied: first id + 2</li>
4999     *     <li>Revoke permission: first id + 3</li>
5000     * </ul></p>
5001     *
5002     * @param name name of the permission
5003     *
5004     * @return The first event id for the permission
5005     */
5006    private static int getBaseEventId(@NonNull String name) {
5007        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5008
5009        if (eventIdIndex == -1) {
5010            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5011                    || "user".equals(Build.TYPE)) {
5012                Log.i(TAG, "Unknown permission " + name);
5013
5014                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5015            } else {
5016                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5017                //
5018                // Also update
5019                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5020                // - metrics_constants.proto
5021                throw new IllegalStateException("Unknown permission " + name);
5022            }
5023        }
5024
5025        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5026    }
5027
5028    /**
5029     * Log that a permission was revoked.
5030     *
5031     * @param context Context of the caller
5032     * @param name name of the permission
5033     * @param packageName package permission if for
5034     */
5035    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5036            @NonNull String packageName) {
5037        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5038    }
5039
5040    /**
5041     * Log that a permission request was granted.
5042     *
5043     * @param context Context of the caller
5044     * @param name name of the permission
5045     * @param packageName package permission if for
5046     */
5047    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5048            @NonNull String packageName) {
5049        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5050    }
5051
5052    @Override
5053    public void resetRuntimePermissions() {
5054        mContext.enforceCallingOrSelfPermission(
5055                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5056                "revokeRuntimePermission");
5057
5058        int callingUid = Binder.getCallingUid();
5059        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5060            mContext.enforceCallingOrSelfPermission(
5061                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5062                    "resetRuntimePermissions");
5063        }
5064
5065        synchronized (mPackages) {
5066            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5067            for (int userId : UserManagerService.getInstance().getUserIds()) {
5068                final int packageCount = mPackages.size();
5069                for (int i = 0; i < packageCount; i++) {
5070                    PackageParser.Package pkg = mPackages.valueAt(i);
5071                    if (!(pkg.mExtras instanceof PackageSetting)) {
5072                        continue;
5073                    }
5074                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5075                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5076                }
5077            }
5078        }
5079    }
5080
5081    @Override
5082    public int getPermissionFlags(String name, String packageName, int userId) {
5083        if (!sUserManager.exists(userId)) {
5084            return 0;
5085        }
5086
5087        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5088
5089        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5090                true /* requireFullPermission */, false /* checkShell */,
5091                "getPermissionFlags");
5092
5093        synchronized (mPackages) {
5094            final PackageParser.Package pkg = mPackages.get(packageName);
5095            if (pkg == null) {
5096                return 0;
5097            }
5098
5099            final BasePermission bp = mSettings.mPermissions.get(name);
5100            if (bp == null) {
5101                return 0;
5102            }
5103
5104            SettingBase sb = (SettingBase) pkg.mExtras;
5105            if (sb == null) {
5106                return 0;
5107            }
5108
5109            PermissionsState permissionsState = sb.getPermissionsState();
5110            return permissionsState.getPermissionFlags(name, userId);
5111        }
5112    }
5113
5114    @Override
5115    public void updatePermissionFlags(String name, String packageName, int flagMask,
5116            int flagValues, int userId) {
5117        if (!sUserManager.exists(userId)) {
5118            return;
5119        }
5120
5121        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5122
5123        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5124                true /* requireFullPermission */, true /* checkShell */,
5125                "updatePermissionFlags");
5126
5127        // Only the system can change these flags and nothing else.
5128        if (getCallingUid() != Process.SYSTEM_UID) {
5129            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5130            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5131            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5132            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5133            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5134        }
5135
5136        synchronized (mPackages) {
5137            final PackageParser.Package pkg = mPackages.get(packageName);
5138            if (pkg == null) {
5139                throw new IllegalArgumentException("Unknown package: " + packageName);
5140            }
5141
5142            final BasePermission bp = mSettings.mPermissions.get(name);
5143            if (bp == null) {
5144                throw new IllegalArgumentException("Unknown permission: " + name);
5145            }
5146
5147            SettingBase sb = (SettingBase) pkg.mExtras;
5148            if (sb == null) {
5149                throw new IllegalArgumentException("Unknown package: " + packageName);
5150            }
5151
5152            PermissionsState permissionsState = sb.getPermissionsState();
5153
5154            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5155
5156            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5157                // Install and runtime permissions are stored in different places,
5158                // so figure out what permission changed and persist the change.
5159                if (permissionsState.getInstallPermissionState(name) != null) {
5160                    scheduleWriteSettingsLocked();
5161                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5162                        || hadState) {
5163                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5164                }
5165            }
5166        }
5167    }
5168
5169    /**
5170     * Update the permission flags for all packages and runtime permissions of a user in order
5171     * to allow device or profile owner to remove POLICY_FIXED.
5172     */
5173    @Override
5174    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5175        if (!sUserManager.exists(userId)) {
5176            return;
5177        }
5178
5179        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5180
5181        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5182                true /* requireFullPermission */, true /* checkShell */,
5183                "updatePermissionFlagsForAllApps");
5184
5185        // Only the system can change system fixed flags.
5186        if (getCallingUid() != Process.SYSTEM_UID) {
5187            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5188            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5189        }
5190
5191        synchronized (mPackages) {
5192            boolean changed = false;
5193            final int packageCount = mPackages.size();
5194            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5195                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5196                SettingBase sb = (SettingBase) pkg.mExtras;
5197                if (sb == null) {
5198                    continue;
5199                }
5200                PermissionsState permissionsState = sb.getPermissionsState();
5201                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5202                        userId, flagMask, flagValues);
5203            }
5204            if (changed) {
5205                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5206            }
5207        }
5208    }
5209
5210    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5211        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5212                != PackageManager.PERMISSION_GRANTED
5213            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5214                != PackageManager.PERMISSION_GRANTED) {
5215            throw new SecurityException(message + " requires "
5216                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5217                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5218        }
5219    }
5220
5221    @Override
5222    public boolean shouldShowRequestPermissionRationale(String permissionName,
5223            String packageName, int userId) {
5224        if (UserHandle.getCallingUserId() != userId) {
5225            mContext.enforceCallingPermission(
5226                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5227                    "canShowRequestPermissionRationale for user " + userId);
5228        }
5229
5230        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5231        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5232            return false;
5233        }
5234
5235        if (checkPermission(permissionName, packageName, userId)
5236                == PackageManager.PERMISSION_GRANTED) {
5237            return false;
5238        }
5239
5240        final int flags;
5241
5242        final long identity = Binder.clearCallingIdentity();
5243        try {
5244            flags = getPermissionFlags(permissionName,
5245                    packageName, userId);
5246        } finally {
5247            Binder.restoreCallingIdentity(identity);
5248        }
5249
5250        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5251                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5252                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5253
5254        if ((flags & fixedFlags) != 0) {
5255            return false;
5256        }
5257
5258        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5259    }
5260
5261    @Override
5262    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5263        mContext.enforceCallingOrSelfPermission(
5264                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5265                "addOnPermissionsChangeListener");
5266
5267        synchronized (mPackages) {
5268            mOnPermissionChangeListeners.addListenerLocked(listener);
5269        }
5270    }
5271
5272    @Override
5273    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5274        synchronized (mPackages) {
5275            mOnPermissionChangeListeners.removeListenerLocked(listener);
5276        }
5277    }
5278
5279    @Override
5280    public boolean isProtectedBroadcast(String actionName) {
5281        synchronized (mPackages) {
5282            if (mProtectedBroadcasts.contains(actionName)) {
5283                return true;
5284            } else if (actionName != null) {
5285                // TODO: remove these terrible hacks
5286                if (actionName.startsWith("android.net.netmon.lingerExpired")
5287                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5288                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5289                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5290                    return true;
5291                }
5292            }
5293        }
5294        return false;
5295    }
5296
5297    @Override
5298    public int checkSignatures(String pkg1, String pkg2) {
5299        synchronized (mPackages) {
5300            final PackageParser.Package p1 = mPackages.get(pkg1);
5301            final PackageParser.Package p2 = mPackages.get(pkg2);
5302            if (p1 == null || p1.mExtras == null
5303                    || p2 == null || p2.mExtras == null) {
5304                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5305            }
5306            return compareSignatures(p1.mSignatures, p2.mSignatures);
5307        }
5308    }
5309
5310    @Override
5311    public int checkUidSignatures(int uid1, int uid2) {
5312        // Map to base uids.
5313        uid1 = UserHandle.getAppId(uid1);
5314        uid2 = UserHandle.getAppId(uid2);
5315        // reader
5316        synchronized (mPackages) {
5317            Signature[] s1;
5318            Signature[] s2;
5319            Object obj = mSettings.getUserIdLPr(uid1);
5320            if (obj != null) {
5321                if (obj instanceof SharedUserSetting) {
5322                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5323                } else if (obj instanceof PackageSetting) {
5324                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5325                } else {
5326                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5327                }
5328            } else {
5329                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5330            }
5331            obj = mSettings.getUserIdLPr(uid2);
5332            if (obj != null) {
5333                if (obj instanceof SharedUserSetting) {
5334                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5335                } else if (obj instanceof PackageSetting) {
5336                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5337                } else {
5338                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5339                }
5340            } else {
5341                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5342            }
5343            return compareSignatures(s1, s2);
5344        }
5345    }
5346
5347    /**
5348     * This method should typically only be used when granting or revoking
5349     * permissions, since the app may immediately restart after this call.
5350     * <p>
5351     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5352     * guard your work against the app being relaunched.
5353     */
5354    private void killUid(int appId, int userId, String reason) {
5355        final long identity = Binder.clearCallingIdentity();
5356        try {
5357            IActivityManager am = ActivityManager.getService();
5358            if (am != null) {
5359                try {
5360                    am.killUid(appId, userId, reason);
5361                } catch (RemoteException e) {
5362                    /* ignore - same process */
5363                }
5364            }
5365        } finally {
5366            Binder.restoreCallingIdentity(identity);
5367        }
5368    }
5369
5370    /**
5371     * Compares two sets of signatures. Returns:
5372     * <br />
5373     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5374     * <br />
5375     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5376     * <br />
5377     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5378     * <br />
5379     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5380     * <br />
5381     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5382     */
5383    static int compareSignatures(Signature[] s1, Signature[] s2) {
5384        if (s1 == null) {
5385            return s2 == null
5386                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5387                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5388        }
5389
5390        if (s2 == null) {
5391            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5392        }
5393
5394        if (s1.length != s2.length) {
5395            return PackageManager.SIGNATURE_NO_MATCH;
5396        }
5397
5398        // Since both signature sets are of size 1, we can compare without HashSets.
5399        if (s1.length == 1) {
5400            return s1[0].equals(s2[0]) ?
5401                    PackageManager.SIGNATURE_MATCH :
5402                    PackageManager.SIGNATURE_NO_MATCH;
5403        }
5404
5405        ArraySet<Signature> set1 = new ArraySet<Signature>();
5406        for (Signature sig : s1) {
5407            set1.add(sig);
5408        }
5409        ArraySet<Signature> set2 = new ArraySet<Signature>();
5410        for (Signature sig : s2) {
5411            set2.add(sig);
5412        }
5413        // Make sure s2 contains all signatures in s1.
5414        if (set1.equals(set2)) {
5415            return PackageManager.SIGNATURE_MATCH;
5416        }
5417        return PackageManager.SIGNATURE_NO_MATCH;
5418    }
5419
5420    /**
5421     * If the database version for this type of package (internal storage or
5422     * external storage) is less than the version where package signatures
5423     * were updated, return true.
5424     */
5425    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5426        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5427        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5428    }
5429
5430    /**
5431     * Used for backward compatibility to make sure any packages with
5432     * certificate chains get upgraded to the new style. {@code existingSigs}
5433     * will be in the old format (since they were stored on disk from before the
5434     * system upgrade) and {@code scannedSigs} will be in the newer format.
5435     */
5436    private int compareSignaturesCompat(PackageSignatures existingSigs,
5437            PackageParser.Package scannedPkg) {
5438        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5439            return PackageManager.SIGNATURE_NO_MATCH;
5440        }
5441
5442        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5443        for (Signature sig : existingSigs.mSignatures) {
5444            existingSet.add(sig);
5445        }
5446        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5447        for (Signature sig : scannedPkg.mSignatures) {
5448            try {
5449                Signature[] chainSignatures = sig.getChainSignatures();
5450                for (Signature chainSig : chainSignatures) {
5451                    scannedCompatSet.add(chainSig);
5452                }
5453            } catch (CertificateEncodingException e) {
5454                scannedCompatSet.add(sig);
5455            }
5456        }
5457        /*
5458         * Make sure the expanded scanned set contains all signatures in the
5459         * existing one.
5460         */
5461        if (scannedCompatSet.equals(existingSet)) {
5462            // Migrate the old signatures to the new scheme.
5463            existingSigs.assignSignatures(scannedPkg.mSignatures);
5464            // The new KeySets will be re-added later in the scanning process.
5465            synchronized (mPackages) {
5466                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5467            }
5468            return PackageManager.SIGNATURE_MATCH;
5469        }
5470        return PackageManager.SIGNATURE_NO_MATCH;
5471    }
5472
5473    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5474        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5475        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5476    }
5477
5478    private int compareSignaturesRecover(PackageSignatures existingSigs,
5479            PackageParser.Package scannedPkg) {
5480        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5481            return PackageManager.SIGNATURE_NO_MATCH;
5482        }
5483
5484        String msg = null;
5485        try {
5486            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5487                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5488                        + scannedPkg.packageName);
5489                return PackageManager.SIGNATURE_MATCH;
5490            }
5491        } catch (CertificateException e) {
5492            msg = e.getMessage();
5493        }
5494
5495        logCriticalInfo(Log.INFO,
5496                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5497        return PackageManager.SIGNATURE_NO_MATCH;
5498    }
5499
5500    @Override
5501    public List<String> getAllPackages() {
5502        synchronized (mPackages) {
5503            return new ArrayList<String>(mPackages.keySet());
5504        }
5505    }
5506
5507    @Override
5508    public String[] getPackagesForUid(int uid) {
5509        final int userId = UserHandle.getUserId(uid);
5510        uid = UserHandle.getAppId(uid);
5511        // reader
5512        synchronized (mPackages) {
5513            Object obj = mSettings.getUserIdLPr(uid);
5514            if (obj instanceof SharedUserSetting) {
5515                final SharedUserSetting sus = (SharedUserSetting) obj;
5516                final int N = sus.packages.size();
5517                String[] res = new String[N];
5518                final Iterator<PackageSetting> it = sus.packages.iterator();
5519                int i = 0;
5520                while (it.hasNext()) {
5521                    PackageSetting ps = it.next();
5522                    if (ps.getInstalled(userId)) {
5523                        res[i++] = ps.name;
5524                    } else {
5525                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5526                    }
5527                }
5528                return res;
5529            } else if (obj instanceof PackageSetting) {
5530                final PackageSetting ps = (PackageSetting) obj;
5531                if (ps.getInstalled(userId)) {
5532                    return new String[]{ps.name};
5533                }
5534            }
5535        }
5536        return null;
5537    }
5538
5539    @Override
5540    public String getNameForUid(int uid) {
5541        // reader
5542        synchronized (mPackages) {
5543            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5544            if (obj instanceof SharedUserSetting) {
5545                final SharedUserSetting sus = (SharedUserSetting) obj;
5546                return sus.name + ":" + sus.userId;
5547            } else if (obj instanceof PackageSetting) {
5548                final PackageSetting ps = (PackageSetting) obj;
5549                return ps.name;
5550            }
5551        }
5552        return null;
5553    }
5554
5555    @Override
5556    public int getUidForSharedUser(String sharedUserName) {
5557        if(sharedUserName == null) {
5558            return -1;
5559        }
5560        // reader
5561        synchronized (mPackages) {
5562            SharedUserSetting suid;
5563            try {
5564                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5565                if (suid != null) {
5566                    return suid.userId;
5567                }
5568            } catch (PackageManagerException ignore) {
5569                // can't happen, but, still need to catch it
5570            }
5571            return -1;
5572        }
5573    }
5574
5575    @Override
5576    public int getFlagsForUid(int uid) {
5577        synchronized (mPackages) {
5578            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5579            if (obj instanceof SharedUserSetting) {
5580                final SharedUserSetting sus = (SharedUserSetting) obj;
5581                return sus.pkgFlags;
5582            } else if (obj instanceof PackageSetting) {
5583                final PackageSetting ps = (PackageSetting) obj;
5584                return ps.pkgFlags;
5585            }
5586        }
5587        return 0;
5588    }
5589
5590    @Override
5591    public int getPrivateFlagsForUid(int uid) {
5592        synchronized (mPackages) {
5593            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5594            if (obj instanceof SharedUserSetting) {
5595                final SharedUserSetting sus = (SharedUserSetting) obj;
5596                return sus.pkgPrivateFlags;
5597            } else if (obj instanceof PackageSetting) {
5598                final PackageSetting ps = (PackageSetting) obj;
5599                return ps.pkgPrivateFlags;
5600            }
5601        }
5602        return 0;
5603    }
5604
5605    @Override
5606    public boolean isUidPrivileged(int uid) {
5607        uid = UserHandle.getAppId(uid);
5608        // reader
5609        synchronized (mPackages) {
5610            Object obj = mSettings.getUserIdLPr(uid);
5611            if (obj instanceof SharedUserSetting) {
5612                final SharedUserSetting sus = (SharedUserSetting) obj;
5613                final Iterator<PackageSetting> it = sus.packages.iterator();
5614                while (it.hasNext()) {
5615                    if (it.next().isPrivileged()) {
5616                        return true;
5617                    }
5618                }
5619            } else if (obj instanceof PackageSetting) {
5620                final PackageSetting ps = (PackageSetting) obj;
5621                return ps.isPrivileged();
5622            }
5623        }
5624        return false;
5625    }
5626
5627    @Override
5628    public String[] getAppOpPermissionPackages(String permissionName) {
5629        synchronized (mPackages) {
5630            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5631            if (pkgs == null) {
5632                return null;
5633            }
5634            return pkgs.toArray(new String[pkgs.size()]);
5635        }
5636    }
5637
5638    @Override
5639    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5640            int flags, int userId) {
5641        return resolveIntentInternal(
5642                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
5643    }
5644
5645    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5646            int flags, int userId, boolean includeInstantApps) {
5647        try {
5648            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5649
5650            if (!sUserManager.exists(userId)) return null;
5651            final int callingUid = Binder.getCallingUid();
5652            flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
5653            enforceCrossUserPermission(callingUid, userId,
5654                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5655
5656            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5657            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5658                    flags, userId, includeInstantApps);
5659            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5660
5661            final ResolveInfo bestChoice =
5662                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5663            return bestChoice;
5664        } finally {
5665            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5666        }
5667    }
5668
5669    @Override
5670    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5671        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5672            throw new SecurityException(
5673                    "findPersistentPreferredActivity can only be run by the system");
5674        }
5675        if (!sUserManager.exists(userId)) {
5676            return null;
5677        }
5678        final int callingUid = Binder.getCallingUid();
5679        intent = updateIntentForResolve(intent);
5680        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5681        final int flags = updateFlagsForResolve(
5682                0, userId, intent, callingUid, false /*includeInstantApps*/);
5683        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5684                userId);
5685        synchronized (mPackages) {
5686            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5687                    userId);
5688        }
5689    }
5690
5691    @Override
5692    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5693            IntentFilter filter, int match, ComponentName activity) {
5694        final int userId = UserHandle.getCallingUserId();
5695        if (DEBUG_PREFERRED) {
5696            Log.v(TAG, "setLastChosenActivity intent=" + intent
5697                + " resolvedType=" + resolvedType
5698                + " flags=" + flags
5699                + " filter=" + filter
5700                + " match=" + match
5701                + " activity=" + activity);
5702            filter.dump(new PrintStreamPrinter(System.out), "    ");
5703        }
5704        intent.setComponent(null);
5705        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5706                userId);
5707        // Find any earlier preferred or last chosen entries and nuke them
5708        findPreferredActivity(intent, resolvedType,
5709                flags, query, 0, false, true, false, userId);
5710        // Add the new activity as the last chosen for this filter
5711        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5712                "Setting last chosen");
5713    }
5714
5715    @Override
5716    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5717        final int userId = UserHandle.getCallingUserId();
5718        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5719        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5720                userId);
5721        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5722                false, false, false, userId);
5723    }
5724
5725    /**
5726     * Returns whether or not instant apps have been disabled remotely.
5727     */
5728    private boolean isEphemeralDisabled() {
5729        return mEphemeralAppsDisabled;
5730    }
5731
5732    private boolean isEphemeralAllowed(
5733            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5734            boolean skipPackageCheck) {
5735        final int callingUser = UserHandle.getCallingUserId();
5736        if (mInstantAppResolverConnection == null) {
5737            return false;
5738        }
5739        if (mInstantAppInstallerActivity == null) {
5740            return false;
5741        }
5742        if (intent.getComponent() != null) {
5743            return false;
5744        }
5745        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5746            return false;
5747        }
5748        if (!skipPackageCheck && intent.getPackage() != null) {
5749            return false;
5750        }
5751        final boolean isWebUri = hasWebURI(intent);
5752        if (!isWebUri || intent.getData().getHost() == null) {
5753            return false;
5754        }
5755        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5756        // Or if there's already an ephemeral app installed that handles the action
5757        synchronized (mPackages) {
5758            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5759            for (int n = 0; n < count; n++) {
5760                final ResolveInfo info = resolvedActivities.get(n);
5761                final String packageName = info.activityInfo.packageName;
5762                final PackageSetting ps = mSettings.mPackages.get(packageName);
5763                if (ps != null) {
5764                    // only check domain verification status if the app is not a browser
5765                    if (!info.handleAllWebDataURI) {
5766                        // Try to get the status from User settings first
5767                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5768                        final int status = (int) (packedStatus >> 32);
5769                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5770                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5771                            if (DEBUG_EPHEMERAL) {
5772                                Slog.v(TAG, "DENY instant app;"
5773                                    + " pkg: " + packageName + ", status: " + status);
5774                            }
5775                            return false;
5776                        }
5777                    }
5778                    if (ps.getInstantApp(userId)) {
5779                        if (DEBUG_EPHEMERAL) {
5780                            Slog.v(TAG, "DENY instant app installed;"
5781                                    + " pkg: " + packageName);
5782                        }
5783                        return false;
5784                    }
5785                }
5786            }
5787        }
5788        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5789        return true;
5790    }
5791
5792    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5793            Intent origIntent, String resolvedType, String callingPackage,
5794            int userId) {
5795        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5796                new InstantAppRequest(responseObj, origIntent, resolvedType,
5797                        callingPackage, userId));
5798        mHandler.sendMessage(msg);
5799    }
5800
5801    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5802            int flags, List<ResolveInfo> query, int userId) {
5803        if (query != null) {
5804            final int N = query.size();
5805            if (N == 1) {
5806                return query.get(0);
5807            } else if (N > 1) {
5808                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5809                // If there is more than one activity with the same priority,
5810                // then let the user decide between them.
5811                ResolveInfo r0 = query.get(0);
5812                ResolveInfo r1 = query.get(1);
5813                if (DEBUG_INTENT_MATCHING || debug) {
5814                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5815                            + r1.activityInfo.name + "=" + r1.priority);
5816                }
5817                // If the first activity has a higher priority, or a different
5818                // default, then it is always desirable to pick it.
5819                if (r0.priority != r1.priority
5820                        || r0.preferredOrder != r1.preferredOrder
5821                        || r0.isDefault != r1.isDefault) {
5822                    return query.get(0);
5823                }
5824                // If we have saved a preference for a preferred activity for
5825                // this Intent, use that.
5826                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5827                        flags, query, r0.priority, true, false, debug, userId);
5828                if (ri != null) {
5829                    return ri;
5830                }
5831                // If we have an ephemeral app, use it
5832                for (int i = 0; i < N; i++) {
5833                    ri = query.get(i);
5834                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5835                        return ri;
5836                    }
5837                }
5838                ri = new ResolveInfo(mResolveInfo);
5839                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5840                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5841                // If all of the options come from the same package, show the application's
5842                // label and icon instead of the generic resolver's.
5843                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5844                // and then throw away the ResolveInfo itself, meaning that the caller loses
5845                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5846                // a fallback for this case; we only set the target package's resources on
5847                // the ResolveInfo, not the ActivityInfo.
5848                final String intentPackage = intent.getPackage();
5849                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5850                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5851                    ri.resolvePackageName = intentPackage;
5852                    if (userNeedsBadging(userId)) {
5853                        ri.noResourceId = true;
5854                    } else {
5855                        ri.icon = appi.icon;
5856                    }
5857                    ri.iconResourceId = appi.icon;
5858                    ri.labelRes = appi.labelRes;
5859                }
5860                ri.activityInfo.applicationInfo = new ApplicationInfo(
5861                        ri.activityInfo.applicationInfo);
5862                if (userId != 0) {
5863                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5864                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5865                }
5866                // Make sure that the resolver is displayable in car mode
5867                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5868                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5869                return ri;
5870            }
5871        }
5872        return null;
5873    }
5874
5875    /**
5876     * Return true if the given list is not empty and all of its contents have
5877     * an activityInfo with the given package name.
5878     */
5879    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5880        if (ArrayUtils.isEmpty(list)) {
5881            return false;
5882        }
5883        for (int i = 0, N = list.size(); i < N; i++) {
5884            final ResolveInfo ri = list.get(i);
5885            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5886            if (ai == null || !packageName.equals(ai.packageName)) {
5887                return false;
5888            }
5889        }
5890        return true;
5891    }
5892
5893    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5894            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5895        final int N = query.size();
5896        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5897                .get(userId);
5898        // Get the list of persistent preferred activities that handle the intent
5899        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5900        List<PersistentPreferredActivity> pprefs = ppir != null
5901                ? ppir.queryIntent(intent, resolvedType,
5902                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5903                        userId)
5904                : null;
5905        if (pprefs != null && pprefs.size() > 0) {
5906            final int M = pprefs.size();
5907            for (int i=0; i<M; i++) {
5908                final PersistentPreferredActivity ppa = pprefs.get(i);
5909                if (DEBUG_PREFERRED || debug) {
5910                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5911                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5912                            + "\n  component=" + ppa.mComponent);
5913                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5914                }
5915                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5916                        flags | MATCH_DISABLED_COMPONENTS, userId);
5917                if (DEBUG_PREFERRED || debug) {
5918                    Slog.v(TAG, "Found persistent preferred activity:");
5919                    if (ai != null) {
5920                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5921                    } else {
5922                        Slog.v(TAG, "  null");
5923                    }
5924                }
5925                if (ai == null) {
5926                    // This previously registered persistent preferred activity
5927                    // component is no longer known. Ignore it and do NOT remove it.
5928                    continue;
5929                }
5930                for (int j=0; j<N; j++) {
5931                    final ResolveInfo ri = query.get(j);
5932                    if (!ri.activityInfo.applicationInfo.packageName
5933                            .equals(ai.applicationInfo.packageName)) {
5934                        continue;
5935                    }
5936                    if (!ri.activityInfo.name.equals(ai.name)) {
5937                        continue;
5938                    }
5939                    //  Found a persistent preference that can handle the intent.
5940                    if (DEBUG_PREFERRED || debug) {
5941                        Slog.v(TAG, "Returning persistent preferred activity: " +
5942                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5943                    }
5944                    return ri;
5945                }
5946            }
5947        }
5948        return null;
5949    }
5950
5951    // TODO: handle preferred activities missing while user has amnesia
5952    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5953            List<ResolveInfo> query, int priority, boolean always,
5954            boolean removeMatches, boolean debug, int userId) {
5955        if (!sUserManager.exists(userId)) return null;
5956        final int callingUid = Binder.getCallingUid();
5957        flags = updateFlagsForResolve(
5958                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5959        intent = updateIntentForResolve(intent);
5960        // writer
5961        synchronized (mPackages) {
5962            // Try to find a matching persistent preferred activity.
5963            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5964                    debug, userId);
5965
5966            // If a persistent preferred activity matched, use it.
5967            if (pri != null) {
5968                return pri;
5969            }
5970
5971            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5972            // Get the list of preferred activities that handle the intent
5973            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5974            List<PreferredActivity> prefs = pir != null
5975                    ? pir.queryIntent(intent, resolvedType,
5976                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5977                            userId)
5978                    : null;
5979            if (prefs != null && prefs.size() > 0) {
5980                boolean changed = false;
5981                try {
5982                    // First figure out how good the original match set is.
5983                    // We will only allow preferred activities that came
5984                    // from the same match quality.
5985                    int match = 0;
5986
5987                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5988
5989                    final int N = query.size();
5990                    for (int j=0; j<N; j++) {
5991                        final ResolveInfo ri = query.get(j);
5992                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5993                                + ": 0x" + Integer.toHexString(match));
5994                        if (ri.match > match) {
5995                            match = ri.match;
5996                        }
5997                    }
5998
5999                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6000                            + Integer.toHexString(match));
6001
6002                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6003                    final int M = prefs.size();
6004                    for (int i=0; i<M; i++) {
6005                        final PreferredActivity pa = prefs.get(i);
6006                        if (DEBUG_PREFERRED || debug) {
6007                            Slog.v(TAG, "Checking PreferredActivity ds="
6008                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6009                                    + "\n  component=" + pa.mPref.mComponent);
6010                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6011                        }
6012                        if (pa.mPref.mMatch != match) {
6013                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6014                                    + Integer.toHexString(pa.mPref.mMatch));
6015                            continue;
6016                        }
6017                        // If it's not an "always" type preferred activity and that's what we're
6018                        // looking for, skip it.
6019                        if (always && !pa.mPref.mAlways) {
6020                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6021                            continue;
6022                        }
6023                        final ActivityInfo ai = getActivityInfo(
6024                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6025                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6026                                userId);
6027                        if (DEBUG_PREFERRED || debug) {
6028                            Slog.v(TAG, "Found preferred activity:");
6029                            if (ai != null) {
6030                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6031                            } else {
6032                                Slog.v(TAG, "  null");
6033                            }
6034                        }
6035                        if (ai == null) {
6036                            // This previously registered preferred activity
6037                            // component is no longer known.  Most likely an update
6038                            // to the app was installed and in the new version this
6039                            // component no longer exists.  Clean it up by removing
6040                            // it from the preferred activities list, and skip it.
6041                            Slog.w(TAG, "Removing dangling preferred activity: "
6042                                    + pa.mPref.mComponent);
6043                            pir.removeFilter(pa);
6044                            changed = true;
6045                            continue;
6046                        }
6047                        for (int j=0; j<N; j++) {
6048                            final ResolveInfo ri = query.get(j);
6049                            if (!ri.activityInfo.applicationInfo.packageName
6050                                    .equals(ai.applicationInfo.packageName)) {
6051                                continue;
6052                            }
6053                            if (!ri.activityInfo.name.equals(ai.name)) {
6054                                continue;
6055                            }
6056
6057                            if (removeMatches) {
6058                                pir.removeFilter(pa);
6059                                changed = true;
6060                                if (DEBUG_PREFERRED) {
6061                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6062                                }
6063                                break;
6064                            }
6065
6066                            // Okay we found a previously set preferred or last chosen app.
6067                            // If the result set is different from when this
6068                            // was created, we need to clear it and re-ask the
6069                            // user their preference, if we're looking for an "always" type entry.
6070                            if (always && !pa.mPref.sameSet(query)) {
6071                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6072                                        + intent + " type " + resolvedType);
6073                                if (DEBUG_PREFERRED) {
6074                                    Slog.v(TAG, "Removing preferred activity since set changed "
6075                                            + pa.mPref.mComponent);
6076                                }
6077                                pir.removeFilter(pa);
6078                                // Re-add the filter as a "last chosen" entry (!always)
6079                                PreferredActivity lastChosen = new PreferredActivity(
6080                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6081                                pir.addFilter(lastChosen);
6082                                changed = true;
6083                                return null;
6084                            }
6085
6086                            // Yay! Either the set matched or we're looking for the last chosen
6087                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6088                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6089                            return ri;
6090                        }
6091                    }
6092                } finally {
6093                    if (changed) {
6094                        if (DEBUG_PREFERRED) {
6095                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6096                        }
6097                        scheduleWritePackageRestrictionsLocked(userId);
6098                    }
6099                }
6100            }
6101        }
6102        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6103        return null;
6104    }
6105
6106    /*
6107     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6108     */
6109    @Override
6110    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6111            int targetUserId) {
6112        mContext.enforceCallingOrSelfPermission(
6113                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6114        List<CrossProfileIntentFilter> matches =
6115                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6116        if (matches != null) {
6117            int size = matches.size();
6118            for (int i = 0; i < size; i++) {
6119                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6120            }
6121        }
6122        if (hasWebURI(intent)) {
6123            // cross-profile app linking works only towards the parent.
6124            final int callingUid = Binder.getCallingUid();
6125            final UserInfo parent = getProfileParent(sourceUserId);
6126            synchronized(mPackages) {
6127                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6128                        false /*includeInstantApps*/);
6129                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6130                        intent, resolvedType, flags, sourceUserId, parent.id);
6131                return xpDomainInfo != null;
6132            }
6133        }
6134        return false;
6135    }
6136
6137    private UserInfo getProfileParent(int userId) {
6138        final long identity = Binder.clearCallingIdentity();
6139        try {
6140            return sUserManager.getProfileParent(userId);
6141        } finally {
6142            Binder.restoreCallingIdentity(identity);
6143        }
6144    }
6145
6146    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6147            String resolvedType, int userId) {
6148        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6149        if (resolver != null) {
6150            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6151        }
6152        return null;
6153    }
6154
6155    @Override
6156    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6157            String resolvedType, int flags, int userId) {
6158        try {
6159            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6160
6161            return new ParceledListSlice<>(
6162                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6163        } finally {
6164            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6165        }
6166    }
6167
6168    /**
6169     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6170     * instant, returns {@code null}.
6171     */
6172    private String getInstantAppPackageName(int callingUid) {
6173        // If the caller is an isolated app use the owner's uid for the lookup.
6174        if (Process.isIsolated(callingUid)) {
6175            callingUid = mIsolatedOwners.get(callingUid);
6176        }
6177        final int appId = UserHandle.getAppId(callingUid);
6178        synchronized (mPackages) {
6179            final Object obj = mSettings.getUserIdLPr(appId);
6180            if (obj instanceof PackageSetting) {
6181                final PackageSetting ps = (PackageSetting) obj;
6182                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6183                return isInstantApp ? ps.pkg.packageName : null;
6184            }
6185        }
6186        return null;
6187    }
6188
6189    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6190            String resolvedType, int flags, int userId) {
6191        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6192    }
6193
6194    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6195            String resolvedType, int flags, int userId, boolean includeInstantApps) {
6196        if (!sUserManager.exists(userId)) return Collections.emptyList();
6197        final int callingUid = Binder.getCallingUid();
6198        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6199        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
6200        enforceCrossUserPermission(callingUid, userId,
6201                false /* requireFullPermission */, false /* checkShell */,
6202                "query intent activities");
6203        ComponentName comp = intent.getComponent();
6204        if (comp == null) {
6205            if (intent.getSelector() != null) {
6206                intent = intent.getSelector();
6207                comp = intent.getComponent();
6208            }
6209        }
6210
6211        if (comp != null) {
6212            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6213            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6214            if (ai != null) {
6215                // When specifying an explicit component, we prevent the activity from being
6216                // used when either 1) the calling package is normal and the activity is within
6217                // an ephemeral application or 2) the calling package is ephemeral and the
6218                // activity is not visible to ephemeral applications.
6219                final boolean matchInstantApp =
6220                        (flags & PackageManager.MATCH_INSTANT) != 0;
6221                final boolean matchVisibleToInstantAppOnly =
6222                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6223                final boolean isCallerInstantApp =
6224                        instantAppPkgName != null;
6225                final boolean isTargetSameInstantApp =
6226                        comp.getPackageName().equals(instantAppPkgName);
6227                final boolean isTargetInstantApp =
6228                        (ai.applicationInfo.privateFlags
6229                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6230                final boolean isTargetHiddenFromInstantApp =
6231                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6232                final boolean blockResolution =
6233                        !isTargetSameInstantApp
6234                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6235                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6236                                        && isTargetHiddenFromInstantApp));
6237                if (!blockResolution) {
6238                    final ResolveInfo ri = new ResolveInfo();
6239                    ri.activityInfo = ai;
6240                    list.add(ri);
6241                }
6242            }
6243            return applyPostResolutionFilter(list, instantAppPkgName);
6244        }
6245
6246        // reader
6247        boolean sortResult = false;
6248        boolean addEphemeral = false;
6249        List<ResolveInfo> result;
6250        final String pkgName = intent.getPackage();
6251        final boolean ephemeralDisabled = isEphemeralDisabled();
6252        synchronized (mPackages) {
6253            if (pkgName == null) {
6254                List<CrossProfileIntentFilter> matchingFilters =
6255                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6256                // Check for results that need to skip the current profile.
6257                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6258                        resolvedType, flags, userId);
6259                if (xpResolveInfo != null) {
6260                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6261                    xpResult.add(xpResolveInfo);
6262                    return applyPostResolutionFilter(
6263                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6264                }
6265
6266                // Check for results in the current profile.
6267                result = filterIfNotSystemUser(mActivities.queryIntent(
6268                        intent, resolvedType, flags, userId), userId);
6269                addEphemeral = !ephemeralDisabled
6270                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6271                // Check for cross profile results.
6272                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6273                xpResolveInfo = queryCrossProfileIntents(
6274                        matchingFilters, intent, resolvedType, flags, userId,
6275                        hasNonNegativePriorityResult);
6276                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6277                    boolean isVisibleToUser = filterIfNotSystemUser(
6278                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6279                    if (isVisibleToUser) {
6280                        result.add(xpResolveInfo);
6281                        sortResult = true;
6282                    }
6283                }
6284                if (hasWebURI(intent)) {
6285                    CrossProfileDomainInfo xpDomainInfo = null;
6286                    final UserInfo parent = getProfileParent(userId);
6287                    if (parent != null) {
6288                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6289                                flags, userId, parent.id);
6290                    }
6291                    if (xpDomainInfo != null) {
6292                        if (xpResolveInfo != null) {
6293                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6294                            // in the result.
6295                            result.remove(xpResolveInfo);
6296                        }
6297                        if (result.size() == 0 && !addEphemeral) {
6298                            // No result in current profile, but found candidate in parent user.
6299                            // And we are not going to add emphemeral app, so we can return the
6300                            // result straight away.
6301                            result.add(xpDomainInfo.resolveInfo);
6302                            return applyPostResolutionFilter(result, instantAppPkgName);
6303                        }
6304                    } else if (result.size() <= 1 && !addEphemeral) {
6305                        // No result in parent user and <= 1 result in current profile, and we
6306                        // are not going to add emphemeral app, so we can return the result without
6307                        // further processing.
6308                        return applyPostResolutionFilter(result, instantAppPkgName);
6309                    }
6310                    // We have more than one candidate (combining results from current and parent
6311                    // profile), so we need filtering and sorting.
6312                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6313                            intent, flags, result, xpDomainInfo, userId);
6314                    sortResult = true;
6315                }
6316            } else {
6317                final PackageParser.Package pkg = mPackages.get(pkgName);
6318                if (pkg != null) {
6319                    return applyPostResolutionFilter(filterIfNotSystemUser(
6320                            mActivities.queryIntentForPackage(
6321                                    intent, resolvedType, flags, pkg.activities, userId),
6322                            userId), instantAppPkgName);
6323                } else {
6324                    // the caller wants to resolve for a particular package; however, there
6325                    // were no installed results, so, try to find an ephemeral result
6326                    addEphemeral = !ephemeralDisabled
6327                            && isEphemeralAllowed(
6328                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6329                    result = new ArrayList<ResolveInfo>();
6330                }
6331            }
6332        }
6333        if (addEphemeral) {
6334            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6335            final InstantAppRequest requestObject = new InstantAppRequest(
6336                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6337                    null /*callingPackage*/, userId);
6338            final AuxiliaryResolveInfo auxiliaryResponse =
6339                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6340                            mContext, mInstantAppResolverConnection, requestObject);
6341            if (auxiliaryResponse != null) {
6342                if (DEBUG_EPHEMERAL) {
6343                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6344                }
6345                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6346                final PackageSetting ps =
6347                        mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6348                if (ps != null) {
6349                    ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6350                            mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6351                    ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6352                    ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6353                    // make sure this resolver is the default
6354                    ephemeralInstaller.isDefault = true;
6355                    ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6356                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6357                    // add a non-generic filter
6358                    ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6359                    ephemeralInstaller.filter.addDataPath(
6360                            intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6361                    ephemeralInstaller.instantAppAvailable = true;
6362                    result.add(ephemeralInstaller);
6363                }
6364            }
6365            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6366        }
6367        if (sortResult) {
6368            Collections.sort(result, mResolvePrioritySorter);
6369        }
6370        return applyPostResolutionFilter(result, instantAppPkgName);
6371    }
6372
6373    private static class CrossProfileDomainInfo {
6374        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6375        ResolveInfo resolveInfo;
6376        /* Best domain verification status of the activities found in the other profile */
6377        int bestDomainVerificationStatus;
6378    }
6379
6380    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6381            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6382        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6383                sourceUserId)) {
6384            return null;
6385        }
6386        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6387                resolvedType, flags, parentUserId);
6388
6389        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6390            return null;
6391        }
6392        CrossProfileDomainInfo result = null;
6393        int size = resultTargetUser.size();
6394        for (int i = 0; i < size; i++) {
6395            ResolveInfo riTargetUser = resultTargetUser.get(i);
6396            // Intent filter verification is only for filters that specify a host. So don't return
6397            // those that handle all web uris.
6398            if (riTargetUser.handleAllWebDataURI) {
6399                continue;
6400            }
6401            String packageName = riTargetUser.activityInfo.packageName;
6402            PackageSetting ps = mSettings.mPackages.get(packageName);
6403            if (ps == null) {
6404                continue;
6405            }
6406            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6407            int status = (int)(verificationState >> 32);
6408            if (result == null) {
6409                result = new CrossProfileDomainInfo();
6410                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6411                        sourceUserId, parentUserId);
6412                result.bestDomainVerificationStatus = status;
6413            } else {
6414                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6415                        result.bestDomainVerificationStatus);
6416            }
6417        }
6418        // Don't consider matches with status NEVER across profiles.
6419        if (result != null && result.bestDomainVerificationStatus
6420                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6421            return null;
6422        }
6423        return result;
6424    }
6425
6426    /**
6427     * Verification statuses are ordered from the worse to the best, except for
6428     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6429     */
6430    private int bestDomainVerificationStatus(int status1, int status2) {
6431        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6432            return status2;
6433        }
6434        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6435            return status1;
6436        }
6437        return (int) MathUtils.max(status1, status2);
6438    }
6439
6440    private boolean isUserEnabled(int userId) {
6441        long callingId = Binder.clearCallingIdentity();
6442        try {
6443            UserInfo userInfo = sUserManager.getUserInfo(userId);
6444            return userInfo != null && userInfo.isEnabled();
6445        } finally {
6446            Binder.restoreCallingIdentity(callingId);
6447        }
6448    }
6449
6450    /**
6451     * Filter out activities with systemUserOnly flag set, when current user is not System.
6452     *
6453     * @return filtered list
6454     */
6455    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6456        if (userId == UserHandle.USER_SYSTEM) {
6457            return resolveInfos;
6458        }
6459        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6460            ResolveInfo info = resolveInfos.get(i);
6461            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6462                resolveInfos.remove(i);
6463            }
6464        }
6465        return resolveInfos;
6466    }
6467
6468    /**
6469     * Filters out ephemeral activities.
6470     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6471     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6472     *
6473     * @param resolveInfos The pre-filtered list of resolved activities
6474     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6475     *          is performed.
6476     * @return A filtered list of resolved activities.
6477     */
6478    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6479            String ephemeralPkgName) {
6480        // TODO: When adding on-demand split support for non-instant apps, remove this check
6481        // and always apply post filtering
6482        if (ephemeralPkgName == null) {
6483            return resolveInfos;
6484        }
6485        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6486            final ResolveInfo info = resolveInfos.get(i);
6487            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6488            // allow activities that are defined in the provided package
6489            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6490                if (info.activityInfo.splitName != null
6491                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6492                                info.activityInfo.splitName)) {
6493                    // requested activity is defined in a split that hasn't been installed yet.
6494                    // add the installer to the resolve list
6495                    if (DEBUG_EPHEMERAL) {
6496                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6497                    }
6498                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6499                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6500                            info.activityInfo.packageName, info.activityInfo.splitName,
6501                            info.activityInfo.applicationInfo.versionCode);
6502                    // make sure this resolver is the default
6503                    installerInfo.isDefault = true;
6504                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6505                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6506                    // add a non-generic filter
6507                    installerInfo.filter = new IntentFilter();
6508                    // load resources from the correct package
6509                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6510                    resolveInfos.set(i, installerInfo);
6511                }
6512                continue;
6513            }
6514            // allow activities that have been explicitly exposed to ephemeral apps
6515            if (!isEphemeralApp
6516                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6517                continue;
6518            }
6519            resolveInfos.remove(i);
6520        }
6521        return resolveInfos;
6522    }
6523
6524    /**
6525     * @param resolveInfos list of resolve infos in descending priority order
6526     * @return if the list contains a resolve info with non-negative priority
6527     */
6528    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6529        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6530    }
6531
6532    private static boolean hasWebURI(Intent intent) {
6533        if (intent.getData() == null) {
6534            return false;
6535        }
6536        final String scheme = intent.getScheme();
6537        if (TextUtils.isEmpty(scheme)) {
6538            return false;
6539        }
6540        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6541    }
6542
6543    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6544            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6545            int userId) {
6546        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6547
6548        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6549            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6550                    candidates.size());
6551        }
6552
6553        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6554        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6555        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6556        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6557        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6558        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6559
6560        synchronized (mPackages) {
6561            final int count = candidates.size();
6562            // First, try to use linked apps. Partition the candidates into four lists:
6563            // one for the final results, one for the "do not use ever", one for "undefined status"
6564            // and finally one for "browser app type".
6565            for (int n=0; n<count; n++) {
6566                ResolveInfo info = candidates.get(n);
6567                String packageName = info.activityInfo.packageName;
6568                PackageSetting ps = mSettings.mPackages.get(packageName);
6569                if (ps != null) {
6570                    // Add to the special match all list (Browser use case)
6571                    if (info.handleAllWebDataURI) {
6572                        matchAllList.add(info);
6573                        continue;
6574                    }
6575                    // Try to get the status from User settings first
6576                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6577                    int status = (int)(packedStatus >> 32);
6578                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6579                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6580                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6581                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6582                                    + " : linkgen=" + linkGeneration);
6583                        }
6584                        // Use link-enabled generation as preferredOrder, i.e.
6585                        // prefer newly-enabled over earlier-enabled.
6586                        info.preferredOrder = linkGeneration;
6587                        alwaysList.add(info);
6588                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6589                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6590                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6591                        }
6592                        neverList.add(info);
6593                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6594                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6595                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6596                        }
6597                        alwaysAskList.add(info);
6598                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6599                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6600                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6601                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6602                        }
6603                        undefinedList.add(info);
6604                    }
6605                }
6606            }
6607
6608            // We'll want to include browser possibilities in a few cases
6609            boolean includeBrowser = false;
6610
6611            // First try to add the "always" resolution(s) for the current user, if any
6612            if (alwaysList.size() > 0) {
6613                result.addAll(alwaysList);
6614            } else {
6615                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6616                result.addAll(undefinedList);
6617                // Maybe add one for the other profile.
6618                if (xpDomainInfo != null && (
6619                        xpDomainInfo.bestDomainVerificationStatus
6620                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6621                    result.add(xpDomainInfo.resolveInfo);
6622                }
6623                includeBrowser = true;
6624            }
6625
6626            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6627            // If there were 'always' entries their preferred order has been set, so we also
6628            // back that off to make the alternatives equivalent
6629            if (alwaysAskList.size() > 0) {
6630                for (ResolveInfo i : result) {
6631                    i.preferredOrder = 0;
6632                }
6633                result.addAll(alwaysAskList);
6634                includeBrowser = true;
6635            }
6636
6637            if (includeBrowser) {
6638                // Also add browsers (all of them or only the default one)
6639                if (DEBUG_DOMAIN_VERIFICATION) {
6640                    Slog.v(TAG, "   ...including browsers in candidate set");
6641                }
6642                if ((matchFlags & MATCH_ALL) != 0) {
6643                    result.addAll(matchAllList);
6644                } else {
6645                    // Browser/generic handling case.  If there's a default browser, go straight
6646                    // to that (but only if there is no other higher-priority match).
6647                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6648                    int maxMatchPrio = 0;
6649                    ResolveInfo defaultBrowserMatch = null;
6650                    final int numCandidates = matchAllList.size();
6651                    for (int n = 0; n < numCandidates; n++) {
6652                        ResolveInfo info = matchAllList.get(n);
6653                        // track the highest overall match priority...
6654                        if (info.priority > maxMatchPrio) {
6655                            maxMatchPrio = info.priority;
6656                        }
6657                        // ...and the highest-priority default browser match
6658                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6659                            if (defaultBrowserMatch == null
6660                                    || (defaultBrowserMatch.priority < info.priority)) {
6661                                if (debug) {
6662                                    Slog.v(TAG, "Considering default browser match " + info);
6663                                }
6664                                defaultBrowserMatch = info;
6665                            }
6666                        }
6667                    }
6668                    if (defaultBrowserMatch != null
6669                            && defaultBrowserMatch.priority >= maxMatchPrio
6670                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6671                    {
6672                        if (debug) {
6673                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6674                        }
6675                        result.add(defaultBrowserMatch);
6676                    } else {
6677                        result.addAll(matchAllList);
6678                    }
6679                }
6680
6681                // If there is nothing selected, add all candidates and remove the ones that the user
6682                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6683                if (result.size() == 0) {
6684                    result.addAll(candidates);
6685                    result.removeAll(neverList);
6686                }
6687            }
6688        }
6689        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6690            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6691                    result.size());
6692            for (ResolveInfo info : result) {
6693                Slog.v(TAG, "  + " + info.activityInfo);
6694            }
6695        }
6696        return result;
6697    }
6698
6699    // Returns a packed value as a long:
6700    //
6701    // high 'int'-sized word: link status: undefined/ask/never/always.
6702    // low 'int'-sized word: relative priority among 'always' results.
6703    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6704        long result = ps.getDomainVerificationStatusForUser(userId);
6705        // if none available, get the master status
6706        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6707            if (ps.getIntentFilterVerificationInfo() != null) {
6708                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6709            }
6710        }
6711        return result;
6712    }
6713
6714    private ResolveInfo querySkipCurrentProfileIntents(
6715            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6716            int flags, int sourceUserId) {
6717        if (matchingFilters != null) {
6718            int size = matchingFilters.size();
6719            for (int i = 0; i < size; i ++) {
6720                CrossProfileIntentFilter filter = matchingFilters.get(i);
6721                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6722                    // Checking if there are activities in the target user that can handle the
6723                    // intent.
6724                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6725                            resolvedType, flags, sourceUserId);
6726                    if (resolveInfo != null) {
6727                        return resolveInfo;
6728                    }
6729                }
6730            }
6731        }
6732        return null;
6733    }
6734
6735    // Return matching ResolveInfo in target user if any.
6736    private ResolveInfo queryCrossProfileIntents(
6737            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6738            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6739        if (matchingFilters != null) {
6740            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6741            // match the same intent. For performance reasons, it is better not to
6742            // run queryIntent twice for the same userId
6743            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6744            int size = matchingFilters.size();
6745            for (int i = 0; i < size; i++) {
6746                CrossProfileIntentFilter filter = matchingFilters.get(i);
6747                int targetUserId = filter.getTargetUserId();
6748                boolean skipCurrentProfile =
6749                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6750                boolean skipCurrentProfileIfNoMatchFound =
6751                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6752                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6753                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6754                    // Checking if there are activities in the target user that can handle the
6755                    // intent.
6756                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6757                            resolvedType, flags, sourceUserId);
6758                    if (resolveInfo != null) return resolveInfo;
6759                    alreadyTriedUserIds.put(targetUserId, true);
6760                }
6761            }
6762        }
6763        return null;
6764    }
6765
6766    /**
6767     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6768     * will forward the intent to the filter's target user.
6769     * Otherwise, returns null.
6770     */
6771    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6772            String resolvedType, int flags, int sourceUserId) {
6773        int targetUserId = filter.getTargetUserId();
6774        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6775                resolvedType, flags, targetUserId);
6776        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6777            // If all the matches in the target profile are suspended, return null.
6778            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6779                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6780                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6781                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6782                            targetUserId);
6783                }
6784            }
6785        }
6786        return null;
6787    }
6788
6789    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6790            int sourceUserId, int targetUserId) {
6791        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6792        long ident = Binder.clearCallingIdentity();
6793        boolean targetIsProfile;
6794        try {
6795            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6796        } finally {
6797            Binder.restoreCallingIdentity(ident);
6798        }
6799        String className;
6800        if (targetIsProfile) {
6801            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6802        } else {
6803            className = FORWARD_INTENT_TO_PARENT;
6804        }
6805        ComponentName forwardingActivityComponentName = new ComponentName(
6806                mAndroidApplication.packageName, className);
6807        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6808                sourceUserId);
6809        if (!targetIsProfile) {
6810            forwardingActivityInfo.showUserIcon = targetUserId;
6811            forwardingResolveInfo.noResourceId = true;
6812        }
6813        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6814        forwardingResolveInfo.priority = 0;
6815        forwardingResolveInfo.preferredOrder = 0;
6816        forwardingResolveInfo.match = 0;
6817        forwardingResolveInfo.isDefault = true;
6818        forwardingResolveInfo.filter = filter;
6819        forwardingResolveInfo.targetUserId = targetUserId;
6820        return forwardingResolveInfo;
6821    }
6822
6823    @Override
6824    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6825            Intent[] specifics, String[] specificTypes, Intent intent,
6826            String resolvedType, int flags, int userId) {
6827        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6828                specificTypes, intent, resolvedType, flags, userId));
6829    }
6830
6831    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6832            Intent[] specifics, String[] specificTypes, Intent intent,
6833            String resolvedType, int flags, int userId) {
6834        if (!sUserManager.exists(userId)) return Collections.emptyList();
6835        final int callingUid = Binder.getCallingUid();
6836        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
6837                false /*includeInstantApps*/);
6838        enforceCrossUserPermission(callingUid, userId,
6839                false /*requireFullPermission*/, false /*checkShell*/,
6840                "query intent activity options");
6841        final String resultsAction = intent.getAction();
6842
6843        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6844                | PackageManager.GET_RESOLVED_FILTER, userId);
6845
6846        if (DEBUG_INTENT_MATCHING) {
6847            Log.v(TAG, "Query " + intent + ": " + results);
6848        }
6849
6850        int specificsPos = 0;
6851        int N;
6852
6853        // todo: note that the algorithm used here is O(N^2).  This
6854        // isn't a problem in our current environment, but if we start running
6855        // into situations where we have more than 5 or 10 matches then this
6856        // should probably be changed to something smarter...
6857
6858        // First we go through and resolve each of the specific items
6859        // that were supplied, taking care of removing any corresponding
6860        // duplicate items in the generic resolve list.
6861        if (specifics != null) {
6862            for (int i=0; i<specifics.length; i++) {
6863                final Intent sintent = specifics[i];
6864                if (sintent == null) {
6865                    continue;
6866                }
6867
6868                if (DEBUG_INTENT_MATCHING) {
6869                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6870                }
6871
6872                String action = sintent.getAction();
6873                if (resultsAction != null && resultsAction.equals(action)) {
6874                    // If this action was explicitly requested, then don't
6875                    // remove things that have it.
6876                    action = null;
6877                }
6878
6879                ResolveInfo ri = null;
6880                ActivityInfo ai = null;
6881
6882                ComponentName comp = sintent.getComponent();
6883                if (comp == null) {
6884                    ri = resolveIntent(
6885                        sintent,
6886                        specificTypes != null ? specificTypes[i] : null,
6887                            flags, userId);
6888                    if (ri == null) {
6889                        continue;
6890                    }
6891                    if (ri == mResolveInfo) {
6892                        // ACK!  Must do something better with this.
6893                    }
6894                    ai = ri.activityInfo;
6895                    comp = new ComponentName(ai.applicationInfo.packageName,
6896                            ai.name);
6897                } else {
6898                    ai = getActivityInfo(comp, flags, userId);
6899                    if (ai == null) {
6900                        continue;
6901                    }
6902                }
6903
6904                // Look for any generic query activities that are duplicates
6905                // of this specific one, and remove them from the results.
6906                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6907                N = results.size();
6908                int j;
6909                for (j=specificsPos; j<N; j++) {
6910                    ResolveInfo sri = results.get(j);
6911                    if ((sri.activityInfo.name.equals(comp.getClassName())
6912                            && sri.activityInfo.applicationInfo.packageName.equals(
6913                                    comp.getPackageName()))
6914                        || (action != null && sri.filter.matchAction(action))) {
6915                        results.remove(j);
6916                        if (DEBUG_INTENT_MATCHING) Log.v(
6917                            TAG, "Removing duplicate item from " + j
6918                            + " due to specific " + specificsPos);
6919                        if (ri == null) {
6920                            ri = sri;
6921                        }
6922                        j--;
6923                        N--;
6924                    }
6925                }
6926
6927                // Add this specific item to its proper place.
6928                if (ri == null) {
6929                    ri = new ResolveInfo();
6930                    ri.activityInfo = ai;
6931                }
6932                results.add(specificsPos, ri);
6933                ri.specificIndex = i;
6934                specificsPos++;
6935            }
6936        }
6937
6938        // Now we go through the remaining generic results and remove any
6939        // duplicate actions that are found here.
6940        N = results.size();
6941        for (int i=specificsPos; i<N-1; i++) {
6942            final ResolveInfo rii = results.get(i);
6943            if (rii.filter == null) {
6944                continue;
6945            }
6946
6947            // Iterate over all of the actions of this result's intent
6948            // filter...  typically this should be just one.
6949            final Iterator<String> it = rii.filter.actionsIterator();
6950            if (it == null) {
6951                continue;
6952            }
6953            while (it.hasNext()) {
6954                final String action = it.next();
6955                if (resultsAction != null && resultsAction.equals(action)) {
6956                    // If this action was explicitly requested, then don't
6957                    // remove things that have it.
6958                    continue;
6959                }
6960                for (int j=i+1; j<N; j++) {
6961                    final ResolveInfo rij = results.get(j);
6962                    if (rij.filter != null && rij.filter.hasAction(action)) {
6963                        results.remove(j);
6964                        if (DEBUG_INTENT_MATCHING) Log.v(
6965                            TAG, "Removing duplicate item from " + j
6966                            + " due to action " + action + " at " + i);
6967                        j--;
6968                        N--;
6969                    }
6970                }
6971            }
6972
6973            // If the caller didn't request filter information, drop it now
6974            // so we don't have to marshall/unmarshall it.
6975            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6976                rii.filter = null;
6977            }
6978        }
6979
6980        // Filter out the caller activity if so requested.
6981        if (caller != null) {
6982            N = results.size();
6983            for (int i=0; i<N; i++) {
6984                ActivityInfo ainfo = results.get(i).activityInfo;
6985                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6986                        && caller.getClassName().equals(ainfo.name)) {
6987                    results.remove(i);
6988                    break;
6989                }
6990            }
6991        }
6992
6993        // If the caller didn't request filter information,
6994        // drop them now so we don't have to
6995        // marshall/unmarshall it.
6996        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6997            N = results.size();
6998            for (int i=0; i<N; i++) {
6999                results.get(i).filter = null;
7000            }
7001        }
7002
7003        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7004        return results;
7005    }
7006
7007    @Override
7008    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7009            String resolvedType, int flags, int userId) {
7010        return new ParceledListSlice<>(
7011                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7012    }
7013
7014    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7015            String resolvedType, int flags, int userId) {
7016        if (!sUserManager.exists(userId)) return Collections.emptyList();
7017        final int callingUid = Binder.getCallingUid();
7018        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7019                false /*includeInstantApps*/);
7020        ComponentName comp = intent.getComponent();
7021        if (comp == null) {
7022            if (intent.getSelector() != null) {
7023                intent = intent.getSelector();
7024                comp = intent.getComponent();
7025            }
7026        }
7027        if (comp != null) {
7028            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7029            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7030            if (ai != null) {
7031                ResolveInfo ri = new ResolveInfo();
7032                ri.activityInfo = ai;
7033                list.add(ri);
7034            }
7035            return list;
7036        }
7037
7038        // reader
7039        synchronized (mPackages) {
7040            String pkgName = intent.getPackage();
7041            if (pkgName == null) {
7042                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7043            }
7044            final PackageParser.Package pkg = mPackages.get(pkgName);
7045            if (pkg != null) {
7046                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7047                        userId);
7048            }
7049            return Collections.emptyList();
7050        }
7051    }
7052
7053    @Override
7054    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7055        final int callingUid = Binder.getCallingUid();
7056        return resolveServiceInternal(
7057                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7058    }
7059
7060    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7061            int userId, int callingUid, boolean includeInstantApps) {
7062        if (!sUserManager.exists(userId)) return null;
7063        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7064        List<ResolveInfo> query = queryIntentServicesInternal(
7065                intent, resolvedType, flags, userId, callingUid, includeInstantApps);
7066        if (query != null) {
7067            if (query.size() >= 1) {
7068                // If there is more than one service with the same priority,
7069                // just arbitrarily pick the first one.
7070                return query.get(0);
7071            }
7072        }
7073        return null;
7074    }
7075
7076    @Override
7077    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7078            String resolvedType, int flags, int userId) {
7079        final int callingUid = Binder.getCallingUid();
7080        return new ParceledListSlice<>(queryIntentServicesInternal(
7081                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7082    }
7083
7084    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7085            String resolvedType, int flags, int userId, int callingUid,
7086            boolean includeInstantApps) {
7087        if (!sUserManager.exists(userId)) return Collections.emptyList();
7088        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7089        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7090        ComponentName comp = intent.getComponent();
7091        if (comp == null) {
7092            if (intent.getSelector() != null) {
7093                intent = intent.getSelector();
7094                comp = intent.getComponent();
7095            }
7096        }
7097        if (comp != null) {
7098            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7099            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7100            if (si != null) {
7101                // When specifying an explicit component, we prevent the service from being
7102                // used when either 1) the service is in an instant application and the
7103                // caller is not the same instant application or 2) the calling package is
7104                // ephemeral and the activity is not visible to ephemeral applications.
7105                final boolean matchInstantApp =
7106                        (flags & PackageManager.MATCH_INSTANT) != 0;
7107                final boolean matchVisibleToInstantAppOnly =
7108                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7109                final boolean isCallerInstantApp =
7110                        instantAppPkgName != null;
7111                final boolean isTargetSameInstantApp =
7112                        comp.getPackageName().equals(instantAppPkgName);
7113                final boolean isTargetInstantApp =
7114                        (si.applicationInfo.privateFlags
7115                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7116                final boolean isTargetHiddenFromInstantApp =
7117                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
7118                final boolean blockResolution =
7119                        !isTargetSameInstantApp
7120                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7121                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7122                                        && isTargetHiddenFromInstantApp));
7123                if (!blockResolution) {
7124                    final ResolveInfo ri = new ResolveInfo();
7125                    ri.serviceInfo = si;
7126                    list.add(ri);
7127                }
7128            }
7129            return list;
7130        }
7131
7132        // reader
7133        synchronized (mPackages) {
7134            String pkgName = intent.getPackage();
7135            if (pkgName == null) {
7136                return applyPostServiceResolutionFilter(
7137                        mServices.queryIntent(intent, resolvedType, flags, userId),
7138                        instantAppPkgName);
7139            }
7140            final PackageParser.Package pkg = mPackages.get(pkgName);
7141            if (pkg != null) {
7142                return applyPostServiceResolutionFilter(
7143                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7144                                userId),
7145                        instantAppPkgName);
7146            }
7147            return Collections.emptyList();
7148        }
7149    }
7150
7151    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7152            String instantAppPkgName) {
7153        // TODO: When adding on-demand split support for non-instant apps, remove this check
7154        // and always apply post filtering
7155        if (instantAppPkgName == null) {
7156            return resolveInfos;
7157        }
7158        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7159            final ResolveInfo info = resolveInfos.get(i);
7160            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7161            // allow services that are defined in the provided package
7162            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7163                if (info.serviceInfo.splitName != null
7164                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7165                                info.serviceInfo.splitName)) {
7166                    // requested service is defined in a split that hasn't been installed yet.
7167                    // add the installer to the resolve list
7168                    if (DEBUG_EPHEMERAL) {
7169                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7170                    }
7171                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7172                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7173                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7174                            info.serviceInfo.applicationInfo.versionCode);
7175                    // make sure this resolver is the default
7176                    installerInfo.isDefault = true;
7177                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7178                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7179                    // add a non-generic filter
7180                    installerInfo.filter = new IntentFilter();
7181                    // load resources from the correct package
7182                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7183                    resolveInfos.set(i, installerInfo);
7184                }
7185                continue;
7186            }
7187            // allow services that have been explicitly exposed to ephemeral apps
7188            if (!isEphemeralApp
7189                    && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
7190                continue;
7191            }
7192            resolveInfos.remove(i);
7193        }
7194        return resolveInfos;
7195    }
7196
7197    @Override
7198    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7199            String resolvedType, int flags, int userId) {
7200        return new ParceledListSlice<>(
7201                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7202    }
7203
7204    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7205            Intent intent, String resolvedType, int flags, int userId) {
7206        if (!sUserManager.exists(userId)) return Collections.emptyList();
7207        final int callingUid = Binder.getCallingUid();
7208        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7209        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7210                false /*includeInstantApps*/);
7211        ComponentName comp = intent.getComponent();
7212        if (comp == null) {
7213            if (intent.getSelector() != null) {
7214                intent = intent.getSelector();
7215                comp = intent.getComponent();
7216            }
7217        }
7218        if (comp != null) {
7219            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7220            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7221            if (pi != null) {
7222                // When specifying an explicit component, we prevent the provider from being
7223                // used when either 1) the provider is in an instant application and the
7224                // caller is not the same instant application or 2) the calling package is an
7225                // instant application and the provider is not visible to instant applications.
7226                final boolean matchInstantApp =
7227                        (flags & PackageManager.MATCH_INSTANT) != 0;
7228                final boolean matchVisibleToInstantAppOnly =
7229                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7230                final boolean isCallerInstantApp =
7231                        instantAppPkgName != null;
7232                final boolean isTargetSameInstantApp =
7233                        comp.getPackageName().equals(instantAppPkgName);
7234                final boolean isTargetInstantApp =
7235                        (pi.applicationInfo.privateFlags
7236                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7237                final boolean isTargetHiddenFromInstantApp =
7238                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
7239                final boolean blockResolution =
7240                        !isTargetSameInstantApp
7241                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7242                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7243                                        && isTargetHiddenFromInstantApp));
7244                if (!blockResolution) {
7245                    final ResolveInfo ri = new ResolveInfo();
7246                    ri.providerInfo = pi;
7247                    list.add(ri);
7248                }
7249            }
7250            return list;
7251        }
7252
7253        // reader
7254        synchronized (mPackages) {
7255            String pkgName = intent.getPackage();
7256            if (pkgName == null) {
7257                return applyPostContentProviderResolutionFilter(
7258                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7259                        instantAppPkgName);
7260            }
7261            final PackageParser.Package pkg = mPackages.get(pkgName);
7262            if (pkg != null) {
7263                return applyPostContentProviderResolutionFilter(
7264                        mProviders.queryIntentForPackage(
7265                        intent, resolvedType, flags, pkg.providers, userId),
7266                        instantAppPkgName);
7267            }
7268            return Collections.emptyList();
7269        }
7270    }
7271
7272    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7273            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7274        // TODO: When adding on-demand split support for non-instant applications, remove
7275        // this check and always apply post filtering
7276        if (instantAppPkgName == null) {
7277            return resolveInfos;
7278        }
7279        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7280            final ResolveInfo info = resolveInfos.get(i);
7281            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7282            // allow providers that are defined in the provided package
7283            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7284                if (info.providerInfo.splitName != null
7285                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7286                                info.providerInfo.splitName)) {
7287                    // requested provider is defined in a split that hasn't been installed yet.
7288                    // add the installer to the resolve list
7289                    if (DEBUG_EPHEMERAL) {
7290                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7291                    }
7292                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7293                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7294                            info.providerInfo.packageName, info.providerInfo.splitName,
7295                            info.providerInfo.applicationInfo.versionCode);
7296                    // make sure this resolver is the default
7297                    installerInfo.isDefault = true;
7298                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7299                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7300                    // add a non-generic filter
7301                    installerInfo.filter = new IntentFilter();
7302                    // load resources from the correct package
7303                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7304                    resolveInfos.set(i, installerInfo);
7305                }
7306                continue;
7307            }
7308            // allow providers that have been explicitly exposed to instant applications
7309            if (!isEphemeralApp
7310                    && ((info.providerInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
7311                continue;
7312            }
7313            resolveInfos.remove(i);
7314        }
7315        return resolveInfos;
7316    }
7317
7318    @Override
7319    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7320        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7321        flags = updateFlagsForPackage(flags, userId, null);
7322        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7323        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7324                true /* requireFullPermission */, false /* checkShell */,
7325                "get installed packages");
7326
7327        // writer
7328        synchronized (mPackages) {
7329            ArrayList<PackageInfo> list;
7330            if (listUninstalled) {
7331                list = new ArrayList<>(mSettings.mPackages.size());
7332                for (PackageSetting ps : mSettings.mPackages.values()) {
7333                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7334                        continue;
7335                    }
7336                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7337                    if (pi != null) {
7338                        list.add(pi);
7339                    }
7340                }
7341            } else {
7342                list = new ArrayList<>(mPackages.size());
7343                for (PackageParser.Package p : mPackages.values()) {
7344                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7345                            Binder.getCallingUid(), userId)) {
7346                        continue;
7347                    }
7348                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7349                            p.mExtras, flags, userId);
7350                    if (pi != null) {
7351                        list.add(pi);
7352                    }
7353                }
7354            }
7355
7356            return new ParceledListSlice<>(list);
7357        }
7358    }
7359
7360    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7361            String[] permissions, boolean[] tmp, int flags, int userId) {
7362        int numMatch = 0;
7363        final PermissionsState permissionsState = ps.getPermissionsState();
7364        for (int i=0; i<permissions.length; i++) {
7365            final String permission = permissions[i];
7366            if (permissionsState.hasPermission(permission, userId)) {
7367                tmp[i] = true;
7368                numMatch++;
7369            } else {
7370                tmp[i] = false;
7371            }
7372        }
7373        if (numMatch == 0) {
7374            return;
7375        }
7376        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7377
7378        // The above might return null in cases of uninstalled apps or install-state
7379        // skew across users/profiles.
7380        if (pi != null) {
7381            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7382                if (numMatch == permissions.length) {
7383                    pi.requestedPermissions = permissions;
7384                } else {
7385                    pi.requestedPermissions = new String[numMatch];
7386                    numMatch = 0;
7387                    for (int i=0; i<permissions.length; i++) {
7388                        if (tmp[i]) {
7389                            pi.requestedPermissions[numMatch] = permissions[i];
7390                            numMatch++;
7391                        }
7392                    }
7393                }
7394            }
7395            list.add(pi);
7396        }
7397    }
7398
7399    @Override
7400    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7401            String[] permissions, int flags, int userId) {
7402        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7403        flags = updateFlagsForPackage(flags, userId, permissions);
7404        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7405                true /* requireFullPermission */, false /* checkShell */,
7406                "get packages holding permissions");
7407        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7408
7409        // writer
7410        synchronized (mPackages) {
7411            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7412            boolean[] tmpBools = new boolean[permissions.length];
7413            if (listUninstalled) {
7414                for (PackageSetting ps : mSettings.mPackages.values()) {
7415                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7416                            userId);
7417                }
7418            } else {
7419                for (PackageParser.Package pkg : mPackages.values()) {
7420                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7421                    if (ps != null) {
7422                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7423                                userId);
7424                    }
7425                }
7426            }
7427
7428            return new ParceledListSlice<PackageInfo>(list);
7429        }
7430    }
7431
7432    @Override
7433    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7434        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7435        flags = updateFlagsForApplication(flags, userId, null);
7436        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7437
7438        // writer
7439        synchronized (mPackages) {
7440            ArrayList<ApplicationInfo> list;
7441            if (listUninstalled) {
7442                list = new ArrayList<>(mSettings.mPackages.size());
7443                for (PackageSetting ps : mSettings.mPackages.values()) {
7444                    ApplicationInfo ai;
7445                    int effectiveFlags = flags;
7446                    if (ps.isSystem()) {
7447                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7448                    }
7449                    if (ps.pkg != null) {
7450                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7451                            continue;
7452                        }
7453                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7454                                ps.readUserState(userId), userId);
7455                        if (ai != null) {
7456                            rebaseEnabledOverlays(ai, userId);
7457                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7458                        }
7459                    } else {
7460                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7461                        // and already converts to externally visible package name
7462                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7463                                Binder.getCallingUid(), effectiveFlags, userId);
7464                    }
7465                    if (ai != null) {
7466                        list.add(ai);
7467                    }
7468                }
7469            } else {
7470                list = new ArrayList<>(mPackages.size());
7471                for (PackageParser.Package p : mPackages.values()) {
7472                    if (p.mExtras != null) {
7473                        PackageSetting ps = (PackageSetting) p.mExtras;
7474                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7475                            continue;
7476                        }
7477                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7478                                ps.readUserState(userId), userId);
7479                        if (ai != null) {
7480                            rebaseEnabledOverlays(ai, userId);
7481                            ai.packageName = resolveExternalPackageNameLPr(p);
7482                            list.add(ai);
7483                        }
7484                    }
7485                }
7486            }
7487
7488            return new ParceledListSlice<>(list);
7489        }
7490    }
7491
7492    @Override
7493    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7494        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7495            return null;
7496        }
7497
7498        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7499                "getEphemeralApplications");
7500        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7501                true /* requireFullPermission */, false /* checkShell */,
7502                "getEphemeralApplications");
7503        synchronized (mPackages) {
7504            List<InstantAppInfo> instantApps = mInstantAppRegistry
7505                    .getInstantAppsLPr(userId);
7506            if (instantApps != null) {
7507                return new ParceledListSlice<>(instantApps);
7508            }
7509        }
7510        return null;
7511    }
7512
7513    @Override
7514    public boolean isInstantApp(String packageName, int userId) {
7515        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7516                true /* requireFullPermission */, false /* checkShell */,
7517                "isInstantApp");
7518        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7519            return false;
7520        }
7521        int uid = Binder.getCallingUid();
7522        if (Process.isIsolated(uid)) {
7523            uid = mIsolatedOwners.get(uid);
7524        }
7525
7526        synchronized (mPackages) {
7527            final PackageSetting ps = mSettings.mPackages.get(packageName);
7528            PackageParser.Package pkg = mPackages.get(packageName);
7529            final boolean returnAllowed =
7530                    ps != null
7531                    && (isCallerSameApp(packageName, uid)
7532                            || mContext.checkCallingOrSelfPermission(
7533                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7534                                            == PERMISSION_GRANTED
7535                            || mInstantAppRegistry.isInstantAccessGranted(
7536                                    userId, UserHandle.getAppId(uid), ps.appId));
7537            if (returnAllowed) {
7538                return ps.getInstantApp(userId);
7539            }
7540        }
7541        return false;
7542    }
7543
7544    @Override
7545    public byte[] getInstantAppCookie(String packageName, int userId) {
7546        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7547            return null;
7548        }
7549
7550        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7551                true /* requireFullPermission */, false /* checkShell */,
7552                "getInstantAppCookie");
7553        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7554            return null;
7555        }
7556        synchronized (mPackages) {
7557            return mInstantAppRegistry.getInstantAppCookieLPw(
7558                    packageName, userId);
7559        }
7560    }
7561
7562    @Override
7563    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7564        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7565            return true;
7566        }
7567
7568        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7569                true /* requireFullPermission */, true /* checkShell */,
7570                "setInstantAppCookie");
7571        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7572            return false;
7573        }
7574        synchronized (mPackages) {
7575            return mInstantAppRegistry.setInstantAppCookieLPw(
7576                    packageName, cookie, userId);
7577        }
7578    }
7579
7580    @Override
7581    public Bitmap getInstantAppIcon(String packageName, int userId) {
7582        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7583            return null;
7584        }
7585
7586        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7587                "getInstantAppIcon");
7588
7589        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7590                true /* requireFullPermission */, false /* checkShell */,
7591                "getInstantAppIcon");
7592
7593        synchronized (mPackages) {
7594            return mInstantAppRegistry.getInstantAppIconLPw(
7595                    packageName, userId);
7596        }
7597    }
7598
7599    private boolean isCallerSameApp(String packageName, int uid) {
7600        PackageParser.Package pkg = mPackages.get(packageName);
7601        return pkg != null
7602                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7603    }
7604
7605    @Override
7606    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7607        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7608    }
7609
7610    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7611        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7612
7613        // reader
7614        synchronized (mPackages) {
7615            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7616            final int userId = UserHandle.getCallingUserId();
7617            while (i.hasNext()) {
7618                final PackageParser.Package p = i.next();
7619                if (p.applicationInfo == null) continue;
7620
7621                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7622                        && !p.applicationInfo.isDirectBootAware();
7623                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7624                        && p.applicationInfo.isDirectBootAware();
7625
7626                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7627                        && (!mSafeMode || isSystemApp(p))
7628                        && (matchesUnaware || matchesAware)) {
7629                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7630                    if (ps != null) {
7631                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7632                                ps.readUserState(userId), userId);
7633                        if (ai != null) {
7634                            rebaseEnabledOverlays(ai, userId);
7635                            finalList.add(ai);
7636                        }
7637                    }
7638                }
7639            }
7640        }
7641
7642        return finalList;
7643    }
7644
7645    @Override
7646    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7647        if (!sUserManager.exists(userId)) return null;
7648        flags = updateFlagsForComponent(flags, userId, name);
7649        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7650        // reader
7651        synchronized (mPackages) {
7652            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7653            PackageSetting ps = provider != null
7654                    ? mSettings.mPackages.get(provider.owner.packageName)
7655                    : null;
7656            if (ps != null) {
7657                final boolean isInstantApp = ps.getInstantApp(userId);
7658                // normal application; filter out instant application provider
7659                if (instantAppPkgName == null && isInstantApp) {
7660                    return null;
7661                }
7662                // instant application; filter out other instant applications
7663                if (instantAppPkgName != null
7664                        && isInstantApp
7665                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7666                    return null;
7667                }
7668                // instant application; filter out non-exposed provider
7669                if (instantAppPkgName != null
7670                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0) {
7671                    return null;
7672                }
7673                // provider not enabled
7674                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7675                    return null;
7676                }
7677                return PackageParser.generateProviderInfo(
7678                        provider, flags, ps.readUserState(userId), userId);
7679            }
7680            return null;
7681        }
7682    }
7683
7684    /**
7685     * @deprecated
7686     */
7687    @Deprecated
7688    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7689        // reader
7690        synchronized (mPackages) {
7691            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7692                    .entrySet().iterator();
7693            final int userId = UserHandle.getCallingUserId();
7694            while (i.hasNext()) {
7695                Map.Entry<String, PackageParser.Provider> entry = i.next();
7696                PackageParser.Provider p = entry.getValue();
7697                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7698
7699                if (ps != null && p.syncable
7700                        && (!mSafeMode || (p.info.applicationInfo.flags
7701                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7702                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7703                            ps.readUserState(userId), userId);
7704                    if (info != null) {
7705                        outNames.add(entry.getKey());
7706                        outInfo.add(info);
7707                    }
7708                }
7709            }
7710        }
7711    }
7712
7713    @Override
7714    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7715            int uid, int flags, String metaDataKey) {
7716        final int userId = processName != null ? UserHandle.getUserId(uid)
7717                : UserHandle.getCallingUserId();
7718        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7719        flags = updateFlagsForComponent(flags, userId, processName);
7720
7721        ArrayList<ProviderInfo> finalList = null;
7722        // reader
7723        synchronized (mPackages) {
7724            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7725            while (i.hasNext()) {
7726                final PackageParser.Provider p = i.next();
7727                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7728                if (ps != null && p.info.authority != null
7729                        && (processName == null
7730                                || (p.info.processName.equals(processName)
7731                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7732                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7733
7734                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7735                    // parameter.
7736                    if (metaDataKey != null
7737                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7738                        continue;
7739                    }
7740
7741                    if (finalList == null) {
7742                        finalList = new ArrayList<ProviderInfo>(3);
7743                    }
7744                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7745                            ps.readUserState(userId), userId);
7746                    if (info != null) {
7747                        finalList.add(info);
7748                    }
7749                }
7750            }
7751        }
7752
7753        if (finalList != null) {
7754            Collections.sort(finalList, mProviderInitOrderSorter);
7755            return new ParceledListSlice<ProviderInfo>(finalList);
7756        }
7757
7758        return ParceledListSlice.emptyList();
7759    }
7760
7761    @Override
7762    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7763        // reader
7764        synchronized (mPackages) {
7765            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7766            return PackageParser.generateInstrumentationInfo(i, flags);
7767        }
7768    }
7769
7770    @Override
7771    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7772            String targetPackage, int flags) {
7773        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7774    }
7775
7776    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7777            int flags) {
7778        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7779
7780        // reader
7781        synchronized (mPackages) {
7782            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7783            while (i.hasNext()) {
7784                final PackageParser.Instrumentation p = i.next();
7785                if (targetPackage == null
7786                        || targetPackage.equals(p.info.targetPackage)) {
7787                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7788                            flags);
7789                    if (ii != null) {
7790                        finalList.add(ii);
7791                    }
7792                }
7793            }
7794        }
7795
7796        return finalList;
7797    }
7798
7799    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7800        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7801        try {
7802            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7803        } finally {
7804            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7805        }
7806    }
7807
7808    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7809        final File[] files = dir.listFiles();
7810        if (ArrayUtils.isEmpty(files)) {
7811            Log.d(TAG, "No files in app dir " + dir);
7812            return;
7813        }
7814
7815        if (DEBUG_PACKAGE_SCANNING) {
7816            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7817                    + " flags=0x" + Integer.toHexString(parseFlags));
7818        }
7819        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7820                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7821
7822        // Submit files for parsing in parallel
7823        int fileCount = 0;
7824        for (File file : files) {
7825            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7826                    && !PackageInstallerService.isStageName(file.getName());
7827            if (!isPackage) {
7828                // Ignore entries which are not packages
7829                continue;
7830            }
7831            parallelPackageParser.submit(file, parseFlags);
7832            fileCount++;
7833        }
7834
7835        // Process results one by one
7836        for (; fileCount > 0; fileCount--) {
7837            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7838            Throwable throwable = parseResult.throwable;
7839            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7840
7841            if (throwable == null) {
7842                // Static shared libraries have synthetic package names
7843                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7844                    renameStaticSharedLibraryPackage(parseResult.pkg);
7845                }
7846                try {
7847                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7848                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7849                                currentTime, null);
7850                    }
7851                } catch (PackageManagerException e) {
7852                    errorCode = e.error;
7853                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7854                }
7855            } else if (throwable instanceof PackageParser.PackageParserException) {
7856                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7857                        throwable;
7858                errorCode = e.error;
7859                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7860            } else {
7861                throw new IllegalStateException("Unexpected exception occurred while parsing "
7862                        + parseResult.scanFile, throwable);
7863            }
7864
7865            // Delete invalid userdata apps
7866            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7867                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7868                logCriticalInfo(Log.WARN,
7869                        "Deleting invalid package at " + parseResult.scanFile);
7870                removeCodePathLI(parseResult.scanFile);
7871            }
7872        }
7873        parallelPackageParser.close();
7874    }
7875
7876    private static File getSettingsProblemFile() {
7877        File dataDir = Environment.getDataDirectory();
7878        File systemDir = new File(dataDir, "system");
7879        File fname = new File(systemDir, "uiderrors.txt");
7880        return fname;
7881    }
7882
7883    static void reportSettingsProblem(int priority, String msg) {
7884        logCriticalInfo(priority, msg);
7885    }
7886
7887    public static void logCriticalInfo(int priority, String msg) {
7888        Slog.println(priority, TAG, msg);
7889        EventLogTags.writePmCriticalInfo(msg);
7890        try {
7891            File fname = getSettingsProblemFile();
7892            FileOutputStream out = new FileOutputStream(fname, true);
7893            PrintWriter pw = new FastPrintWriter(out);
7894            SimpleDateFormat formatter = new SimpleDateFormat();
7895            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7896            pw.println(dateString + ": " + msg);
7897            pw.close();
7898            FileUtils.setPermissions(
7899                    fname.toString(),
7900                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7901                    -1, -1);
7902        } catch (java.io.IOException e) {
7903        }
7904    }
7905
7906    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7907        if (srcFile.isDirectory()) {
7908            final File baseFile = new File(pkg.baseCodePath);
7909            long maxModifiedTime = baseFile.lastModified();
7910            if (pkg.splitCodePaths != null) {
7911                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7912                    final File splitFile = new File(pkg.splitCodePaths[i]);
7913                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7914                }
7915            }
7916            return maxModifiedTime;
7917        }
7918        return srcFile.lastModified();
7919    }
7920
7921    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7922            final int policyFlags) throws PackageManagerException {
7923        // When upgrading from pre-N MR1, verify the package time stamp using the package
7924        // directory and not the APK file.
7925        final long lastModifiedTime = mIsPreNMR1Upgrade
7926                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7927        if (ps != null
7928                && ps.codePath.equals(srcFile)
7929                && ps.timeStamp == lastModifiedTime
7930                && !isCompatSignatureUpdateNeeded(pkg)
7931                && !isRecoverSignatureUpdateNeeded(pkg)) {
7932            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7933            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7934            ArraySet<PublicKey> signingKs;
7935            synchronized (mPackages) {
7936                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7937            }
7938            if (ps.signatures.mSignatures != null
7939                    && ps.signatures.mSignatures.length != 0
7940                    && signingKs != null) {
7941                // Optimization: reuse the existing cached certificates
7942                // if the package appears to be unchanged.
7943                pkg.mSignatures = ps.signatures.mSignatures;
7944                pkg.mSigningKeys = signingKs;
7945                return;
7946            }
7947
7948            Slog.w(TAG, "PackageSetting for " + ps.name
7949                    + " is missing signatures.  Collecting certs again to recover them.");
7950        } else {
7951            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7952        }
7953
7954        try {
7955            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7956            PackageParser.collectCertificates(pkg, policyFlags);
7957        } catch (PackageParserException e) {
7958            throw PackageManagerException.from(e);
7959        } finally {
7960            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7961        }
7962    }
7963
7964    /**
7965     *  Traces a package scan.
7966     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7967     */
7968    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7969            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7970        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7971        try {
7972            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7973        } finally {
7974            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7975        }
7976    }
7977
7978    /**
7979     *  Scans a package and returns the newly parsed package.
7980     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7981     */
7982    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7983            long currentTime, UserHandle user) throws PackageManagerException {
7984        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7985        PackageParser pp = new PackageParser();
7986        pp.setSeparateProcesses(mSeparateProcesses);
7987        pp.setOnlyCoreApps(mOnlyCore);
7988        pp.setDisplayMetrics(mMetrics);
7989        pp.setCallback(mPackageParserCallback);
7990
7991        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7992            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7993        }
7994
7995        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7996        final PackageParser.Package pkg;
7997        try {
7998            pkg = pp.parsePackage(scanFile, parseFlags);
7999        } catch (PackageParserException e) {
8000            throw PackageManagerException.from(e);
8001        } finally {
8002            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8003        }
8004
8005        // Static shared libraries have synthetic package names
8006        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8007            renameStaticSharedLibraryPackage(pkg);
8008        }
8009
8010        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8011    }
8012
8013    /**
8014     *  Scans a package and returns the newly parsed package.
8015     *  @throws PackageManagerException on a parse error.
8016     */
8017    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8018            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8019            throws PackageManagerException {
8020        // If the package has children and this is the first dive in the function
8021        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8022        // packages (parent and children) would be successfully scanned before the
8023        // actual scan since scanning mutates internal state and we want to atomically
8024        // install the package and its children.
8025        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8026            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8027                scanFlags |= SCAN_CHECK_ONLY;
8028            }
8029        } else {
8030            scanFlags &= ~SCAN_CHECK_ONLY;
8031        }
8032
8033        // Scan the parent
8034        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8035                scanFlags, currentTime, user);
8036
8037        // Scan the children
8038        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8039        for (int i = 0; i < childCount; i++) {
8040            PackageParser.Package childPackage = pkg.childPackages.get(i);
8041            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8042                    currentTime, user);
8043        }
8044
8045
8046        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8047            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8048        }
8049
8050        return scannedPkg;
8051    }
8052
8053    /**
8054     *  Scans a package and returns the newly parsed package.
8055     *  @throws PackageManagerException on a parse error.
8056     */
8057    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8058            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8059            throws PackageManagerException {
8060        PackageSetting ps = null;
8061        PackageSetting updatedPkg;
8062        // reader
8063        synchronized (mPackages) {
8064            // Look to see if we already know about this package.
8065            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8066            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8067                // This package has been renamed to its original name.  Let's
8068                // use that.
8069                ps = mSettings.getPackageLPr(oldName);
8070            }
8071            // If there was no original package, see one for the real package name.
8072            if (ps == null) {
8073                ps = mSettings.getPackageLPr(pkg.packageName);
8074            }
8075            // Check to see if this package could be hiding/updating a system
8076            // package.  Must look for it either under the original or real
8077            // package name depending on our state.
8078            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8079            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8080
8081            // If this is a package we don't know about on the system partition, we
8082            // may need to remove disabled child packages on the system partition
8083            // or may need to not add child packages if the parent apk is updated
8084            // on the data partition and no longer defines this child package.
8085            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8086                // If this is a parent package for an updated system app and this system
8087                // app got an OTA update which no longer defines some of the child packages
8088                // we have to prune them from the disabled system packages.
8089                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8090                if (disabledPs != null) {
8091                    final int scannedChildCount = (pkg.childPackages != null)
8092                            ? pkg.childPackages.size() : 0;
8093                    final int disabledChildCount = disabledPs.childPackageNames != null
8094                            ? disabledPs.childPackageNames.size() : 0;
8095                    for (int i = 0; i < disabledChildCount; i++) {
8096                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8097                        boolean disabledPackageAvailable = false;
8098                        for (int j = 0; j < scannedChildCount; j++) {
8099                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8100                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8101                                disabledPackageAvailable = true;
8102                                break;
8103                            }
8104                         }
8105                         if (!disabledPackageAvailable) {
8106                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8107                         }
8108                    }
8109                }
8110            }
8111        }
8112
8113        boolean updatedPkgBetter = false;
8114        // First check if this is a system package that may involve an update
8115        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8116            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8117            // it needs to drop FLAG_PRIVILEGED.
8118            if (locationIsPrivileged(scanFile)) {
8119                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8120            } else {
8121                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8122            }
8123
8124            if (ps != null && !ps.codePath.equals(scanFile)) {
8125                // The path has changed from what was last scanned...  check the
8126                // version of the new path against what we have stored to determine
8127                // what to do.
8128                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8129                if (pkg.mVersionCode <= ps.versionCode) {
8130                    // The system package has been updated and the code path does not match
8131                    // Ignore entry. Skip it.
8132                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8133                            + " ignored: updated version " + ps.versionCode
8134                            + " better than this " + pkg.mVersionCode);
8135                    if (!updatedPkg.codePath.equals(scanFile)) {
8136                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8137                                + ps.name + " changing from " + updatedPkg.codePathString
8138                                + " to " + scanFile);
8139                        updatedPkg.codePath = scanFile;
8140                        updatedPkg.codePathString = scanFile.toString();
8141                        updatedPkg.resourcePath = scanFile;
8142                        updatedPkg.resourcePathString = scanFile.toString();
8143                    }
8144                    updatedPkg.pkg = pkg;
8145                    updatedPkg.versionCode = pkg.mVersionCode;
8146
8147                    // Update the disabled system child packages to point to the package too.
8148                    final int childCount = updatedPkg.childPackageNames != null
8149                            ? updatedPkg.childPackageNames.size() : 0;
8150                    for (int i = 0; i < childCount; i++) {
8151                        String childPackageName = updatedPkg.childPackageNames.get(i);
8152                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8153                                childPackageName);
8154                        if (updatedChildPkg != null) {
8155                            updatedChildPkg.pkg = pkg;
8156                            updatedChildPkg.versionCode = pkg.mVersionCode;
8157                        }
8158                    }
8159
8160                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8161                            + scanFile + " ignored: updated version " + ps.versionCode
8162                            + " better than this " + pkg.mVersionCode);
8163                } else {
8164                    // The current app on the system partition is better than
8165                    // what we have updated to on the data partition; switch
8166                    // back to the system partition version.
8167                    // At this point, its safely assumed that package installation for
8168                    // apps in system partition will go through. If not there won't be a working
8169                    // version of the app
8170                    // writer
8171                    synchronized (mPackages) {
8172                        // Just remove the loaded entries from package lists.
8173                        mPackages.remove(ps.name);
8174                    }
8175
8176                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8177                            + " reverting from " + ps.codePathString
8178                            + ": new version " + pkg.mVersionCode
8179                            + " better than installed " + ps.versionCode);
8180
8181                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8182                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8183                    synchronized (mInstallLock) {
8184                        args.cleanUpResourcesLI();
8185                    }
8186                    synchronized (mPackages) {
8187                        mSettings.enableSystemPackageLPw(ps.name);
8188                    }
8189                    updatedPkgBetter = true;
8190                }
8191            }
8192        }
8193
8194        if (updatedPkg != null) {
8195            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8196            // initially
8197            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8198
8199            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8200            // flag set initially
8201            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8202                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8203            }
8204        }
8205
8206        // Verify certificates against what was last scanned
8207        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8208
8209        /*
8210         * A new system app appeared, but we already had a non-system one of the
8211         * same name installed earlier.
8212         */
8213        boolean shouldHideSystemApp = false;
8214        if (updatedPkg == null && ps != null
8215                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8216            /*
8217             * Check to make sure the signatures match first. If they don't,
8218             * wipe the installed application and its data.
8219             */
8220            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8221                    != PackageManager.SIGNATURE_MATCH) {
8222                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8223                        + " signatures don't match existing userdata copy; removing");
8224                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8225                        "scanPackageInternalLI")) {
8226                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8227                }
8228                ps = null;
8229            } else {
8230                /*
8231                 * If the newly-added system app is an older version than the
8232                 * already installed version, hide it. It will be scanned later
8233                 * and re-added like an update.
8234                 */
8235                if (pkg.mVersionCode <= ps.versionCode) {
8236                    shouldHideSystemApp = true;
8237                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8238                            + " but new version " + pkg.mVersionCode + " better than installed "
8239                            + ps.versionCode + "; hiding system");
8240                } else {
8241                    /*
8242                     * The newly found system app is a newer version that the
8243                     * one previously installed. Simply remove the
8244                     * already-installed application and replace it with our own
8245                     * while keeping the application data.
8246                     */
8247                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8248                            + " reverting from " + ps.codePathString + ": new version "
8249                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8250                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8251                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8252                    synchronized (mInstallLock) {
8253                        args.cleanUpResourcesLI();
8254                    }
8255                }
8256            }
8257        }
8258
8259        // The apk is forward locked (not public) if its code and resources
8260        // are kept in different files. (except for app in either system or
8261        // vendor path).
8262        // TODO grab this value from PackageSettings
8263        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8264            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8265                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8266            }
8267        }
8268
8269        // TODO: extend to support forward-locked splits
8270        String resourcePath = null;
8271        String baseResourcePath = null;
8272        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8273            if (ps != null && ps.resourcePathString != null) {
8274                resourcePath = ps.resourcePathString;
8275                baseResourcePath = ps.resourcePathString;
8276            } else {
8277                // Should not happen at all. Just log an error.
8278                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8279            }
8280        } else {
8281            resourcePath = pkg.codePath;
8282            baseResourcePath = pkg.baseCodePath;
8283        }
8284
8285        // Set application objects path explicitly.
8286        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8287        pkg.setApplicationInfoCodePath(pkg.codePath);
8288        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8289        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8290        pkg.setApplicationInfoResourcePath(resourcePath);
8291        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8292        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8293
8294        final int userId = ((user == null) ? 0 : user.getIdentifier());
8295        if (ps != null && ps.getInstantApp(userId)) {
8296            scanFlags |= SCAN_AS_INSTANT_APP;
8297        }
8298
8299        // Note that we invoke the following method only if we are about to unpack an application
8300        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8301                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8302
8303        /*
8304         * If the system app should be overridden by a previously installed
8305         * data, hide the system app now and let the /data/app scan pick it up
8306         * again.
8307         */
8308        if (shouldHideSystemApp) {
8309            synchronized (mPackages) {
8310                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8311            }
8312        }
8313
8314        return scannedPkg;
8315    }
8316
8317    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8318        // Derive the new package synthetic package name
8319        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8320                + pkg.staticSharedLibVersion);
8321    }
8322
8323    private static String fixProcessName(String defProcessName,
8324            String processName) {
8325        if (processName == null) {
8326            return defProcessName;
8327        }
8328        return processName;
8329    }
8330
8331    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8332            throws PackageManagerException {
8333        if (pkgSetting.signatures.mSignatures != null) {
8334            // Already existing package. Make sure signatures match
8335            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8336                    == PackageManager.SIGNATURE_MATCH;
8337            if (!match) {
8338                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8339                        == PackageManager.SIGNATURE_MATCH;
8340            }
8341            if (!match) {
8342                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8343                        == PackageManager.SIGNATURE_MATCH;
8344            }
8345            if (!match) {
8346                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8347                        + pkg.packageName + " signatures do not match the "
8348                        + "previously installed version; ignoring!");
8349            }
8350        }
8351
8352        // Check for shared user signatures
8353        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8354            // Already existing package. Make sure signatures match
8355            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8356                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8357            if (!match) {
8358                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8359                        == PackageManager.SIGNATURE_MATCH;
8360            }
8361            if (!match) {
8362                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8363                        == PackageManager.SIGNATURE_MATCH;
8364            }
8365            if (!match) {
8366                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8367                        "Package " + pkg.packageName
8368                        + " has no signatures that match those in shared user "
8369                        + pkgSetting.sharedUser.name + "; ignoring!");
8370            }
8371        }
8372    }
8373
8374    /**
8375     * Enforces that only the system UID or root's UID can call a method exposed
8376     * via Binder.
8377     *
8378     * @param message used as message if SecurityException is thrown
8379     * @throws SecurityException if the caller is not system or root
8380     */
8381    private static final void enforceSystemOrRoot(String message) {
8382        final int uid = Binder.getCallingUid();
8383        if (uid != Process.SYSTEM_UID && uid != 0) {
8384            throw new SecurityException(message);
8385        }
8386    }
8387
8388    @Override
8389    public void performFstrimIfNeeded() {
8390        enforceSystemOrRoot("Only the system can request fstrim");
8391
8392        // Before everything else, see whether we need to fstrim.
8393        try {
8394            IStorageManager sm = PackageHelper.getStorageManager();
8395            if (sm != null) {
8396                boolean doTrim = false;
8397                final long interval = android.provider.Settings.Global.getLong(
8398                        mContext.getContentResolver(),
8399                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8400                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8401                if (interval > 0) {
8402                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8403                    if (timeSinceLast > interval) {
8404                        doTrim = true;
8405                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8406                                + "; running immediately");
8407                    }
8408                }
8409                if (doTrim) {
8410                    final boolean dexOptDialogShown;
8411                    synchronized (mPackages) {
8412                        dexOptDialogShown = mDexOptDialogShown;
8413                    }
8414                    if (!isFirstBoot() && dexOptDialogShown) {
8415                        try {
8416                            ActivityManager.getService().showBootMessage(
8417                                    mContext.getResources().getString(
8418                                            R.string.android_upgrading_fstrim), true);
8419                        } catch (RemoteException e) {
8420                        }
8421                    }
8422                    sm.runMaintenance();
8423                }
8424            } else {
8425                Slog.e(TAG, "storageManager service unavailable!");
8426            }
8427        } catch (RemoteException e) {
8428            // Can't happen; StorageManagerService is local
8429        }
8430    }
8431
8432    @Override
8433    public void updatePackagesIfNeeded() {
8434        enforceSystemOrRoot("Only the system can request package update");
8435
8436        // We need to re-extract after an OTA.
8437        boolean causeUpgrade = isUpgrade();
8438
8439        // First boot or factory reset.
8440        // Note: we also handle devices that are upgrading to N right now as if it is their
8441        //       first boot, as they do not have profile data.
8442        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8443
8444        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8445        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8446
8447        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8448            return;
8449        }
8450
8451        List<PackageParser.Package> pkgs;
8452        synchronized (mPackages) {
8453            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8454        }
8455
8456        final long startTime = System.nanoTime();
8457        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8458                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8459
8460        final int elapsedTimeSeconds =
8461                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8462
8463        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8464        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8465        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8466        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8467        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8468    }
8469
8470    /**
8471     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8472     * containing statistics about the invocation. The array consists of three elements,
8473     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8474     * and {@code numberOfPackagesFailed}.
8475     */
8476    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8477            String compilerFilter) {
8478
8479        int numberOfPackagesVisited = 0;
8480        int numberOfPackagesOptimized = 0;
8481        int numberOfPackagesSkipped = 0;
8482        int numberOfPackagesFailed = 0;
8483        final int numberOfPackagesToDexopt = pkgs.size();
8484
8485        for (PackageParser.Package pkg : pkgs) {
8486            numberOfPackagesVisited++;
8487
8488            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8489                if (DEBUG_DEXOPT) {
8490                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8491                }
8492                numberOfPackagesSkipped++;
8493                continue;
8494            }
8495
8496            if (DEBUG_DEXOPT) {
8497                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8498                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8499            }
8500
8501            if (showDialog) {
8502                try {
8503                    ActivityManager.getService().showBootMessage(
8504                            mContext.getResources().getString(R.string.android_upgrading_apk,
8505                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8506                } catch (RemoteException e) {
8507                }
8508                synchronized (mPackages) {
8509                    mDexOptDialogShown = true;
8510                }
8511            }
8512
8513            // If the OTA updates a system app which was previously preopted to a non-preopted state
8514            // the app might end up being verified at runtime. That's because by default the apps
8515            // are verify-profile but for preopted apps there's no profile.
8516            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8517            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8518            // filter (by default interpret-only).
8519            // Note that at this stage unused apps are already filtered.
8520            if (isSystemApp(pkg) &&
8521                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8522                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8523                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8524            }
8525
8526            // checkProfiles is false to avoid merging profiles during boot which
8527            // might interfere with background compilation (b/28612421).
8528            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8529            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8530            // trade-off worth doing to save boot time work.
8531            int dexOptStatus = performDexOptTraced(pkg.packageName,
8532                    false /* checkProfiles */,
8533                    compilerFilter,
8534                    false /* force */);
8535            switch (dexOptStatus) {
8536                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8537                    numberOfPackagesOptimized++;
8538                    break;
8539                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8540                    numberOfPackagesSkipped++;
8541                    break;
8542                case PackageDexOptimizer.DEX_OPT_FAILED:
8543                    numberOfPackagesFailed++;
8544                    break;
8545                default:
8546                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8547                    break;
8548            }
8549        }
8550
8551        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8552                numberOfPackagesFailed };
8553    }
8554
8555    @Override
8556    public void notifyPackageUse(String packageName, int reason) {
8557        synchronized (mPackages) {
8558            PackageParser.Package p = mPackages.get(packageName);
8559            if (p == null) {
8560                return;
8561            }
8562            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8563        }
8564    }
8565
8566    @Override
8567    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8568        int userId = UserHandle.getCallingUserId();
8569        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8570        if (ai == null) {
8571            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8572                + loadingPackageName + ", user=" + userId);
8573            return;
8574        }
8575        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8576    }
8577
8578    // TODO: this is not used nor needed. Delete it.
8579    @Override
8580    public boolean performDexOptIfNeeded(String packageName) {
8581        int dexOptStatus = performDexOptTraced(packageName,
8582                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8583        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8584    }
8585
8586    @Override
8587    public boolean performDexOpt(String packageName,
8588            boolean checkProfiles, int compileReason, boolean force) {
8589        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8590                getCompilerFilterForReason(compileReason), force);
8591        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8592    }
8593
8594    @Override
8595    public boolean performDexOptMode(String packageName,
8596            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8597        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8598                targetCompilerFilter, force);
8599        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8600    }
8601
8602    private int performDexOptTraced(String packageName,
8603                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8604        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8605        try {
8606            return performDexOptInternal(packageName, checkProfiles,
8607                    targetCompilerFilter, force);
8608        } finally {
8609            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8610        }
8611    }
8612
8613    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8614    // if the package can now be considered up to date for the given filter.
8615    private int performDexOptInternal(String packageName,
8616                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8617        PackageParser.Package p;
8618        synchronized (mPackages) {
8619            p = mPackages.get(packageName);
8620            if (p == null) {
8621                // Package could not be found. Report failure.
8622                return PackageDexOptimizer.DEX_OPT_FAILED;
8623            }
8624            mPackageUsage.maybeWriteAsync(mPackages);
8625            mCompilerStats.maybeWriteAsync();
8626        }
8627        long callingId = Binder.clearCallingIdentity();
8628        try {
8629            synchronized (mInstallLock) {
8630                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8631                        targetCompilerFilter, force);
8632            }
8633        } finally {
8634            Binder.restoreCallingIdentity(callingId);
8635        }
8636    }
8637
8638    public ArraySet<String> getOptimizablePackages() {
8639        ArraySet<String> pkgs = new ArraySet<String>();
8640        synchronized (mPackages) {
8641            for (PackageParser.Package p : mPackages.values()) {
8642                if (PackageDexOptimizer.canOptimizePackage(p)) {
8643                    pkgs.add(p.packageName);
8644                }
8645            }
8646        }
8647        return pkgs;
8648    }
8649
8650    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8651            boolean checkProfiles, String targetCompilerFilter,
8652            boolean force) {
8653        // Select the dex optimizer based on the force parameter.
8654        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8655        //       allocate an object here.
8656        PackageDexOptimizer pdo = force
8657                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8658                : mPackageDexOptimizer;
8659
8660        // Dexopt all dependencies first. Note: we ignore the return value and march on
8661        // on errors.
8662        // Note that we are going to call performDexOpt on those libraries as many times as
8663        // they are referenced in packages. When we do a batch of performDexOpt (for example
8664        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8665        // and the first package that uses the library will dexopt it. The
8666        // others will see that the compiled code for the library is up to date.
8667        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8668        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8669        if (!deps.isEmpty()) {
8670            for (PackageParser.Package depPackage : deps) {
8671                // TODO: Analyze and investigate if we (should) profile libraries.
8672                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8673                        false /* checkProfiles */,
8674                        targetCompilerFilter,
8675                        getOrCreateCompilerPackageStats(depPackage),
8676                        true /* isUsedByOtherApps */);
8677            }
8678        }
8679        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8680                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8681                mDexManager.isUsedByOtherApps(p.packageName));
8682    }
8683
8684    // Performs dexopt on the used secondary dex files belonging to the given package.
8685    // Returns true if all dex files were process successfully (which could mean either dexopt or
8686    // skip). Returns false if any of the files caused errors.
8687    @Override
8688    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8689            boolean force) {
8690        mDexManager.reconcileSecondaryDexFiles(packageName);
8691        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8692    }
8693
8694    public boolean performDexOptSecondary(String packageName, int compileReason,
8695            boolean force) {
8696        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8697    }
8698
8699    /**
8700     * Reconcile the information we have about the secondary dex files belonging to
8701     * {@code packagName} and the actual dex files. For all dex files that were
8702     * deleted, update the internal records and delete the generated oat files.
8703     */
8704    @Override
8705    public void reconcileSecondaryDexFiles(String packageName) {
8706        mDexManager.reconcileSecondaryDexFiles(packageName);
8707    }
8708
8709    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8710    // a reference there.
8711    /*package*/ DexManager getDexManager() {
8712        return mDexManager;
8713    }
8714
8715    /**
8716     * Execute the background dexopt job immediately.
8717     */
8718    @Override
8719    public boolean runBackgroundDexoptJob() {
8720        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8721    }
8722
8723    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8724        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8725                || p.usesStaticLibraries != null) {
8726            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8727            Set<String> collectedNames = new HashSet<>();
8728            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8729
8730            retValue.remove(p);
8731
8732            return retValue;
8733        } else {
8734            return Collections.emptyList();
8735        }
8736    }
8737
8738    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8739            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8740        if (!collectedNames.contains(p.packageName)) {
8741            collectedNames.add(p.packageName);
8742            collected.add(p);
8743
8744            if (p.usesLibraries != null) {
8745                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8746                        null, collected, collectedNames);
8747            }
8748            if (p.usesOptionalLibraries != null) {
8749                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8750                        null, collected, collectedNames);
8751            }
8752            if (p.usesStaticLibraries != null) {
8753                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8754                        p.usesStaticLibrariesVersions, collected, collectedNames);
8755            }
8756        }
8757    }
8758
8759    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8760            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8761        final int libNameCount = libs.size();
8762        for (int i = 0; i < libNameCount; i++) {
8763            String libName = libs.get(i);
8764            int version = (versions != null && versions.length == libNameCount)
8765                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8766            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8767            if (libPkg != null) {
8768                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8769            }
8770        }
8771    }
8772
8773    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8774        synchronized (mPackages) {
8775            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8776            if (libEntry != null) {
8777                return mPackages.get(libEntry.apk);
8778            }
8779            return null;
8780        }
8781    }
8782
8783    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8784        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8785        if (versionedLib == null) {
8786            return null;
8787        }
8788        return versionedLib.get(version);
8789    }
8790
8791    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8792        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8793                pkg.staticSharedLibName);
8794        if (versionedLib == null) {
8795            return null;
8796        }
8797        int previousLibVersion = -1;
8798        final int versionCount = versionedLib.size();
8799        for (int i = 0; i < versionCount; i++) {
8800            final int libVersion = versionedLib.keyAt(i);
8801            if (libVersion < pkg.staticSharedLibVersion) {
8802                previousLibVersion = Math.max(previousLibVersion, libVersion);
8803            }
8804        }
8805        if (previousLibVersion >= 0) {
8806            return versionedLib.get(previousLibVersion);
8807        }
8808        return null;
8809    }
8810
8811    public void shutdown() {
8812        mPackageUsage.writeNow(mPackages);
8813        mCompilerStats.writeNow();
8814    }
8815
8816    @Override
8817    public void dumpProfiles(String packageName) {
8818        PackageParser.Package pkg;
8819        synchronized (mPackages) {
8820            pkg = mPackages.get(packageName);
8821            if (pkg == null) {
8822                throw new IllegalArgumentException("Unknown package: " + packageName);
8823            }
8824        }
8825        /* Only the shell, root, or the app user should be able to dump profiles. */
8826        int callingUid = Binder.getCallingUid();
8827        if (callingUid != Process.SHELL_UID &&
8828            callingUid != Process.ROOT_UID &&
8829            callingUid != pkg.applicationInfo.uid) {
8830            throw new SecurityException("dumpProfiles");
8831        }
8832
8833        synchronized (mInstallLock) {
8834            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8835            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8836            try {
8837                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8838                String codePaths = TextUtils.join(";", allCodePaths);
8839                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8840            } catch (InstallerException e) {
8841                Slog.w(TAG, "Failed to dump profiles", e);
8842            }
8843            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8844        }
8845    }
8846
8847    @Override
8848    public void forceDexOpt(String packageName) {
8849        enforceSystemOrRoot("forceDexOpt");
8850
8851        PackageParser.Package pkg;
8852        synchronized (mPackages) {
8853            pkg = mPackages.get(packageName);
8854            if (pkg == null) {
8855                throw new IllegalArgumentException("Unknown package: " + packageName);
8856            }
8857        }
8858
8859        synchronized (mInstallLock) {
8860            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8861
8862            // Whoever is calling forceDexOpt wants a fully compiled package.
8863            // Don't use profiles since that may cause compilation to be skipped.
8864            final int res = performDexOptInternalWithDependenciesLI(pkg,
8865                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8866                    true /* force */);
8867
8868            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8869            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8870                throw new IllegalStateException("Failed to dexopt: " + res);
8871            }
8872        }
8873    }
8874
8875    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8876        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8877            Slog.w(TAG, "Unable to update from " + oldPkg.name
8878                    + " to " + newPkg.packageName
8879                    + ": old package not in system partition");
8880            return false;
8881        } else if (mPackages.get(oldPkg.name) != null) {
8882            Slog.w(TAG, "Unable to update from " + oldPkg.name
8883                    + " to " + newPkg.packageName
8884                    + ": old package still exists");
8885            return false;
8886        }
8887        return true;
8888    }
8889
8890    void removeCodePathLI(File codePath) {
8891        if (codePath.isDirectory()) {
8892            try {
8893                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8894            } catch (InstallerException e) {
8895                Slog.w(TAG, "Failed to remove code path", e);
8896            }
8897        } else {
8898            codePath.delete();
8899        }
8900    }
8901
8902    private int[] resolveUserIds(int userId) {
8903        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8904    }
8905
8906    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8907        if (pkg == null) {
8908            Slog.wtf(TAG, "Package was null!", new Throwable());
8909            return;
8910        }
8911        clearAppDataLeafLIF(pkg, userId, flags);
8912        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8913        for (int i = 0; i < childCount; i++) {
8914            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8915        }
8916    }
8917
8918    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8919        final PackageSetting ps;
8920        synchronized (mPackages) {
8921            ps = mSettings.mPackages.get(pkg.packageName);
8922        }
8923        for (int realUserId : resolveUserIds(userId)) {
8924            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8925            try {
8926                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8927                        ceDataInode);
8928            } catch (InstallerException e) {
8929                Slog.w(TAG, String.valueOf(e));
8930            }
8931        }
8932    }
8933
8934    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8935        if (pkg == null) {
8936            Slog.wtf(TAG, "Package was null!", new Throwable());
8937            return;
8938        }
8939        destroyAppDataLeafLIF(pkg, userId, flags);
8940        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8941        for (int i = 0; i < childCount; i++) {
8942            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8943        }
8944    }
8945
8946    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8947        final PackageSetting ps;
8948        synchronized (mPackages) {
8949            ps = mSettings.mPackages.get(pkg.packageName);
8950        }
8951        for (int realUserId : resolveUserIds(userId)) {
8952            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8953            try {
8954                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8955                        ceDataInode);
8956            } catch (InstallerException e) {
8957                Slog.w(TAG, String.valueOf(e));
8958            }
8959            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8960        }
8961    }
8962
8963    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8964        if (pkg == null) {
8965            Slog.wtf(TAG, "Package was null!", new Throwable());
8966            return;
8967        }
8968        destroyAppProfilesLeafLIF(pkg);
8969        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8970        for (int i = 0; i < childCount; i++) {
8971            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8972        }
8973    }
8974
8975    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8976        try {
8977            mInstaller.destroyAppProfiles(pkg.packageName);
8978        } catch (InstallerException e) {
8979            Slog.w(TAG, String.valueOf(e));
8980        }
8981    }
8982
8983    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8984        if (pkg == null) {
8985            Slog.wtf(TAG, "Package was null!", new Throwable());
8986            return;
8987        }
8988        clearAppProfilesLeafLIF(pkg);
8989        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8990        for (int i = 0; i < childCount; i++) {
8991            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8992        }
8993    }
8994
8995    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8996        try {
8997            mInstaller.clearAppProfiles(pkg.packageName);
8998        } catch (InstallerException e) {
8999            Slog.w(TAG, String.valueOf(e));
9000        }
9001    }
9002
9003    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9004            long lastUpdateTime) {
9005        // Set parent install/update time
9006        PackageSetting ps = (PackageSetting) pkg.mExtras;
9007        if (ps != null) {
9008            ps.firstInstallTime = firstInstallTime;
9009            ps.lastUpdateTime = lastUpdateTime;
9010        }
9011        // Set children install/update time
9012        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9013        for (int i = 0; i < childCount; i++) {
9014            PackageParser.Package childPkg = pkg.childPackages.get(i);
9015            ps = (PackageSetting) childPkg.mExtras;
9016            if (ps != null) {
9017                ps.firstInstallTime = firstInstallTime;
9018                ps.lastUpdateTime = lastUpdateTime;
9019            }
9020        }
9021    }
9022
9023    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9024            PackageParser.Package changingLib) {
9025        if (file.path != null) {
9026            usesLibraryFiles.add(file.path);
9027            return;
9028        }
9029        PackageParser.Package p = mPackages.get(file.apk);
9030        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9031            // If we are doing this while in the middle of updating a library apk,
9032            // then we need to make sure to use that new apk for determining the
9033            // dependencies here.  (We haven't yet finished committing the new apk
9034            // to the package manager state.)
9035            if (p == null || p.packageName.equals(changingLib.packageName)) {
9036                p = changingLib;
9037            }
9038        }
9039        if (p != null) {
9040            usesLibraryFiles.addAll(p.getAllCodePaths());
9041        }
9042    }
9043
9044    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9045            PackageParser.Package changingLib) throws PackageManagerException {
9046        if (pkg == null) {
9047            return;
9048        }
9049        ArraySet<String> usesLibraryFiles = null;
9050        if (pkg.usesLibraries != null) {
9051            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9052                    null, null, pkg.packageName, changingLib, true, null);
9053        }
9054        if (pkg.usesStaticLibraries != null) {
9055            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9056                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9057                    pkg.packageName, changingLib, true, usesLibraryFiles);
9058        }
9059        if (pkg.usesOptionalLibraries != null) {
9060            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9061                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9062        }
9063        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9064            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9065        } else {
9066            pkg.usesLibraryFiles = null;
9067        }
9068    }
9069
9070    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9071            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9072            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9073            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9074            throws PackageManagerException {
9075        final int libCount = requestedLibraries.size();
9076        for (int i = 0; i < libCount; i++) {
9077            final String libName = requestedLibraries.get(i);
9078            final int libVersion = requiredVersions != null ? requiredVersions[i]
9079                    : SharedLibraryInfo.VERSION_UNDEFINED;
9080            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9081            if (libEntry == null) {
9082                if (required) {
9083                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9084                            "Package " + packageName + " requires unavailable shared library "
9085                                    + libName + "; failing!");
9086                } else {
9087                    Slog.w(TAG, "Package " + packageName
9088                            + " desires unavailable shared library "
9089                            + libName + "; ignoring!");
9090                }
9091            } else {
9092                if (requiredVersions != null && requiredCertDigests != null) {
9093                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9094                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9095                            "Package " + packageName + " requires unavailable static shared"
9096                                    + " library " + libName + " version "
9097                                    + libEntry.info.getVersion() + "; failing!");
9098                    }
9099
9100                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9101                    if (libPkg == null) {
9102                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9103                                "Package " + packageName + " requires unavailable static shared"
9104                                        + " library; failing!");
9105                    }
9106
9107                    String expectedCertDigest = requiredCertDigests[i];
9108                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9109                                libPkg.mSignatures[0]);
9110                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9111                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9112                                "Package " + packageName + " requires differently signed" +
9113                                        " static shared library; failing!");
9114                    }
9115                }
9116
9117                if (outUsedLibraries == null) {
9118                    outUsedLibraries = new ArraySet<>();
9119                }
9120                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9121            }
9122        }
9123        return outUsedLibraries;
9124    }
9125
9126    private static boolean hasString(List<String> list, List<String> which) {
9127        if (list == null) {
9128            return false;
9129        }
9130        for (int i=list.size()-1; i>=0; i--) {
9131            for (int j=which.size()-1; j>=0; j--) {
9132                if (which.get(j).equals(list.get(i))) {
9133                    return true;
9134                }
9135            }
9136        }
9137        return false;
9138    }
9139
9140    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9141            PackageParser.Package changingPkg) {
9142        ArrayList<PackageParser.Package> res = null;
9143        for (PackageParser.Package pkg : mPackages.values()) {
9144            if (changingPkg != null
9145                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9146                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9147                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9148                            changingPkg.staticSharedLibName)) {
9149                return null;
9150            }
9151            if (res == null) {
9152                res = new ArrayList<>();
9153            }
9154            res.add(pkg);
9155            try {
9156                updateSharedLibrariesLPr(pkg, changingPkg);
9157            } catch (PackageManagerException e) {
9158                // If a system app update or an app and a required lib missing we
9159                // delete the package and for updated system apps keep the data as
9160                // it is better for the user to reinstall than to be in an limbo
9161                // state. Also libs disappearing under an app should never happen
9162                // - just in case.
9163                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9164                    final int flags = pkg.isUpdatedSystemApp()
9165                            ? PackageManager.DELETE_KEEP_DATA : 0;
9166                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9167                            flags , null, true, null);
9168                }
9169                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9170            }
9171        }
9172        return res;
9173    }
9174
9175    /**
9176     * Derive the value of the {@code cpuAbiOverride} based on the provided
9177     * value and an optional stored value from the package settings.
9178     */
9179    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9180        String cpuAbiOverride = null;
9181
9182        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9183            cpuAbiOverride = null;
9184        } else if (abiOverride != null) {
9185            cpuAbiOverride = abiOverride;
9186        } else if (settings != null) {
9187            cpuAbiOverride = settings.cpuAbiOverrideString;
9188        }
9189
9190        return cpuAbiOverride;
9191    }
9192
9193    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9194            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9195                    throws PackageManagerException {
9196        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9197        // If the package has children and this is the first dive in the function
9198        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9199        // whether all packages (parent and children) would be successfully scanned
9200        // before the actual scan since scanning mutates internal state and we want
9201        // to atomically install the package and its children.
9202        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9203            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9204                scanFlags |= SCAN_CHECK_ONLY;
9205            }
9206        } else {
9207            scanFlags &= ~SCAN_CHECK_ONLY;
9208        }
9209
9210        final PackageParser.Package scannedPkg;
9211        try {
9212            // Scan the parent
9213            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9214            // Scan the children
9215            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9216            for (int i = 0; i < childCount; i++) {
9217                PackageParser.Package childPkg = pkg.childPackages.get(i);
9218                scanPackageLI(childPkg, policyFlags,
9219                        scanFlags, currentTime, user);
9220            }
9221        } finally {
9222            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9223        }
9224
9225        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9226            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9227        }
9228
9229        return scannedPkg;
9230    }
9231
9232    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9233            int scanFlags, long currentTime, @Nullable UserHandle user)
9234                    throws PackageManagerException {
9235        boolean success = false;
9236        try {
9237            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9238                    currentTime, user);
9239            success = true;
9240            return res;
9241        } finally {
9242            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9243                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9244                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9245                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9246                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9247            }
9248        }
9249    }
9250
9251    /**
9252     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9253     */
9254    private static boolean apkHasCode(String fileName) {
9255        StrictJarFile jarFile = null;
9256        try {
9257            jarFile = new StrictJarFile(fileName,
9258                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9259            return jarFile.findEntry("classes.dex") != null;
9260        } catch (IOException ignore) {
9261        } finally {
9262            try {
9263                if (jarFile != null) {
9264                    jarFile.close();
9265                }
9266            } catch (IOException ignore) {}
9267        }
9268        return false;
9269    }
9270
9271    /**
9272     * Enforces code policy for the package. This ensures that if an APK has
9273     * declared hasCode="true" in its manifest that the APK actually contains
9274     * code.
9275     *
9276     * @throws PackageManagerException If bytecode could not be found when it should exist
9277     */
9278    private static void assertCodePolicy(PackageParser.Package pkg)
9279            throws PackageManagerException {
9280        final boolean shouldHaveCode =
9281                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9282        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9283            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9284                    "Package " + pkg.baseCodePath + " code is missing");
9285        }
9286
9287        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9288            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9289                final boolean splitShouldHaveCode =
9290                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9291                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9292                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9293                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9294                }
9295            }
9296        }
9297    }
9298
9299    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9300            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9301                    throws PackageManagerException {
9302        if (DEBUG_PACKAGE_SCANNING) {
9303            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9304                Log.d(TAG, "Scanning package " + pkg.packageName);
9305        }
9306
9307        applyPolicy(pkg, policyFlags);
9308
9309        assertPackageIsValid(pkg, policyFlags, scanFlags);
9310
9311        // Initialize package source and resource directories
9312        final File scanFile = new File(pkg.codePath);
9313        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9314        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9315
9316        SharedUserSetting suid = null;
9317        PackageSetting pkgSetting = null;
9318
9319        // Getting the package setting may have a side-effect, so if we
9320        // are only checking if scan would succeed, stash a copy of the
9321        // old setting to restore at the end.
9322        PackageSetting nonMutatedPs = null;
9323
9324        // We keep references to the derived CPU Abis from settings in oder to reuse
9325        // them in the case where we're not upgrading or booting for the first time.
9326        String primaryCpuAbiFromSettings = null;
9327        String secondaryCpuAbiFromSettings = null;
9328
9329        // writer
9330        synchronized (mPackages) {
9331            if (pkg.mSharedUserId != null) {
9332                // SIDE EFFECTS; may potentially allocate a new shared user
9333                suid = mSettings.getSharedUserLPw(
9334                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9335                if (DEBUG_PACKAGE_SCANNING) {
9336                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9337                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9338                                + "): packages=" + suid.packages);
9339                }
9340            }
9341
9342            // Check if we are renaming from an original package name.
9343            PackageSetting origPackage = null;
9344            String realName = null;
9345            if (pkg.mOriginalPackages != null) {
9346                // This package may need to be renamed to a previously
9347                // installed name.  Let's check on that...
9348                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9349                if (pkg.mOriginalPackages.contains(renamed)) {
9350                    // This package had originally been installed as the
9351                    // original name, and we have already taken care of
9352                    // transitioning to the new one.  Just update the new
9353                    // one to continue using the old name.
9354                    realName = pkg.mRealPackage;
9355                    if (!pkg.packageName.equals(renamed)) {
9356                        // Callers into this function may have already taken
9357                        // care of renaming the package; only do it here if
9358                        // it is not already done.
9359                        pkg.setPackageName(renamed);
9360                    }
9361                } else {
9362                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9363                        if ((origPackage = mSettings.getPackageLPr(
9364                                pkg.mOriginalPackages.get(i))) != null) {
9365                            // We do have the package already installed under its
9366                            // original name...  should we use it?
9367                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9368                                // New package is not compatible with original.
9369                                origPackage = null;
9370                                continue;
9371                            } else if (origPackage.sharedUser != null) {
9372                                // Make sure uid is compatible between packages.
9373                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9374                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9375                                            + " to " + pkg.packageName + ": old uid "
9376                                            + origPackage.sharedUser.name
9377                                            + " differs from " + pkg.mSharedUserId);
9378                                    origPackage = null;
9379                                    continue;
9380                                }
9381                                // TODO: Add case when shared user id is added [b/28144775]
9382                            } else {
9383                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9384                                        + pkg.packageName + " to old name " + origPackage.name);
9385                            }
9386                            break;
9387                        }
9388                    }
9389                }
9390            }
9391
9392            if (mTransferedPackages.contains(pkg.packageName)) {
9393                Slog.w(TAG, "Package " + pkg.packageName
9394                        + " was transferred to another, but its .apk remains");
9395            }
9396
9397            // See comments in nonMutatedPs declaration
9398            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9399                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9400                if (foundPs != null) {
9401                    nonMutatedPs = new PackageSetting(foundPs);
9402                }
9403            }
9404
9405            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9406                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9407                if (foundPs != null) {
9408                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9409                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9410                }
9411            }
9412
9413            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9414            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9415                PackageManagerService.reportSettingsProblem(Log.WARN,
9416                        "Package " + pkg.packageName + " shared user changed from "
9417                                + (pkgSetting.sharedUser != null
9418                                        ? pkgSetting.sharedUser.name : "<nothing>")
9419                                + " to "
9420                                + (suid != null ? suid.name : "<nothing>")
9421                                + "; replacing with new");
9422                pkgSetting = null;
9423            }
9424            final PackageSetting oldPkgSetting =
9425                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9426            final PackageSetting disabledPkgSetting =
9427                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9428
9429            String[] usesStaticLibraries = null;
9430            if (pkg.usesStaticLibraries != null) {
9431                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9432                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9433            }
9434
9435            if (pkgSetting == null) {
9436                final String parentPackageName = (pkg.parentPackage != null)
9437                        ? pkg.parentPackage.packageName : null;
9438                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9439                // REMOVE SharedUserSetting from method; update in a separate call
9440                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9441                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9442                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9443                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9444                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9445                        true /*allowInstall*/, instantApp, parentPackageName,
9446                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9447                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9448                // SIDE EFFECTS; updates system state; move elsewhere
9449                if (origPackage != null) {
9450                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9451                }
9452                mSettings.addUserToSettingLPw(pkgSetting);
9453            } else {
9454                // REMOVE SharedUserSetting from method; update in a separate call.
9455                //
9456                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9457                // secondaryCpuAbi are not known at this point so we always update them
9458                // to null here, only to reset them at a later point.
9459                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9460                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9461                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9462                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9463                        UserManagerService.getInstance(), usesStaticLibraries,
9464                        pkg.usesStaticLibrariesVersions);
9465            }
9466            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9467            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9468
9469            // SIDE EFFECTS; modifies system state; move elsewhere
9470            if (pkgSetting.origPackage != null) {
9471                // If we are first transitioning from an original package,
9472                // fix up the new package's name now.  We need to do this after
9473                // looking up the package under its new name, so getPackageLP
9474                // can take care of fiddling things correctly.
9475                pkg.setPackageName(origPackage.name);
9476
9477                // File a report about this.
9478                String msg = "New package " + pkgSetting.realName
9479                        + " renamed to replace old package " + pkgSetting.name;
9480                reportSettingsProblem(Log.WARN, msg);
9481
9482                // Make a note of it.
9483                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9484                    mTransferedPackages.add(origPackage.name);
9485                }
9486
9487                // No longer need to retain this.
9488                pkgSetting.origPackage = null;
9489            }
9490
9491            // SIDE EFFECTS; modifies system state; move elsewhere
9492            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9493                // Make a note of it.
9494                mTransferedPackages.add(pkg.packageName);
9495            }
9496
9497            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9498                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9499            }
9500
9501            if ((scanFlags & SCAN_BOOTING) == 0
9502                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9503                // Check all shared libraries and map to their actual file path.
9504                // We only do this here for apps not on a system dir, because those
9505                // are the only ones that can fail an install due to this.  We
9506                // will take care of the system apps by updating all of their
9507                // library paths after the scan is done. Also during the initial
9508                // scan don't update any libs as we do this wholesale after all
9509                // apps are scanned to avoid dependency based scanning.
9510                updateSharedLibrariesLPr(pkg, null);
9511            }
9512
9513            if (mFoundPolicyFile) {
9514                SELinuxMMAC.assignSeInfoValue(pkg);
9515            }
9516            pkg.applicationInfo.uid = pkgSetting.appId;
9517            pkg.mExtras = pkgSetting;
9518
9519
9520            // Static shared libs have same package with different versions where
9521            // we internally use a synthetic package name to allow multiple versions
9522            // of the same package, therefore we need to compare signatures against
9523            // the package setting for the latest library version.
9524            PackageSetting signatureCheckPs = pkgSetting;
9525            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9526                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9527                if (libraryEntry != null) {
9528                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9529                }
9530            }
9531
9532            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9533                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9534                    // We just determined the app is signed correctly, so bring
9535                    // over the latest parsed certs.
9536                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9537                } else {
9538                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9539                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9540                                "Package " + pkg.packageName + " upgrade keys do not match the "
9541                                + "previously installed version");
9542                    } else {
9543                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9544                        String msg = "System package " + pkg.packageName
9545                                + " signature changed; retaining data.";
9546                        reportSettingsProblem(Log.WARN, msg);
9547                    }
9548                }
9549            } else {
9550                try {
9551                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9552                    verifySignaturesLP(signatureCheckPs, pkg);
9553                    // We just determined the app is signed correctly, so bring
9554                    // over the latest parsed certs.
9555                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9556                } catch (PackageManagerException e) {
9557                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9558                        throw e;
9559                    }
9560                    // The signature has changed, but this package is in the system
9561                    // image...  let's recover!
9562                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9563                    // However...  if this package is part of a shared user, but it
9564                    // doesn't match the signature of the shared user, let's fail.
9565                    // What this means is that you can't change the signatures
9566                    // associated with an overall shared user, which doesn't seem all
9567                    // that unreasonable.
9568                    if (signatureCheckPs.sharedUser != null) {
9569                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9570                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9571                            throw new PackageManagerException(
9572                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9573                                    "Signature mismatch for shared user: "
9574                                            + pkgSetting.sharedUser);
9575                        }
9576                    }
9577                    // File a report about this.
9578                    String msg = "System package " + pkg.packageName
9579                            + " signature changed; retaining data.";
9580                    reportSettingsProblem(Log.WARN, msg);
9581                }
9582            }
9583
9584            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9585                // This package wants to adopt ownership of permissions from
9586                // another package.
9587                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9588                    final String origName = pkg.mAdoptPermissions.get(i);
9589                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9590                    if (orig != null) {
9591                        if (verifyPackageUpdateLPr(orig, pkg)) {
9592                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9593                                    + pkg.packageName);
9594                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9595                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9596                        }
9597                    }
9598                }
9599            }
9600        }
9601
9602        pkg.applicationInfo.processName = fixProcessName(
9603                pkg.applicationInfo.packageName,
9604                pkg.applicationInfo.processName);
9605
9606        if (pkg != mPlatformPackage) {
9607            // Get all of our default paths setup
9608            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9609        }
9610
9611        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9612
9613        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9614            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9615                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9616                derivePackageAbi(
9617                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9618                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9619
9620                // Some system apps still use directory structure for native libraries
9621                // in which case we might end up not detecting abi solely based on apk
9622                // structure. Try to detect abi based on directory structure.
9623                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9624                        pkg.applicationInfo.primaryCpuAbi == null) {
9625                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9626                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9627                }
9628            } else {
9629                // This is not a first boot or an upgrade, don't bother deriving the
9630                // ABI during the scan. Instead, trust the value that was stored in the
9631                // package setting.
9632                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9633                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9634
9635                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9636
9637                if (DEBUG_ABI_SELECTION) {
9638                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9639                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9640                        pkg.applicationInfo.secondaryCpuAbi);
9641                }
9642            }
9643        } else {
9644            if ((scanFlags & SCAN_MOVE) != 0) {
9645                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9646                // but we already have this packages package info in the PackageSetting. We just
9647                // use that and derive the native library path based on the new codepath.
9648                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9649                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9650            }
9651
9652            // Set native library paths again. For moves, the path will be updated based on the
9653            // ABIs we've determined above. For non-moves, the path will be updated based on the
9654            // ABIs we determined during compilation, but the path will depend on the final
9655            // package path (after the rename away from the stage path).
9656            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9657        }
9658
9659        // This is a special case for the "system" package, where the ABI is
9660        // dictated by the zygote configuration (and init.rc). We should keep track
9661        // of this ABI so that we can deal with "normal" applications that run under
9662        // the same UID correctly.
9663        if (mPlatformPackage == pkg) {
9664            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9665                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9666        }
9667
9668        // If there's a mismatch between the abi-override in the package setting
9669        // and the abiOverride specified for the install. Warn about this because we
9670        // would've already compiled the app without taking the package setting into
9671        // account.
9672        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9673            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9674                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9675                        " for package " + pkg.packageName);
9676            }
9677        }
9678
9679        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9680        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9681        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9682
9683        // Copy the derived override back to the parsed package, so that we can
9684        // update the package settings accordingly.
9685        pkg.cpuAbiOverride = cpuAbiOverride;
9686
9687        if (DEBUG_ABI_SELECTION) {
9688            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9689                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9690                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9691        }
9692
9693        // Push the derived path down into PackageSettings so we know what to
9694        // clean up at uninstall time.
9695        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9696
9697        if (DEBUG_ABI_SELECTION) {
9698            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9699                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9700                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9701        }
9702
9703        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9704        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9705            // We don't do this here during boot because we can do it all
9706            // at once after scanning all existing packages.
9707            //
9708            // We also do this *before* we perform dexopt on this package, so that
9709            // we can avoid redundant dexopts, and also to make sure we've got the
9710            // code and package path correct.
9711            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9712        }
9713
9714        if (mFactoryTest && pkg.requestedPermissions.contains(
9715                android.Manifest.permission.FACTORY_TEST)) {
9716            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9717        }
9718
9719        if (isSystemApp(pkg)) {
9720            pkgSetting.isOrphaned = true;
9721        }
9722
9723        // Take care of first install / last update times.
9724        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9725        if (currentTime != 0) {
9726            if (pkgSetting.firstInstallTime == 0) {
9727                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9728            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9729                pkgSetting.lastUpdateTime = currentTime;
9730            }
9731        } else if (pkgSetting.firstInstallTime == 0) {
9732            // We need *something*.  Take time time stamp of the file.
9733            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9734        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9735            if (scanFileTime != pkgSetting.timeStamp) {
9736                // A package on the system image has changed; consider this
9737                // to be an update.
9738                pkgSetting.lastUpdateTime = scanFileTime;
9739            }
9740        }
9741        pkgSetting.setTimeStamp(scanFileTime);
9742
9743        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9744            if (nonMutatedPs != null) {
9745                synchronized (mPackages) {
9746                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9747                }
9748            }
9749        } else {
9750            final int userId = user == null ? 0 : user.getIdentifier();
9751            // Modify state for the given package setting
9752            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9753                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9754            if (pkgSetting.getInstantApp(userId)) {
9755                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9756            }
9757        }
9758        return pkg;
9759    }
9760
9761    /**
9762     * Applies policy to the parsed package based upon the given policy flags.
9763     * Ensures the package is in a good state.
9764     * <p>
9765     * Implementation detail: This method must NOT have any side effect. It would
9766     * ideally be static, but, it requires locks to read system state.
9767     */
9768    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9769        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9770            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9771            if (pkg.applicationInfo.isDirectBootAware()) {
9772                // we're direct boot aware; set for all components
9773                for (PackageParser.Service s : pkg.services) {
9774                    s.info.encryptionAware = s.info.directBootAware = true;
9775                }
9776                for (PackageParser.Provider p : pkg.providers) {
9777                    p.info.encryptionAware = p.info.directBootAware = true;
9778                }
9779                for (PackageParser.Activity a : pkg.activities) {
9780                    a.info.encryptionAware = a.info.directBootAware = true;
9781                }
9782                for (PackageParser.Activity r : pkg.receivers) {
9783                    r.info.encryptionAware = r.info.directBootAware = true;
9784                }
9785            }
9786        } else {
9787            // Only allow system apps to be flagged as core apps.
9788            pkg.coreApp = false;
9789            // clear flags not applicable to regular apps
9790            pkg.applicationInfo.privateFlags &=
9791                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9792            pkg.applicationInfo.privateFlags &=
9793                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9794        }
9795        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9796
9797        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9798            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9799        }
9800
9801        if (!isSystemApp(pkg)) {
9802            // Only system apps can use these features.
9803            pkg.mOriginalPackages = null;
9804            pkg.mRealPackage = null;
9805            pkg.mAdoptPermissions = null;
9806        }
9807    }
9808
9809    /**
9810     * Asserts the parsed package is valid according to the given policy. If the
9811     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9812     * <p>
9813     * Implementation detail: This method must NOT have any side effects. It would
9814     * ideally be static, but, it requires locks to read system state.
9815     *
9816     * @throws PackageManagerException If the package fails any of the validation checks
9817     */
9818    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9819            throws PackageManagerException {
9820        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9821            assertCodePolicy(pkg);
9822        }
9823
9824        if (pkg.applicationInfo.getCodePath() == null ||
9825                pkg.applicationInfo.getResourcePath() == null) {
9826            // Bail out. The resource and code paths haven't been set.
9827            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9828                    "Code and resource paths haven't been set correctly");
9829        }
9830
9831        // Make sure we're not adding any bogus keyset info
9832        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9833        ksms.assertScannedPackageValid(pkg);
9834
9835        synchronized (mPackages) {
9836            // The special "android" package can only be defined once
9837            if (pkg.packageName.equals("android")) {
9838                if (mAndroidApplication != null) {
9839                    Slog.w(TAG, "*************************************************");
9840                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9841                    Slog.w(TAG, " codePath=" + pkg.codePath);
9842                    Slog.w(TAG, "*************************************************");
9843                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9844                            "Core android package being redefined.  Skipping.");
9845                }
9846            }
9847
9848            // A package name must be unique; don't allow duplicates
9849            if (mPackages.containsKey(pkg.packageName)) {
9850                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9851                        "Application package " + pkg.packageName
9852                        + " already installed.  Skipping duplicate.");
9853            }
9854
9855            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9856                // Static libs have a synthetic package name containing the version
9857                // but we still want the base name to be unique.
9858                if (mPackages.containsKey(pkg.manifestPackageName)) {
9859                    throw new PackageManagerException(
9860                            "Duplicate static shared lib provider package");
9861                }
9862
9863                // Static shared libraries should have at least O target SDK
9864                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9865                    throw new PackageManagerException(
9866                            "Packages declaring static-shared libs must target O SDK or higher");
9867                }
9868
9869                // Package declaring static a shared lib cannot be instant apps
9870                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9871                    throw new PackageManagerException(
9872                            "Packages declaring static-shared libs cannot be instant apps");
9873                }
9874
9875                // Package declaring static a shared lib cannot be renamed since the package
9876                // name is synthetic and apps can't code around package manager internals.
9877                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9878                    throw new PackageManagerException(
9879                            "Packages declaring static-shared libs cannot be renamed");
9880                }
9881
9882                // Package declaring static a shared lib cannot declare child packages
9883                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9884                    throw new PackageManagerException(
9885                            "Packages declaring static-shared libs cannot have child packages");
9886                }
9887
9888                // Package declaring static a shared lib cannot declare dynamic libs
9889                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9890                    throw new PackageManagerException(
9891                            "Packages declaring static-shared libs cannot declare dynamic libs");
9892                }
9893
9894                // Package declaring static a shared lib cannot declare shared users
9895                if (pkg.mSharedUserId != null) {
9896                    throw new PackageManagerException(
9897                            "Packages declaring static-shared libs cannot declare shared users");
9898                }
9899
9900                // Static shared libs cannot declare activities
9901                if (!pkg.activities.isEmpty()) {
9902                    throw new PackageManagerException(
9903                            "Static shared libs cannot declare activities");
9904                }
9905
9906                // Static shared libs cannot declare services
9907                if (!pkg.services.isEmpty()) {
9908                    throw new PackageManagerException(
9909                            "Static shared libs cannot declare services");
9910                }
9911
9912                // Static shared libs cannot declare providers
9913                if (!pkg.providers.isEmpty()) {
9914                    throw new PackageManagerException(
9915                            "Static shared libs cannot declare content providers");
9916                }
9917
9918                // Static shared libs cannot declare receivers
9919                if (!pkg.receivers.isEmpty()) {
9920                    throw new PackageManagerException(
9921                            "Static shared libs cannot declare broadcast receivers");
9922                }
9923
9924                // Static shared libs cannot declare permission groups
9925                if (!pkg.permissionGroups.isEmpty()) {
9926                    throw new PackageManagerException(
9927                            "Static shared libs cannot declare permission groups");
9928                }
9929
9930                // Static shared libs cannot declare permissions
9931                if (!pkg.permissions.isEmpty()) {
9932                    throw new PackageManagerException(
9933                            "Static shared libs cannot declare permissions");
9934                }
9935
9936                // Static shared libs cannot declare protected broadcasts
9937                if (pkg.protectedBroadcasts != null) {
9938                    throw new PackageManagerException(
9939                            "Static shared libs cannot declare protected broadcasts");
9940                }
9941
9942                // Static shared libs cannot be overlay targets
9943                if (pkg.mOverlayTarget != null) {
9944                    throw new PackageManagerException(
9945                            "Static shared libs cannot be overlay targets");
9946                }
9947
9948                // The version codes must be ordered as lib versions
9949                int minVersionCode = Integer.MIN_VALUE;
9950                int maxVersionCode = Integer.MAX_VALUE;
9951
9952                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9953                        pkg.staticSharedLibName);
9954                if (versionedLib != null) {
9955                    final int versionCount = versionedLib.size();
9956                    for (int i = 0; i < versionCount; i++) {
9957                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9958                        // TODO: We will change version code to long, so in the new API it is long
9959                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9960                                .getVersionCode();
9961                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9962                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9963                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9964                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9965                        } else {
9966                            minVersionCode = maxVersionCode = libVersionCode;
9967                            break;
9968                        }
9969                    }
9970                }
9971                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9972                    throw new PackageManagerException("Static shared"
9973                            + " lib version codes must be ordered as lib versions");
9974                }
9975            }
9976
9977            // Only privileged apps and updated privileged apps can add child packages.
9978            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9979                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9980                    throw new PackageManagerException("Only privileged apps can add child "
9981                            + "packages. Ignoring package " + pkg.packageName);
9982                }
9983                final int childCount = pkg.childPackages.size();
9984                for (int i = 0; i < childCount; i++) {
9985                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9986                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9987                            childPkg.packageName)) {
9988                        throw new PackageManagerException("Can't override child of "
9989                                + "another disabled app. Ignoring package " + pkg.packageName);
9990                    }
9991                }
9992            }
9993
9994            // If we're only installing presumed-existing packages, require that the
9995            // scanned APK is both already known and at the path previously established
9996            // for it.  Previously unknown packages we pick up normally, but if we have an
9997            // a priori expectation about this package's install presence, enforce it.
9998            // With a singular exception for new system packages. When an OTA contains
9999            // a new system package, we allow the codepath to change from a system location
10000            // to the user-installed location. If we don't allow this change, any newer,
10001            // user-installed version of the application will be ignored.
10002            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10003                if (mExpectingBetter.containsKey(pkg.packageName)) {
10004                    logCriticalInfo(Log.WARN,
10005                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10006                } else {
10007                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10008                    if (known != null) {
10009                        if (DEBUG_PACKAGE_SCANNING) {
10010                            Log.d(TAG, "Examining " + pkg.codePath
10011                                    + " and requiring known paths " + known.codePathString
10012                                    + " & " + known.resourcePathString);
10013                        }
10014                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10015                                || !pkg.applicationInfo.getResourcePath().equals(
10016                                        known.resourcePathString)) {
10017                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10018                                    "Application package " + pkg.packageName
10019                                    + " found at " + pkg.applicationInfo.getCodePath()
10020                                    + " but expected at " + known.codePathString
10021                                    + "; ignoring.");
10022                        }
10023                    }
10024                }
10025            }
10026
10027            // Verify that this new package doesn't have any content providers
10028            // that conflict with existing packages.  Only do this if the
10029            // package isn't already installed, since we don't want to break
10030            // things that are installed.
10031            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10032                final int N = pkg.providers.size();
10033                int i;
10034                for (i=0; i<N; i++) {
10035                    PackageParser.Provider p = pkg.providers.get(i);
10036                    if (p.info.authority != null) {
10037                        String names[] = p.info.authority.split(";");
10038                        for (int j = 0; j < names.length; j++) {
10039                            if (mProvidersByAuthority.containsKey(names[j])) {
10040                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10041                                final String otherPackageName =
10042                                        ((other != null && other.getComponentName() != null) ?
10043                                                other.getComponentName().getPackageName() : "?");
10044                                throw new PackageManagerException(
10045                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10046                                        "Can't install because provider name " + names[j]
10047                                                + " (in package " + pkg.applicationInfo.packageName
10048                                                + ") is already used by " + otherPackageName);
10049                            }
10050                        }
10051                    }
10052                }
10053            }
10054        }
10055    }
10056
10057    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10058            int type, String declaringPackageName, int declaringVersionCode) {
10059        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10060        if (versionedLib == null) {
10061            versionedLib = new SparseArray<>();
10062            mSharedLibraries.put(name, versionedLib);
10063            if (type == SharedLibraryInfo.TYPE_STATIC) {
10064                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10065            }
10066        } else if (versionedLib.indexOfKey(version) >= 0) {
10067            return false;
10068        }
10069        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10070                version, type, declaringPackageName, declaringVersionCode);
10071        versionedLib.put(version, libEntry);
10072        return true;
10073    }
10074
10075    private boolean removeSharedLibraryLPw(String name, int version) {
10076        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10077        if (versionedLib == null) {
10078            return false;
10079        }
10080        final int libIdx = versionedLib.indexOfKey(version);
10081        if (libIdx < 0) {
10082            return false;
10083        }
10084        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10085        versionedLib.remove(version);
10086        if (versionedLib.size() <= 0) {
10087            mSharedLibraries.remove(name);
10088            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10089                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10090                        .getPackageName());
10091            }
10092        }
10093        return true;
10094    }
10095
10096    /**
10097     * Adds a scanned package to the system. When this method is finished, the package will
10098     * be available for query, resolution, etc...
10099     */
10100    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10101            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10102        final String pkgName = pkg.packageName;
10103        if (mCustomResolverComponentName != null &&
10104                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10105            setUpCustomResolverActivity(pkg);
10106        }
10107
10108        if (pkg.packageName.equals("android")) {
10109            synchronized (mPackages) {
10110                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10111                    // Set up information for our fall-back user intent resolution activity.
10112                    mPlatformPackage = pkg;
10113                    pkg.mVersionCode = mSdkVersion;
10114                    mAndroidApplication = pkg.applicationInfo;
10115                    if (!mResolverReplaced) {
10116                        mResolveActivity.applicationInfo = mAndroidApplication;
10117                        mResolveActivity.name = ResolverActivity.class.getName();
10118                        mResolveActivity.packageName = mAndroidApplication.packageName;
10119                        mResolveActivity.processName = "system:ui";
10120                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10121                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10122                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10123                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10124                        mResolveActivity.exported = true;
10125                        mResolveActivity.enabled = true;
10126                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10127                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10128                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10129                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10130                                | ActivityInfo.CONFIG_ORIENTATION
10131                                | ActivityInfo.CONFIG_KEYBOARD
10132                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10133                        mResolveInfo.activityInfo = mResolveActivity;
10134                        mResolveInfo.priority = 0;
10135                        mResolveInfo.preferredOrder = 0;
10136                        mResolveInfo.match = 0;
10137                        mResolveComponentName = new ComponentName(
10138                                mAndroidApplication.packageName, mResolveActivity.name);
10139                    }
10140                }
10141            }
10142        }
10143
10144        ArrayList<PackageParser.Package> clientLibPkgs = null;
10145        // writer
10146        synchronized (mPackages) {
10147            boolean hasStaticSharedLibs = false;
10148
10149            // Any app can add new static shared libraries
10150            if (pkg.staticSharedLibName != null) {
10151                // Static shared libs don't allow renaming as they have synthetic package
10152                // names to allow install of multiple versions, so use name from manifest.
10153                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10154                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10155                        pkg.manifestPackageName, pkg.mVersionCode)) {
10156                    hasStaticSharedLibs = true;
10157                } else {
10158                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10159                                + pkg.staticSharedLibName + " already exists; skipping");
10160                }
10161                // Static shared libs cannot be updated once installed since they
10162                // use synthetic package name which includes the version code, so
10163                // not need to update other packages's shared lib dependencies.
10164            }
10165
10166            if (!hasStaticSharedLibs
10167                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10168                // Only system apps can add new dynamic shared libraries.
10169                if (pkg.libraryNames != null) {
10170                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10171                        String name = pkg.libraryNames.get(i);
10172                        boolean allowed = false;
10173                        if (pkg.isUpdatedSystemApp()) {
10174                            // New library entries can only be added through the
10175                            // system image.  This is important to get rid of a lot
10176                            // of nasty edge cases: for example if we allowed a non-
10177                            // system update of the app to add a library, then uninstalling
10178                            // the update would make the library go away, and assumptions
10179                            // we made such as through app install filtering would now
10180                            // have allowed apps on the device which aren't compatible
10181                            // with it.  Better to just have the restriction here, be
10182                            // conservative, and create many fewer cases that can negatively
10183                            // impact the user experience.
10184                            final PackageSetting sysPs = mSettings
10185                                    .getDisabledSystemPkgLPr(pkg.packageName);
10186                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10187                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10188                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10189                                        allowed = true;
10190                                        break;
10191                                    }
10192                                }
10193                            }
10194                        } else {
10195                            allowed = true;
10196                        }
10197                        if (allowed) {
10198                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10199                                    SharedLibraryInfo.VERSION_UNDEFINED,
10200                                    SharedLibraryInfo.TYPE_DYNAMIC,
10201                                    pkg.packageName, pkg.mVersionCode)) {
10202                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10203                                        + name + " already exists; skipping");
10204                            }
10205                        } else {
10206                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10207                                    + name + " that is not declared on system image; skipping");
10208                        }
10209                    }
10210
10211                    if ((scanFlags & SCAN_BOOTING) == 0) {
10212                        // If we are not booting, we need to update any applications
10213                        // that are clients of our shared library.  If we are booting,
10214                        // this will all be done once the scan is complete.
10215                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10216                    }
10217                }
10218            }
10219        }
10220
10221        if ((scanFlags & SCAN_BOOTING) != 0) {
10222            // No apps can run during boot scan, so they don't need to be frozen
10223        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10224            // Caller asked to not kill app, so it's probably not frozen
10225        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10226            // Caller asked us to ignore frozen check for some reason; they
10227            // probably didn't know the package name
10228        } else {
10229            // We're doing major surgery on this package, so it better be frozen
10230            // right now to keep it from launching
10231            checkPackageFrozen(pkgName);
10232        }
10233
10234        // Also need to kill any apps that are dependent on the library.
10235        if (clientLibPkgs != null) {
10236            for (int i=0; i<clientLibPkgs.size(); i++) {
10237                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10238                killApplication(clientPkg.applicationInfo.packageName,
10239                        clientPkg.applicationInfo.uid, "update lib");
10240            }
10241        }
10242
10243        // writer
10244        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10245
10246        synchronized (mPackages) {
10247            // We don't expect installation to fail beyond this point
10248
10249            // Add the new setting to mSettings
10250            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10251            // Add the new setting to mPackages
10252            mPackages.put(pkg.applicationInfo.packageName, pkg);
10253            // Make sure we don't accidentally delete its data.
10254            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10255            while (iter.hasNext()) {
10256                PackageCleanItem item = iter.next();
10257                if (pkgName.equals(item.packageName)) {
10258                    iter.remove();
10259                }
10260            }
10261
10262            // Add the package's KeySets to the global KeySetManagerService
10263            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10264            ksms.addScannedPackageLPw(pkg);
10265
10266            int N = pkg.providers.size();
10267            StringBuilder r = null;
10268            int i;
10269            for (i=0; i<N; i++) {
10270                PackageParser.Provider p = pkg.providers.get(i);
10271                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10272                        p.info.processName);
10273                mProviders.addProvider(p);
10274                p.syncable = p.info.isSyncable;
10275                if (p.info.authority != null) {
10276                    String names[] = p.info.authority.split(";");
10277                    p.info.authority = null;
10278                    for (int j = 0; j < names.length; j++) {
10279                        if (j == 1 && p.syncable) {
10280                            // We only want the first authority for a provider to possibly be
10281                            // syncable, so if we already added this provider using a different
10282                            // authority clear the syncable flag. We copy the provider before
10283                            // changing it because the mProviders object contains a reference
10284                            // to a provider that we don't want to change.
10285                            // Only do this for the second authority since the resulting provider
10286                            // object can be the same for all future authorities for this provider.
10287                            p = new PackageParser.Provider(p);
10288                            p.syncable = false;
10289                        }
10290                        if (!mProvidersByAuthority.containsKey(names[j])) {
10291                            mProvidersByAuthority.put(names[j], p);
10292                            if (p.info.authority == null) {
10293                                p.info.authority = names[j];
10294                            } else {
10295                                p.info.authority = p.info.authority + ";" + names[j];
10296                            }
10297                            if (DEBUG_PACKAGE_SCANNING) {
10298                                if (chatty)
10299                                    Log.d(TAG, "Registered content provider: " + names[j]
10300                                            + ", className = " + p.info.name + ", isSyncable = "
10301                                            + p.info.isSyncable);
10302                            }
10303                        } else {
10304                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10305                            Slog.w(TAG, "Skipping provider name " + names[j] +
10306                                    " (in package " + pkg.applicationInfo.packageName +
10307                                    "): name already used by "
10308                                    + ((other != null && other.getComponentName() != null)
10309                                            ? other.getComponentName().getPackageName() : "?"));
10310                        }
10311                    }
10312                }
10313                if (chatty) {
10314                    if (r == null) {
10315                        r = new StringBuilder(256);
10316                    } else {
10317                        r.append(' ');
10318                    }
10319                    r.append(p.info.name);
10320                }
10321            }
10322            if (r != null) {
10323                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10324            }
10325
10326            N = pkg.services.size();
10327            r = null;
10328            for (i=0; i<N; i++) {
10329                PackageParser.Service s = pkg.services.get(i);
10330                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10331                        s.info.processName);
10332                mServices.addService(s);
10333                if (chatty) {
10334                    if (r == null) {
10335                        r = new StringBuilder(256);
10336                    } else {
10337                        r.append(' ');
10338                    }
10339                    r.append(s.info.name);
10340                }
10341            }
10342            if (r != null) {
10343                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10344            }
10345
10346            N = pkg.receivers.size();
10347            r = null;
10348            for (i=0; i<N; i++) {
10349                PackageParser.Activity a = pkg.receivers.get(i);
10350                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10351                        a.info.processName);
10352                mReceivers.addActivity(a, "receiver");
10353                if (chatty) {
10354                    if (r == null) {
10355                        r = new StringBuilder(256);
10356                    } else {
10357                        r.append(' ');
10358                    }
10359                    r.append(a.info.name);
10360                }
10361            }
10362            if (r != null) {
10363                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10364            }
10365
10366            N = pkg.activities.size();
10367            r = null;
10368            for (i=0; i<N; i++) {
10369                PackageParser.Activity a = pkg.activities.get(i);
10370                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10371                        a.info.processName);
10372                mActivities.addActivity(a, "activity");
10373                if (chatty) {
10374                    if (r == null) {
10375                        r = new StringBuilder(256);
10376                    } else {
10377                        r.append(' ');
10378                    }
10379                    r.append(a.info.name);
10380                }
10381            }
10382            if (r != null) {
10383                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10384            }
10385
10386            N = pkg.permissionGroups.size();
10387            r = null;
10388            for (i=0; i<N; i++) {
10389                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10390                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10391                final String curPackageName = cur == null ? null : cur.info.packageName;
10392                // Dont allow ephemeral apps to define new permission groups.
10393                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10394                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10395                            + pg.info.packageName
10396                            + " ignored: instant apps cannot define new permission groups.");
10397                    continue;
10398                }
10399                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10400                if (cur == null || isPackageUpdate) {
10401                    mPermissionGroups.put(pg.info.name, pg);
10402                    if (chatty) {
10403                        if (r == null) {
10404                            r = new StringBuilder(256);
10405                        } else {
10406                            r.append(' ');
10407                        }
10408                        if (isPackageUpdate) {
10409                            r.append("UPD:");
10410                        }
10411                        r.append(pg.info.name);
10412                    }
10413                } else {
10414                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10415                            + pg.info.packageName + " ignored: original from "
10416                            + cur.info.packageName);
10417                    if (chatty) {
10418                        if (r == null) {
10419                            r = new StringBuilder(256);
10420                        } else {
10421                            r.append(' ');
10422                        }
10423                        r.append("DUP:");
10424                        r.append(pg.info.name);
10425                    }
10426                }
10427            }
10428            if (r != null) {
10429                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10430            }
10431
10432            N = pkg.permissions.size();
10433            r = null;
10434            for (i=0; i<N; i++) {
10435                PackageParser.Permission p = pkg.permissions.get(i);
10436
10437                // Dont allow ephemeral apps to define new permissions.
10438                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10439                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10440                            + p.info.packageName
10441                            + " ignored: instant apps cannot define new permissions.");
10442                    continue;
10443                }
10444
10445                // Assume by default that we did not install this permission into the system.
10446                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10447
10448                // Now that permission groups have a special meaning, we ignore permission
10449                // groups for legacy apps to prevent unexpected behavior. In particular,
10450                // permissions for one app being granted to someone just becase they happen
10451                // to be in a group defined by another app (before this had no implications).
10452                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10453                    p.group = mPermissionGroups.get(p.info.group);
10454                    // Warn for a permission in an unknown group.
10455                    if (p.info.group != null && p.group == null) {
10456                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10457                                + p.info.packageName + " in an unknown group " + p.info.group);
10458                    }
10459                }
10460
10461                ArrayMap<String, BasePermission> permissionMap =
10462                        p.tree ? mSettings.mPermissionTrees
10463                                : mSettings.mPermissions;
10464                BasePermission bp = permissionMap.get(p.info.name);
10465
10466                // Allow system apps to redefine non-system permissions
10467                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10468                    final boolean currentOwnerIsSystem = (bp.perm != null
10469                            && isSystemApp(bp.perm.owner));
10470                    if (isSystemApp(p.owner)) {
10471                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10472                            // It's a built-in permission and no owner, take ownership now
10473                            bp.packageSetting = pkgSetting;
10474                            bp.perm = p;
10475                            bp.uid = pkg.applicationInfo.uid;
10476                            bp.sourcePackage = p.info.packageName;
10477                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10478                        } else if (!currentOwnerIsSystem) {
10479                            String msg = "New decl " + p.owner + " of permission  "
10480                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10481                            reportSettingsProblem(Log.WARN, msg);
10482                            bp = null;
10483                        }
10484                    }
10485                }
10486
10487                if (bp == null) {
10488                    bp = new BasePermission(p.info.name, p.info.packageName,
10489                            BasePermission.TYPE_NORMAL);
10490                    permissionMap.put(p.info.name, bp);
10491                }
10492
10493                if (bp.perm == null) {
10494                    if (bp.sourcePackage == null
10495                            || bp.sourcePackage.equals(p.info.packageName)) {
10496                        BasePermission tree = findPermissionTreeLP(p.info.name);
10497                        if (tree == null
10498                                || tree.sourcePackage.equals(p.info.packageName)) {
10499                            bp.packageSetting = pkgSetting;
10500                            bp.perm = p;
10501                            bp.uid = pkg.applicationInfo.uid;
10502                            bp.sourcePackage = p.info.packageName;
10503                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10504                            if (chatty) {
10505                                if (r == null) {
10506                                    r = new StringBuilder(256);
10507                                } else {
10508                                    r.append(' ');
10509                                }
10510                                r.append(p.info.name);
10511                            }
10512                        } else {
10513                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10514                                    + p.info.packageName + " ignored: base tree "
10515                                    + tree.name + " is from package "
10516                                    + tree.sourcePackage);
10517                        }
10518                    } else {
10519                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10520                                + p.info.packageName + " ignored: original from "
10521                                + bp.sourcePackage);
10522                    }
10523                } else if (chatty) {
10524                    if (r == null) {
10525                        r = new StringBuilder(256);
10526                    } else {
10527                        r.append(' ');
10528                    }
10529                    r.append("DUP:");
10530                    r.append(p.info.name);
10531                }
10532                if (bp.perm == p) {
10533                    bp.protectionLevel = p.info.protectionLevel;
10534                }
10535            }
10536
10537            if (r != null) {
10538                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10539            }
10540
10541            N = pkg.instrumentation.size();
10542            r = null;
10543            for (i=0; i<N; i++) {
10544                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10545                a.info.packageName = pkg.applicationInfo.packageName;
10546                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10547                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10548                a.info.splitNames = pkg.splitNames;
10549                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10550                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10551                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10552                a.info.dataDir = pkg.applicationInfo.dataDir;
10553                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10554                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10555                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10556                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10557                mInstrumentation.put(a.getComponentName(), a);
10558                if (chatty) {
10559                    if (r == null) {
10560                        r = new StringBuilder(256);
10561                    } else {
10562                        r.append(' ');
10563                    }
10564                    r.append(a.info.name);
10565                }
10566            }
10567            if (r != null) {
10568                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10569            }
10570
10571            if (pkg.protectedBroadcasts != null) {
10572                N = pkg.protectedBroadcasts.size();
10573                for (i=0; i<N; i++) {
10574                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10575                }
10576            }
10577        }
10578
10579        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10580    }
10581
10582    /**
10583     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10584     * is derived purely on the basis of the contents of {@code scanFile} and
10585     * {@code cpuAbiOverride}.
10586     *
10587     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10588     */
10589    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10590                                 String cpuAbiOverride, boolean extractLibs,
10591                                 File appLib32InstallDir)
10592            throws PackageManagerException {
10593        // Give ourselves some initial paths; we'll come back for another
10594        // pass once we've determined ABI below.
10595        setNativeLibraryPaths(pkg, appLib32InstallDir);
10596
10597        // We would never need to extract libs for forward-locked and external packages,
10598        // since the container service will do it for us. We shouldn't attempt to
10599        // extract libs from system app when it was not updated.
10600        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10601                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10602            extractLibs = false;
10603        }
10604
10605        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10606        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10607
10608        NativeLibraryHelper.Handle handle = null;
10609        try {
10610            handle = NativeLibraryHelper.Handle.create(pkg);
10611            // TODO(multiArch): This can be null for apps that didn't go through the
10612            // usual installation process. We can calculate it again, like we
10613            // do during install time.
10614            //
10615            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10616            // unnecessary.
10617            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10618
10619            // Null out the abis so that they can be recalculated.
10620            pkg.applicationInfo.primaryCpuAbi = null;
10621            pkg.applicationInfo.secondaryCpuAbi = null;
10622            if (isMultiArch(pkg.applicationInfo)) {
10623                // Warn if we've set an abiOverride for multi-lib packages..
10624                // By definition, we need to copy both 32 and 64 bit libraries for
10625                // such packages.
10626                if (pkg.cpuAbiOverride != null
10627                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10628                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10629                }
10630
10631                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10632                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10633                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10634                    if (extractLibs) {
10635                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10636                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10637                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10638                                useIsaSpecificSubdirs);
10639                    } else {
10640                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10641                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10642                    }
10643                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10644                }
10645
10646                maybeThrowExceptionForMultiArchCopy(
10647                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10648
10649                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10650                    if (extractLibs) {
10651                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10652                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10653                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10654                                useIsaSpecificSubdirs);
10655                    } else {
10656                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10657                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10658                    }
10659                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10660                }
10661
10662                maybeThrowExceptionForMultiArchCopy(
10663                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10664
10665                if (abi64 >= 0) {
10666                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10667                }
10668
10669                if (abi32 >= 0) {
10670                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10671                    if (abi64 >= 0) {
10672                        if (pkg.use32bitAbi) {
10673                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10674                            pkg.applicationInfo.primaryCpuAbi = abi;
10675                        } else {
10676                            pkg.applicationInfo.secondaryCpuAbi = abi;
10677                        }
10678                    } else {
10679                        pkg.applicationInfo.primaryCpuAbi = abi;
10680                    }
10681                }
10682
10683            } else {
10684                String[] abiList = (cpuAbiOverride != null) ?
10685                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10686
10687                // Enable gross and lame hacks for apps that are built with old
10688                // SDK tools. We must scan their APKs for renderscript bitcode and
10689                // not launch them if it's present. Don't bother checking on devices
10690                // that don't have 64 bit support.
10691                boolean needsRenderScriptOverride = false;
10692                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10693                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10694                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10695                    needsRenderScriptOverride = true;
10696                }
10697
10698                final int copyRet;
10699                if (extractLibs) {
10700                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10701                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10702                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10703                } else {
10704                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10705                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10706                }
10707                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10708
10709                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10710                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10711                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10712                }
10713
10714                if (copyRet >= 0) {
10715                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10716                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10717                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10718                } else if (needsRenderScriptOverride) {
10719                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10720                }
10721            }
10722        } catch (IOException ioe) {
10723            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10724        } finally {
10725            IoUtils.closeQuietly(handle);
10726        }
10727
10728        // Now that we've calculated the ABIs and determined if it's an internal app,
10729        // we will go ahead and populate the nativeLibraryPath.
10730        setNativeLibraryPaths(pkg, appLib32InstallDir);
10731    }
10732
10733    /**
10734     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10735     * i.e, so that all packages can be run inside a single process if required.
10736     *
10737     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10738     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10739     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10740     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10741     * updating a package that belongs to a shared user.
10742     *
10743     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10744     * adds unnecessary complexity.
10745     */
10746    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10747            PackageParser.Package scannedPackage) {
10748        String requiredInstructionSet = null;
10749        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10750            requiredInstructionSet = VMRuntime.getInstructionSet(
10751                     scannedPackage.applicationInfo.primaryCpuAbi);
10752        }
10753
10754        PackageSetting requirer = null;
10755        for (PackageSetting ps : packagesForUser) {
10756            // If packagesForUser contains scannedPackage, we skip it. This will happen
10757            // when scannedPackage is an update of an existing package. Without this check,
10758            // we will never be able to change the ABI of any package belonging to a shared
10759            // user, even if it's compatible with other packages.
10760            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10761                if (ps.primaryCpuAbiString == null) {
10762                    continue;
10763                }
10764
10765                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10766                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10767                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10768                    // this but there's not much we can do.
10769                    String errorMessage = "Instruction set mismatch, "
10770                            + ((requirer == null) ? "[caller]" : requirer)
10771                            + " requires " + requiredInstructionSet + " whereas " + ps
10772                            + " requires " + instructionSet;
10773                    Slog.w(TAG, errorMessage);
10774                }
10775
10776                if (requiredInstructionSet == null) {
10777                    requiredInstructionSet = instructionSet;
10778                    requirer = ps;
10779                }
10780            }
10781        }
10782
10783        if (requiredInstructionSet != null) {
10784            String adjustedAbi;
10785            if (requirer != null) {
10786                // requirer != null implies that either scannedPackage was null or that scannedPackage
10787                // did not require an ABI, in which case we have to adjust scannedPackage to match
10788                // the ABI of the set (which is the same as requirer's ABI)
10789                adjustedAbi = requirer.primaryCpuAbiString;
10790                if (scannedPackage != null) {
10791                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10792                }
10793            } else {
10794                // requirer == null implies that we're updating all ABIs in the set to
10795                // match scannedPackage.
10796                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10797            }
10798
10799            for (PackageSetting ps : packagesForUser) {
10800                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10801                    if (ps.primaryCpuAbiString != null) {
10802                        continue;
10803                    }
10804
10805                    ps.primaryCpuAbiString = adjustedAbi;
10806                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10807                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10808                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10809                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10810                                + " (requirer="
10811                                + (requirer != null ? requirer.pkg : "null")
10812                                + ", scannedPackage="
10813                                + (scannedPackage != null ? scannedPackage : "null")
10814                                + ")");
10815                        try {
10816                            mInstaller.rmdex(ps.codePathString,
10817                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10818                        } catch (InstallerException ignored) {
10819                        }
10820                    }
10821                }
10822            }
10823        }
10824    }
10825
10826    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10827        synchronized (mPackages) {
10828            mResolverReplaced = true;
10829            // Set up information for custom user intent resolution activity.
10830            mResolveActivity.applicationInfo = pkg.applicationInfo;
10831            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10832            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10833            mResolveActivity.processName = pkg.applicationInfo.packageName;
10834            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10835            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10836                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10837            mResolveActivity.theme = 0;
10838            mResolveActivity.exported = true;
10839            mResolveActivity.enabled = true;
10840            mResolveInfo.activityInfo = mResolveActivity;
10841            mResolveInfo.priority = 0;
10842            mResolveInfo.preferredOrder = 0;
10843            mResolveInfo.match = 0;
10844            mResolveComponentName = mCustomResolverComponentName;
10845            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10846                    mResolveComponentName);
10847        }
10848    }
10849
10850    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
10851        if (installerActivity == null) {
10852            if (DEBUG_EPHEMERAL) {
10853                Slog.d(TAG, "Clear ephemeral installer activity");
10854            }
10855            mInstantAppInstallerActivity = null;
10856            return;
10857        }
10858
10859        if (DEBUG_EPHEMERAL) {
10860            Slog.d(TAG, "Set ephemeral installer activity: "
10861                    + installerActivity.getComponentName());
10862        }
10863        // Set up information for ephemeral installer activity
10864        mInstantAppInstallerActivity = installerActivity;
10865        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10866                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10867        mInstantAppInstallerActivity.exported = true;
10868        mInstantAppInstallerActivity.enabled = true;
10869        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10870        mInstantAppInstallerInfo.priority = 0;
10871        mInstantAppInstallerInfo.preferredOrder = 1;
10872        mInstantAppInstallerInfo.isDefault = true;
10873        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10874                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10875    }
10876
10877    private static String calculateBundledApkRoot(final String codePathString) {
10878        final File codePath = new File(codePathString);
10879        final File codeRoot;
10880        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10881            codeRoot = Environment.getRootDirectory();
10882        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10883            codeRoot = Environment.getOemDirectory();
10884        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10885            codeRoot = Environment.getVendorDirectory();
10886        } else {
10887            // Unrecognized code path; take its top real segment as the apk root:
10888            // e.g. /something/app/blah.apk => /something
10889            try {
10890                File f = codePath.getCanonicalFile();
10891                File parent = f.getParentFile();    // non-null because codePath is a file
10892                File tmp;
10893                while ((tmp = parent.getParentFile()) != null) {
10894                    f = parent;
10895                    parent = tmp;
10896                }
10897                codeRoot = f;
10898                Slog.w(TAG, "Unrecognized code path "
10899                        + codePath + " - using " + codeRoot);
10900            } catch (IOException e) {
10901                // Can't canonicalize the code path -- shenanigans?
10902                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10903                return Environment.getRootDirectory().getPath();
10904            }
10905        }
10906        return codeRoot.getPath();
10907    }
10908
10909    /**
10910     * Derive and set the location of native libraries for the given package,
10911     * which varies depending on where and how the package was installed.
10912     */
10913    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10914        final ApplicationInfo info = pkg.applicationInfo;
10915        final String codePath = pkg.codePath;
10916        final File codeFile = new File(codePath);
10917        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10918        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10919
10920        info.nativeLibraryRootDir = null;
10921        info.nativeLibraryRootRequiresIsa = false;
10922        info.nativeLibraryDir = null;
10923        info.secondaryNativeLibraryDir = null;
10924
10925        if (isApkFile(codeFile)) {
10926            // Monolithic install
10927            if (bundledApp) {
10928                // If "/system/lib64/apkname" exists, assume that is the per-package
10929                // native library directory to use; otherwise use "/system/lib/apkname".
10930                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10931                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10932                        getPrimaryInstructionSet(info));
10933
10934                // This is a bundled system app so choose the path based on the ABI.
10935                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10936                // is just the default path.
10937                final String apkName = deriveCodePathName(codePath);
10938                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10939                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10940                        apkName).getAbsolutePath();
10941
10942                if (info.secondaryCpuAbi != null) {
10943                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10944                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10945                            secondaryLibDir, apkName).getAbsolutePath();
10946                }
10947            } else if (asecApp) {
10948                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10949                        .getAbsolutePath();
10950            } else {
10951                final String apkName = deriveCodePathName(codePath);
10952                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10953                        .getAbsolutePath();
10954            }
10955
10956            info.nativeLibraryRootRequiresIsa = false;
10957            info.nativeLibraryDir = info.nativeLibraryRootDir;
10958        } else {
10959            // Cluster install
10960            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10961            info.nativeLibraryRootRequiresIsa = true;
10962
10963            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10964                    getPrimaryInstructionSet(info)).getAbsolutePath();
10965
10966            if (info.secondaryCpuAbi != null) {
10967                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10968                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10969            }
10970        }
10971    }
10972
10973    /**
10974     * Calculate the abis and roots for a bundled app. These can uniquely
10975     * be determined from the contents of the system partition, i.e whether
10976     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10977     * of this information, and instead assume that the system was built
10978     * sensibly.
10979     */
10980    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10981                                           PackageSetting pkgSetting) {
10982        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10983
10984        // If "/system/lib64/apkname" exists, assume that is the per-package
10985        // native library directory to use; otherwise use "/system/lib/apkname".
10986        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10987        setBundledAppAbi(pkg, apkRoot, apkName);
10988        // pkgSetting might be null during rescan following uninstall of updates
10989        // to a bundled app, so accommodate that possibility.  The settings in
10990        // that case will be established later from the parsed package.
10991        //
10992        // If the settings aren't null, sync them up with what we've just derived.
10993        // note that apkRoot isn't stored in the package settings.
10994        if (pkgSetting != null) {
10995            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10996            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10997        }
10998    }
10999
11000    /**
11001     * Deduces the ABI of a bundled app and sets the relevant fields on the
11002     * parsed pkg object.
11003     *
11004     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11005     *        under which system libraries are installed.
11006     * @param apkName the name of the installed package.
11007     */
11008    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11009        final File codeFile = new File(pkg.codePath);
11010
11011        final boolean has64BitLibs;
11012        final boolean has32BitLibs;
11013        if (isApkFile(codeFile)) {
11014            // Monolithic install
11015            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11016            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11017        } else {
11018            // Cluster install
11019            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11020            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11021                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11022                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11023                has64BitLibs = (new File(rootDir, isa)).exists();
11024            } else {
11025                has64BitLibs = false;
11026            }
11027            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11028                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11029                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11030                has32BitLibs = (new File(rootDir, isa)).exists();
11031            } else {
11032                has32BitLibs = false;
11033            }
11034        }
11035
11036        if (has64BitLibs && !has32BitLibs) {
11037            // The package has 64 bit libs, but not 32 bit libs. Its primary
11038            // ABI should be 64 bit. We can safely assume here that the bundled
11039            // native libraries correspond to the most preferred ABI in the list.
11040
11041            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11042            pkg.applicationInfo.secondaryCpuAbi = null;
11043        } else if (has32BitLibs && !has64BitLibs) {
11044            // The package has 32 bit libs but not 64 bit libs. Its primary
11045            // ABI should be 32 bit.
11046
11047            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11048            pkg.applicationInfo.secondaryCpuAbi = null;
11049        } else if (has32BitLibs && has64BitLibs) {
11050            // The application has both 64 and 32 bit bundled libraries. We check
11051            // here that the app declares multiArch support, and warn if it doesn't.
11052            //
11053            // We will be lenient here and record both ABIs. The primary will be the
11054            // ABI that's higher on the list, i.e, a device that's configured to prefer
11055            // 64 bit apps will see a 64 bit primary ABI,
11056
11057            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11058                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11059            }
11060
11061            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11062                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11063                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11064            } else {
11065                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11066                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11067            }
11068        } else {
11069            pkg.applicationInfo.primaryCpuAbi = null;
11070            pkg.applicationInfo.secondaryCpuAbi = null;
11071        }
11072    }
11073
11074    private void killApplication(String pkgName, int appId, String reason) {
11075        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11076    }
11077
11078    private void killApplication(String pkgName, int appId, int userId, String reason) {
11079        // Request the ActivityManager to kill the process(only for existing packages)
11080        // so that we do not end up in a confused state while the user is still using the older
11081        // version of the application while the new one gets installed.
11082        final long token = Binder.clearCallingIdentity();
11083        try {
11084            IActivityManager am = ActivityManager.getService();
11085            if (am != null) {
11086                try {
11087                    am.killApplication(pkgName, appId, userId, reason);
11088                } catch (RemoteException e) {
11089                }
11090            }
11091        } finally {
11092            Binder.restoreCallingIdentity(token);
11093        }
11094    }
11095
11096    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11097        // Remove the parent package setting
11098        PackageSetting ps = (PackageSetting) pkg.mExtras;
11099        if (ps != null) {
11100            removePackageLI(ps, chatty);
11101        }
11102        // Remove the child package setting
11103        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11104        for (int i = 0; i < childCount; i++) {
11105            PackageParser.Package childPkg = pkg.childPackages.get(i);
11106            ps = (PackageSetting) childPkg.mExtras;
11107            if (ps != null) {
11108                removePackageLI(ps, chatty);
11109            }
11110        }
11111    }
11112
11113    void removePackageLI(PackageSetting ps, boolean chatty) {
11114        if (DEBUG_INSTALL) {
11115            if (chatty)
11116                Log.d(TAG, "Removing package " + ps.name);
11117        }
11118
11119        // writer
11120        synchronized (mPackages) {
11121            mPackages.remove(ps.name);
11122            final PackageParser.Package pkg = ps.pkg;
11123            if (pkg != null) {
11124                cleanPackageDataStructuresLILPw(pkg, chatty);
11125            }
11126        }
11127    }
11128
11129    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11130        if (DEBUG_INSTALL) {
11131            if (chatty)
11132                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11133        }
11134
11135        // writer
11136        synchronized (mPackages) {
11137            // Remove the parent package
11138            mPackages.remove(pkg.applicationInfo.packageName);
11139            cleanPackageDataStructuresLILPw(pkg, chatty);
11140
11141            // Remove the child packages
11142            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11143            for (int i = 0; i < childCount; i++) {
11144                PackageParser.Package childPkg = pkg.childPackages.get(i);
11145                mPackages.remove(childPkg.applicationInfo.packageName);
11146                cleanPackageDataStructuresLILPw(childPkg, chatty);
11147            }
11148        }
11149    }
11150
11151    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11152        int N = pkg.providers.size();
11153        StringBuilder r = null;
11154        int i;
11155        for (i=0; i<N; i++) {
11156            PackageParser.Provider p = pkg.providers.get(i);
11157            mProviders.removeProvider(p);
11158            if (p.info.authority == null) {
11159
11160                /* There was another ContentProvider with this authority when
11161                 * this app was installed so this authority is null,
11162                 * Ignore it as we don't have to unregister the provider.
11163                 */
11164                continue;
11165            }
11166            String names[] = p.info.authority.split(";");
11167            for (int j = 0; j < names.length; j++) {
11168                if (mProvidersByAuthority.get(names[j]) == p) {
11169                    mProvidersByAuthority.remove(names[j]);
11170                    if (DEBUG_REMOVE) {
11171                        if (chatty)
11172                            Log.d(TAG, "Unregistered content provider: " + names[j]
11173                                    + ", className = " + p.info.name + ", isSyncable = "
11174                                    + p.info.isSyncable);
11175                    }
11176                }
11177            }
11178            if (DEBUG_REMOVE && chatty) {
11179                if (r == null) {
11180                    r = new StringBuilder(256);
11181                } else {
11182                    r.append(' ');
11183                }
11184                r.append(p.info.name);
11185            }
11186        }
11187        if (r != null) {
11188            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11189        }
11190
11191        N = pkg.services.size();
11192        r = null;
11193        for (i=0; i<N; i++) {
11194            PackageParser.Service s = pkg.services.get(i);
11195            mServices.removeService(s);
11196            if (chatty) {
11197                if (r == null) {
11198                    r = new StringBuilder(256);
11199                } else {
11200                    r.append(' ');
11201                }
11202                r.append(s.info.name);
11203            }
11204        }
11205        if (r != null) {
11206            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11207        }
11208
11209        N = pkg.receivers.size();
11210        r = null;
11211        for (i=0; i<N; i++) {
11212            PackageParser.Activity a = pkg.receivers.get(i);
11213            mReceivers.removeActivity(a, "receiver");
11214            if (DEBUG_REMOVE && chatty) {
11215                if (r == null) {
11216                    r = new StringBuilder(256);
11217                } else {
11218                    r.append(' ');
11219                }
11220                r.append(a.info.name);
11221            }
11222        }
11223        if (r != null) {
11224            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11225        }
11226
11227        N = pkg.activities.size();
11228        r = null;
11229        for (i=0; i<N; i++) {
11230            PackageParser.Activity a = pkg.activities.get(i);
11231            mActivities.removeActivity(a, "activity");
11232            if (DEBUG_REMOVE && chatty) {
11233                if (r == null) {
11234                    r = new StringBuilder(256);
11235                } else {
11236                    r.append(' ');
11237                }
11238                r.append(a.info.name);
11239            }
11240        }
11241        if (r != null) {
11242            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11243        }
11244
11245        N = pkg.permissions.size();
11246        r = null;
11247        for (i=0; i<N; i++) {
11248            PackageParser.Permission p = pkg.permissions.get(i);
11249            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11250            if (bp == null) {
11251                bp = mSettings.mPermissionTrees.get(p.info.name);
11252            }
11253            if (bp != null && bp.perm == p) {
11254                bp.perm = null;
11255                if (DEBUG_REMOVE && chatty) {
11256                    if (r == null) {
11257                        r = new StringBuilder(256);
11258                    } else {
11259                        r.append(' ');
11260                    }
11261                    r.append(p.info.name);
11262                }
11263            }
11264            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11265                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11266                if (appOpPkgs != null) {
11267                    appOpPkgs.remove(pkg.packageName);
11268                }
11269            }
11270        }
11271        if (r != null) {
11272            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11273        }
11274
11275        N = pkg.requestedPermissions.size();
11276        r = null;
11277        for (i=0; i<N; i++) {
11278            String perm = pkg.requestedPermissions.get(i);
11279            BasePermission bp = mSettings.mPermissions.get(perm);
11280            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11281                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11282                if (appOpPkgs != null) {
11283                    appOpPkgs.remove(pkg.packageName);
11284                    if (appOpPkgs.isEmpty()) {
11285                        mAppOpPermissionPackages.remove(perm);
11286                    }
11287                }
11288            }
11289        }
11290        if (r != null) {
11291            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11292        }
11293
11294        N = pkg.instrumentation.size();
11295        r = null;
11296        for (i=0; i<N; i++) {
11297            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11298            mInstrumentation.remove(a.getComponentName());
11299            if (DEBUG_REMOVE && chatty) {
11300                if (r == null) {
11301                    r = new StringBuilder(256);
11302                } else {
11303                    r.append(' ');
11304                }
11305                r.append(a.info.name);
11306            }
11307        }
11308        if (r != null) {
11309            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11310        }
11311
11312        r = null;
11313        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11314            // Only system apps can hold shared libraries.
11315            if (pkg.libraryNames != null) {
11316                for (i = 0; i < pkg.libraryNames.size(); i++) {
11317                    String name = pkg.libraryNames.get(i);
11318                    if (removeSharedLibraryLPw(name, 0)) {
11319                        if (DEBUG_REMOVE && chatty) {
11320                            if (r == null) {
11321                                r = new StringBuilder(256);
11322                            } else {
11323                                r.append(' ');
11324                            }
11325                            r.append(name);
11326                        }
11327                    }
11328                }
11329            }
11330        }
11331
11332        r = null;
11333
11334        // Any package can hold static shared libraries.
11335        if (pkg.staticSharedLibName != null) {
11336            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11337                if (DEBUG_REMOVE && chatty) {
11338                    if (r == null) {
11339                        r = new StringBuilder(256);
11340                    } else {
11341                        r.append(' ');
11342                    }
11343                    r.append(pkg.staticSharedLibName);
11344                }
11345            }
11346        }
11347
11348        if (r != null) {
11349            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11350        }
11351    }
11352
11353    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11354        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11355            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11356                return true;
11357            }
11358        }
11359        return false;
11360    }
11361
11362    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11363    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11364    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11365
11366    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11367        // Update the parent permissions
11368        updatePermissionsLPw(pkg.packageName, pkg, flags);
11369        // Update the child permissions
11370        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11371        for (int i = 0; i < childCount; i++) {
11372            PackageParser.Package childPkg = pkg.childPackages.get(i);
11373            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11374        }
11375    }
11376
11377    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11378            int flags) {
11379        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11380        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11381    }
11382
11383    private void updatePermissionsLPw(String changingPkg,
11384            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11385        // Make sure there are no dangling permission trees.
11386        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11387        while (it.hasNext()) {
11388            final BasePermission bp = it.next();
11389            if (bp.packageSetting == null) {
11390                // We may not yet have parsed the package, so just see if
11391                // we still know about its settings.
11392                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11393            }
11394            if (bp.packageSetting == null) {
11395                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11396                        + " from package " + bp.sourcePackage);
11397                it.remove();
11398            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11399                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11400                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11401                            + " from package " + bp.sourcePackage);
11402                    flags |= UPDATE_PERMISSIONS_ALL;
11403                    it.remove();
11404                }
11405            }
11406        }
11407
11408        // Make sure all dynamic permissions have been assigned to a package,
11409        // and make sure there are no dangling permissions.
11410        it = mSettings.mPermissions.values().iterator();
11411        while (it.hasNext()) {
11412            final BasePermission bp = it.next();
11413            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11414                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11415                        + bp.name + " pkg=" + bp.sourcePackage
11416                        + " info=" + bp.pendingInfo);
11417                if (bp.packageSetting == null && bp.pendingInfo != null) {
11418                    final BasePermission tree = findPermissionTreeLP(bp.name);
11419                    if (tree != null && tree.perm != null) {
11420                        bp.packageSetting = tree.packageSetting;
11421                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11422                                new PermissionInfo(bp.pendingInfo));
11423                        bp.perm.info.packageName = tree.perm.info.packageName;
11424                        bp.perm.info.name = bp.name;
11425                        bp.uid = tree.uid;
11426                    }
11427                }
11428            }
11429            if (bp.packageSetting == null) {
11430                // We may not yet have parsed the package, so just see if
11431                // we still know about its settings.
11432                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11433            }
11434            if (bp.packageSetting == null) {
11435                Slog.w(TAG, "Removing dangling permission: " + bp.name
11436                        + " from package " + bp.sourcePackage);
11437                it.remove();
11438            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11439                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11440                    Slog.i(TAG, "Removing old permission: " + bp.name
11441                            + " from package " + bp.sourcePackage);
11442                    flags |= UPDATE_PERMISSIONS_ALL;
11443                    it.remove();
11444                }
11445            }
11446        }
11447
11448        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11449        // Now update the permissions for all packages, in particular
11450        // replace the granted permissions of the system packages.
11451        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11452            for (PackageParser.Package pkg : mPackages.values()) {
11453                if (pkg != pkgInfo) {
11454                    // Only replace for packages on requested volume
11455                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11456                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11457                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11458                    grantPermissionsLPw(pkg, replace, changingPkg);
11459                }
11460            }
11461        }
11462
11463        if (pkgInfo != null) {
11464            // Only replace for packages on requested volume
11465            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11466            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11467                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11468            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11469        }
11470        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11471    }
11472
11473    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11474            String packageOfInterest) {
11475        // IMPORTANT: There are two types of permissions: install and runtime.
11476        // Install time permissions are granted when the app is installed to
11477        // all device users and users added in the future. Runtime permissions
11478        // are granted at runtime explicitly to specific users. Normal and signature
11479        // protected permissions are install time permissions. Dangerous permissions
11480        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11481        // otherwise they are runtime permissions. This function does not manage
11482        // runtime permissions except for the case an app targeting Lollipop MR1
11483        // being upgraded to target a newer SDK, in which case dangerous permissions
11484        // are transformed from install time to runtime ones.
11485
11486        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11487        if (ps == null) {
11488            return;
11489        }
11490
11491        PermissionsState permissionsState = ps.getPermissionsState();
11492        PermissionsState origPermissions = permissionsState;
11493
11494        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11495
11496        boolean runtimePermissionsRevoked = false;
11497        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11498
11499        boolean changedInstallPermission = false;
11500
11501        if (replace) {
11502            ps.installPermissionsFixed = false;
11503            if (!ps.isSharedUser()) {
11504                origPermissions = new PermissionsState(permissionsState);
11505                permissionsState.reset();
11506            } else {
11507                // We need to know only about runtime permission changes since the
11508                // calling code always writes the install permissions state but
11509                // the runtime ones are written only if changed. The only cases of
11510                // changed runtime permissions here are promotion of an install to
11511                // runtime and revocation of a runtime from a shared user.
11512                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11513                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11514                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11515                    runtimePermissionsRevoked = true;
11516                }
11517            }
11518        }
11519
11520        permissionsState.setGlobalGids(mGlobalGids);
11521
11522        final int N = pkg.requestedPermissions.size();
11523        for (int i=0; i<N; i++) {
11524            final String name = pkg.requestedPermissions.get(i);
11525            final BasePermission bp = mSettings.mPermissions.get(name);
11526            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11527                    >= Build.VERSION_CODES.M;
11528
11529            if (DEBUG_INSTALL) {
11530                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11531            }
11532
11533            if (bp == null || bp.packageSetting == null) {
11534                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11535                    Slog.w(TAG, "Unknown permission " + name
11536                            + " in package " + pkg.packageName);
11537                }
11538                continue;
11539            }
11540
11541
11542            // Limit ephemeral apps to ephemeral allowed permissions.
11543            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11544                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11545                        + pkg.packageName);
11546                continue;
11547            }
11548
11549            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
11550                Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
11551                        + pkg.packageName);
11552                continue;
11553            }
11554
11555            final String perm = bp.name;
11556            boolean allowedSig = false;
11557            int grant = GRANT_DENIED;
11558
11559            // Keep track of app op permissions.
11560            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11561                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11562                if (pkgs == null) {
11563                    pkgs = new ArraySet<>();
11564                    mAppOpPermissionPackages.put(bp.name, pkgs);
11565                }
11566                pkgs.add(pkg.packageName);
11567            }
11568
11569            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11570            switch (level) {
11571                case PermissionInfo.PROTECTION_NORMAL: {
11572                    // For all apps normal permissions are install time ones.
11573                    grant = GRANT_INSTALL;
11574                } break;
11575
11576                case PermissionInfo.PROTECTION_DANGEROUS: {
11577                    // If a permission review is required for legacy apps we represent
11578                    // their permissions as always granted runtime ones since we need
11579                    // to keep the review required permission flag per user while an
11580                    // install permission's state is shared across all users.
11581                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11582                        // For legacy apps dangerous permissions are install time ones.
11583                        grant = GRANT_INSTALL;
11584                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11585                        // For legacy apps that became modern, install becomes runtime.
11586                        grant = GRANT_UPGRADE;
11587                    } else if (mPromoteSystemApps
11588                            && isSystemApp(ps)
11589                            && mExistingSystemPackages.contains(ps.name)) {
11590                        // For legacy system apps, install becomes runtime.
11591                        // We cannot check hasInstallPermission() for system apps since those
11592                        // permissions were granted implicitly and not persisted pre-M.
11593                        grant = GRANT_UPGRADE;
11594                    } else {
11595                        // For modern apps keep runtime permissions unchanged.
11596                        grant = GRANT_RUNTIME;
11597                    }
11598                } break;
11599
11600                case PermissionInfo.PROTECTION_SIGNATURE: {
11601                    // For all apps signature permissions are install time ones.
11602                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11603                    if (allowedSig) {
11604                        grant = GRANT_INSTALL;
11605                    }
11606                } break;
11607            }
11608
11609            if (DEBUG_INSTALL) {
11610                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11611            }
11612
11613            if (grant != GRANT_DENIED) {
11614                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11615                    // If this is an existing, non-system package, then
11616                    // we can't add any new permissions to it.
11617                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11618                        // Except...  if this is a permission that was added
11619                        // to the platform (note: need to only do this when
11620                        // updating the platform).
11621                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11622                            grant = GRANT_DENIED;
11623                        }
11624                    }
11625                }
11626
11627                switch (grant) {
11628                    case GRANT_INSTALL: {
11629                        // Revoke this as runtime permission to handle the case of
11630                        // a runtime permission being downgraded to an install one.
11631                        // Also in permission review mode we keep dangerous permissions
11632                        // for legacy apps
11633                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11634                            if (origPermissions.getRuntimePermissionState(
11635                                    bp.name, userId) != null) {
11636                                // Revoke the runtime permission and clear the flags.
11637                                origPermissions.revokeRuntimePermission(bp, userId);
11638                                origPermissions.updatePermissionFlags(bp, userId,
11639                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11640                                // If we revoked a permission permission, we have to write.
11641                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11642                                        changedRuntimePermissionUserIds, userId);
11643                            }
11644                        }
11645                        // Grant an install permission.
11646                        if (permissionsState.grantInstallPermission(bp) !=
11647                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11648                            changedInstallPermission = true;
11649                        }
11650                    } break;
11651
11652                    case GRANT_RUNTIME: {
11653                        // Grant previously granted runtime permissions.
11654                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11655                            PermissionState permissionState = origPermissions
11656                                    .getRuntimePermissionState(bp.name, userId);
11657                            int flags = permissionState != null
11658                                    ? permissionState.getFlags() : 0;
11659                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11660                                // Don't propagate the permission in a permission review mode if
11661                                // the former was revoked, i.e. marked to not propagate on upgrade.
11662                                // Note that in a permission review mode install permissions are
11663                                // represented as constantly granted runtime ones since we need to
11664                                // keep a per user state associated with the permission. Also the
11665                                // revoke on upgrade flag is no longer applicable and is reset.
11666                                final boolean revokeOnUpgrade = (flags & PackageManager
11667                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11668                                if (revokeOnUpgrade) {
11669                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11670                                    // Since we changed the flags, we have to write.
11671                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11672                                            changedRuntimePermissionUserIds, userId);
11673                                }
11674                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11675                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11676                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11677                                        // If we cannot put the permission as it was,
11678                                        // we have to write.
11679                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11680                                                changedRuntimePermissionUserIds, userId);
11681                                    }
11682                                }
11683
11684                                // If the app supports runtime permissions no need for a review.
11685                                if (mPermissionReviewRequired
11686                                        && appSupportsRuntimePermissions
11687                                        && (flags & PackageManager
11688                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11689                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11690                                    // Since we changed the flags, we have to write.
11691                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11692                                            changedRuntimePermissionUserIds, userId);
11693                                }
11694                            } else if (mPermissionReviewRequired
11695                                    && !appSupportsRuntimePermissions) {
11696                                // For legacy apps that need a permission review, every new
11697                                // runtime permission is granted but it is pending a review.
11698                                // We also need to review only platform defined runtime
11699                                // permissions as these are the only ones the platform knows
11700                                // how to disable the API to simulate revocation as legacy
11701                                // apps don't expect to run with revoked permissions.
11702                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11703                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11704                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11705                                        // We changed the flags, hence have to write.
11706                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11707                                                changedRuntimePermissionUserIds, userId);
11708                                    }
11709                                }
11710                                if (permissionsState.grantRuntimePermission(bp, userId)
11711                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11712                                    // We changed the permission, hence have to write.
11713                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11714                                            changedRuntimePermissionUserIds, userId);
11715                                }
11716                            }
11717                            // Propagate the permission flags.
11718                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11719                        }
11720                    } break;
11721
11722                    case GRANT_UPGRADE: {
11723                        // Grant runtime permissions for a previously held install permission.
11724                        PermissionState permissionState = origPermissions
11725                                .getInstallPermissionState(bp.name);
11726                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11727
11728                        if (origPermissions.revokeInstallPermission(bp)
11729                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11730                            // We will be transferring the permission flags, so clear them.
11731                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11732                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11733                            changedInstallPermission = true;
11734                        }
11735
11736                        // If the permission is not to be promoted to runtime we ignore it and
11737                        // also its other flags as they are not applicable to install permissions.
11738                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11739                            for (int userId : currentUserIds) {
11740                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11741                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11742                                    // Transfer the permission flags.
11743                                    permissionsState.updatePermissionFlags(bp, userId,
11744                                            flags, flags);
11745                                    // If we granted the permission, we have to write.
11746                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11747                                            changedRuntimePermissionUserIds, userId);
11748                                }
11749                            }
11750                        }
11751                    } break;
11752
11753                    default: {
11754                        if (packageOfInterest == null
11755                                || packageOfInterest.equals(pkg.packageName)) {
11756                            Slog.w(TAG, "Not granting permission " + perm
11757                                    + " to package " + pkg.packageName
11758                                    + " because it was previously installed without");
11759                        }
11760                    } break;
11761                }
11762            } else {
11763                if (permissionsState.revokeInstallPermission(bp) !=
11764                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11765                    // Also drop the permission flags.
11766                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11767                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11768                    changedInstallPermission = true;
11769                    Slog.i(TAG, "Un-granting permission " + perm
11770                            + " from package " + pkg.packageName
11771                            + " (protectionLevel=" + bp.protectionLevel
11772                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11773                            + ")");
11774                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11775                    // Don't print warning for app op permissions, since it is fine for them
11776                    // not to be granted, there is a UI for the user to decide.
11777                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11778                        Slog.w(TAG, "Not granting permission " + perm
11779                                + " to package " + pkg.packageName
11780                                + " (protectionLevel=" + bp.protectionLevel
11781                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11782                                + ")");
11783                    }
11784                }
11785            }
11786        }
11787
11788        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11789                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11790            // This is the first that we have heard about this package, so the
11791            // permissions we have now selected are fixed until explicitly
11792            // changed.
11793            ps.installPermissionsFixed = true;
11794        }
11795
11796        // Persist the runtime permissions state for users with changes. If permissions
11797        // were revoked because no app in the shared user declares them we have to
11798        // write synchronously to avoid losing runtime permissions state.
11799        for (int userId : changedRuntimePermissionUserIds) {
11800            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11801        }
11802    }
11803
11804    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11805        boolean allowed = false;
11806        final int NP = PackageParser.NEW_PERMISSIONS.length;
11807        for (int ip=0; ip<NP; ip++) {
11808            final PackageParser.NewPermissionInfo npi
11809                    = PackageParser.NEW_PERMISSIONS[ip];
11810            if (npi.name.equals(perm)
11811                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11812                allowed = true;
11813                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11814                        + pkg.packageName);
11815                break;
11816            }
11817        }
11818        return allowed;
11819    }
11820
11821    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11822            BasePermission bp, PermissionsState origPermissions) {
11823        boolean privilegedPermission = (bp.protectionLevel
11824                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11825        boolean privappPermissionsDisable =
11826                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11827        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11828        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11829        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11830                && !platformPackage && platformPermission) {
11831            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11832                    .getPrivAppPermissions(pkg.packageName);
11833            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11834            if (!whitelisted) {
11835                Slog.w(TAG, "Privileged permission " + perm + " for package "
11836                        + pkg.packageName + " - not in privapp-permissions whitelist");
11837                // Only report violations for apps on system image
11838                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11839                    if (mPrivappPermissionsViolations == null) {
11840                        mPrivappPermissionsViolations = new ArraySet<>();
11841                    }
11842                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11843                }
11844                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11845                    return false;
11846                }
11847            }
11848        }
11849        boolean allowed = (compareSignatures(
11850                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11851                        == PackageManager.SIGNATURE_MATCH)
11852                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11853                        == PackageManager.SIGNATURE_MATCH);
11854        if (!allowed && privilegedPermission) {
11855            if (isSystemApp(pkg)) {
11856                // For updated system applications, a system permission
11857                // is granted only if it had been defined by the original application.
11858                if (pkg.isUpdatedSystemApp()) {
11859                    final PackageSetting sysPs = mSettings
11860                            .getDisabledSystemPkgLPr(pkg.packageName);
11861                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11862                        // If the original was granted this permission, we take
11863                        // that grant decision as read and propagate it to the
11864                        // update.
11865                        if (sysPs.isPrivileged()) {
11866                            allowed = true;
11867                        }
11868                    } else {
11869                        // The system apk may have been updated with an older
11870                        // version of the one on the data partition, but which
11871                        // granted a new system permission that it didn't have
11872                        // before.  In this case we do want to allow the app to
11873                        // now get the new permission if the ancestral apk is
11874                        // privileged to get it.
11875                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11876                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11877                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11878                                    allowed = true;
11879                                    break;
11880                                }
11881                            }
11882                        }
11883                        // Also if a privileged parent package on the system image or any of
11884                        // its children requested a privileged permission, the updated child
11885                        // packages can also get the permission.
11886                        if (pkg.parentPackage != null) {
11887                            final PackageSetting disabledSysParentPs = mSettings
11888                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11889                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11890                                    && disabledSysParentPs.isPrivileged()) {
11891                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11892                                    allowed = true;
11893                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11894                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11895                                    for (int i = 0; i < count; i++) {
11896                                        PackageParser.Package disabledSysChildPkg =
11897                                                disabledSysParentPs.pkg.childPackages.get(i);
11898                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11899                                                perm)) {
11900                                            allowed = true;
11901                                            break;
11902                                        }
11903                                    }
11904                                }
11905                            }
11906                        }
11907                    }
11908                } else {
11909                    allowed = isPrivilegedApp(pkg);
11910                }
11911            }
11912        }
11913        if (!allowed) {
11914            if (!allowed && (bp.protectionLevel
11915                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11916                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11917                // If this was a previously normal/dangerous permission that got moved
11918                // to a system permission as part of the runtime permission redesign, then
11919                // we still want to blindly grant it to old apps.
11920                allowed = true;
11921            }
11922            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11923                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11924                // If this permission is to be granted to the system installer and
11925                // this app is an installer, then it gets the permission.
11926                allowed = true;
11927            }
11928            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11929                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11930                // If this permission is to be granted to the system verifier and
11931                // this app is a verifier, then it gets the permission.
11932                allowed = true;
11933            }
11934            if (!allowed && (bp.protectionLevel
11935                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11936                    && isSystemApp(pkg)) {
11937                // Any pre-installed system app is allowed to get this permission.
11938                allowed = true;
11939            }
11940            if (!allowed && (bp.protectionLevel
11941                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11942                // For development permissions, a development permission
11943                // is granted only if it was already granted.
11944                allowed = origPermissions.hasInstallPermission(perm);
11945            }
11946            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11947                    && pkg.packageName.equals(mSetupWizardPackage)) {
11948                // If this permission is to be granted to the system setup wizard and
11949                // this app is a setup wizard, then it gets the permission.
11950                allowed = true;
11951            }
11952        }
11953        return allowed;
11954    }
11955
11956    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11957        final int permCount = pkg.requestedPermissions.size();
11958        for (int j = 0; j < permCount; j++) {
11959            String requestedPermission = pkg.requestedPermissions.get(j);
11960            if (permission.equals(requestedPermission)) {
11961                return true;
11962            }
11963        }
11964        return false;
11965    }
11966
11967    final class ActivityIntentResolver
11968            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11969        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11970                boolean defaultOnly, int userId) {
11971            if (!sUserManager.exists(userId)) return null;
11972            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11973            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11974        }
11975
11976        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11977                int userId) {
11978            if (!sUserManager.exists(userId)) return null;
11979            mFlags = flags;
11980            return super.queryIntent(intent, resolvedType,
11981                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11982                    userId);
11983        }
11984
11985        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11986                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11987            if (!sUserManager.exists(userId)) return null;
11988            if (packageActivities == null) {
11989                return null;
11990            }
11991            mFlags = flags;
11992            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11993            final int N = packageActivities.size();
11994            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11995                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11996
11997            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11998            for (int i = 0; i < N; ++i) {
11999                intentFilters = packageActivities.get(i).intents;
12000                if (intentFilters != null && intentFilters.size() > 0) {
12001                    PackageParser.ActivityIntentInfo[] array =
12002                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12003                    intentFilters.toArray(array);
12004                    listCut.add(array);
12005                }
12006            }
12007            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12008        }
12009
12010        /**
12011         * Finds a privileged activity that matches the specified activity names.
12012         */
12013        private PackageParser.Activity findMatchingActivity(
12014                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12015            for (PackageParser.Activity sysActivity : activityList) {
12016                if (sysActivity.info.name.equals(activityInfo.name)) {
12017                    return sysActivity;
12018                }
12019                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12020                    return sysActivity;
12021                }
12022                if (sysActivity.info.targetActivity != null) {
12023                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12024                        return sysActivity;
12025                    }
12026                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12027                        return sysActivity;
12028                    }
12029                }
12030            }
12031            return null;
12032        }
12033
12034        public class IterGenerator<E> {
12035            public Iterator<E> generate(ActivityIntentInfo info) {
12036                return null;
12037            }
12038        }
12039
12040        public class ActionIterGenerator extends IterGenerator<String> {
12041            @Override
12042            public Iterator<String> generate(ActivityIntentInfo info) {
12043                return info.actionsIterator();
12044            }
12045        }
12046
12047        public class CategoriesIterGenerator extends IterGenerator<String> {
12048            @Override
12049            public Iterator<String> generate(ActivityIntentInfo info) {
12050                return info.categoriesIterator();
12051            }
12052        }
12053
12054        public class SchemesIterGenerator extends IterGenerator<String> {
12055            @Override
12056            public Iterator<String> generate(ActivityIntentInfo info) {
12057                return info.schemesIterator();
12058            }
12059        }
12060
12061        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12062            @Override
12063            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12064                return info.authoritiesIterator();
12065            }
12066        }
12067
12068        /**
12069         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12070         * MODIFIED. Do not pass in a list that should not be changed.
12071         */
12072        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12073                IterGenerator<T> generator, Iterator<T> searchIterator) {
12074            // loop through the set of actions; every one must be found in the intent filter
12075            while (searchIterator.hasNext()) {
12076                // we must have at least one filter in the list to consider a match
12077                if (intentList.size() == 0) {
12078                    break;
12079                }
12080
12081                final T searchAction = searchIterator.next();
12082
12083                // loop through the set of intent filters
12084                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12085                while (intentIter.hasNext()) {
12086                    final ActivityIntentInfo intentInfo = intentIter.next();
12087                    boolean selectionFound = false;
12088
12089                    // loop through the intent filter's selection criteria; at least one
12090                    // of them must match the searched criteria
12091                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12092                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12093                        final T intentSelection = intentSelectionIter.next();
12094                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12095                            selectionFound = true;
12096                            break;
12097                        }
12098                    }
12099
12100                    // the selection criteria wasn't found in this filter's set; this filter
12101                    // is not a potential match
12102                    if (!selectionFound) {
12103                        intentIter.remove();
12104                    }
12105                }
12106            }
12107        }
12108
12109        private boolean isProtectedAction(ActivityIntentInfo filter) {
12110            final Iterator<String> actionsIter = filter.actionsIterator();
12111            while (actionsIter != null && actionsIter.hasNext()) {
12112                final String filterAction = actionsIter.next();
12113                if (PROTECTED_ACTIONS.contains(filterAction)) {
12114                    return true;
12115                }
12116            }
12117            return false;
12118        }
12119
12120        /**
12121         * Adjusts the priority of the given intent filter according to policy.
12122         * <p>
12123         * <ul>
12124         * <li>The priority for non privileged applications is capped to '0'</li>
12125         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12126         * <li>The priority for unbundled updates to privileged applications is capped to the
12127         *      priority defined on the system partition</li>
12128         * </ul>
12129         * <p>
12130         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12131         * allowed to obtain any priority on any action.
12132         */
12133        private void adjustPriority(
12134                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12135            // nothing to do; priority is fine as-is
12136            if (intent.getPriority() <= 0) {
12137                return;
12138            }
12139
12140            final ActivityInfo activityInfo = intent.activity.info;
12141            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12142
12143            final boolean privilegedApp =
12144                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12145            if (!privilegedApp) {
12146                // non-privileged applications can never define a priority >0
12147                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12148                        + " package: " + applicationInfo.packageName
12149                        + " activity: " + intent.activity.className
12150                        + " origPrio: " + intent.getPriority());
12151                intent.setPriority(0);
12152                return;
12153            }
12154
12155            if (systemActivities == null) {
12156                // the system package is not disabled; we're parsing the system partition
12157                if (isProtectedAction(intent)) {
12158                    if (mDeferProtectedFilters) {
12159                        // We can't deal with these just yet. No component should ever obtain a
12160                        // >0 priority for a protected actions, with ONE exception -- the setup
12161                        // wizard. The setup wizard, however, cannot be known until we're able to
12162                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12163                        // until all intent filters have been processed. Chicken, meet egg.
12164                        // Let the filter temporarily have a high priority and rectify the
12165                        // priorities after all system packages have been scanned.
12166                        mProtectedFilters.add(intent);
12167                        if (DEBUG_FILTERS) {
12168                            Slog.i(TAG, "Protected action; save for later;"
12169                                    + " package: " + applicationInfo.packageName
12170                                    + " activity: " + intent.activity.className
12171                                    + " origPrio: " + intent.getPriority());
12172                        }
12173                        return;
12174                    } else {
12175                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12176                            Slog.i(TAG, "No setup wizard;"
12177                                + " All protected intents capped to priority 0");
12178                        }
12179                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12180                            if (DEBUG_FILTERS) {
12181                                Slog.i(TAG, "Found setup wizard;"
12182                                    + " allow priority " + intent.getPriority() + ";"
12183                                    + " package: " + intent.activity.info.packageName
12184                                    + " activity: " + intent.activity.className
12185                                    + " priority: " + intent.getPriority());
12186                            }
12187                            // setup wizard gets whatever it wants
12188                            return;
12189                        }
12190                        Slog.w(TAG, "Protected action; cap priority to 0;"
12191                                + " package: " + intent.activity.info.packageName
12192                                + " activity: " + intent.activity.className
12193                                + " origPrio: " + intent.getPriority());
12194                        intent.setPriority(0);
12195                        return;
12196                    }
12197                }
12198                // privileged apps on the system image get whatever priority they request
12199                return;
12200            }
12201
12202            // privileged app unbundled update ... try to find the same activity
12203            final PackageParser.Activity foundActivity =
12204                    findMatchingActivity(systemActivities, activityInfo);
12205            if (foundActivity == null) {
12206                // this is a new activity; it cannot obtain >0 priority
12207                if (DEBUG_FILTERS) {
12208                    Slog.i(TAG, "New activity; cap priority to 0;"
12209                            + " package: " + applicationInfo.packageName
12210                            + " activity: " + intent.activity.className
12211                            + " origPrio: " + intent.getPriority());
12212                }
12213                intent.setPriority(0);
12214                return;
12215            }
12216
12217            // found activity, now check for filter equivalence
12218
12219            // a shallow copy is enough; we modify the list, not its contents
12220            final List<ActivityIntentInfo> intentListCopy =
12221                    new ArrayList<>(foundActivity.intents);
12222            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12223
12224            // find matching action subsets
12225            final Iterator<String> actionsIterator = intent.actionsIterator();
12226            if (actionsIterator != null) {
12227                getIntentListSubset(
12228                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12229                if (intentListCopy.size() == 0) {
12230                    // no more intents to match; we're not equivalent
12231                    if (DEBUG_FILTERS) {
12232                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12233                                + " package: " + applicationInfo.packageName
12234                                + " activity: " + intent.activity.className
12235                                + " origPrio: " + intent.getPriority());
12236                    }
12237                    intent.setPriority(0);
12238                    return;
12239                }
12240            }
12241
12242            // find matching category subsets
12243            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12244            if (categoriesIterator != null) {
12245                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12246                        categoriesIterator);
12247                if (intentListCopy.size() == 0) {
12248                    // no more intents to match; we're not equivalent
12249                    if (DEBUG_FILTERS) {
12250                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12251                                + " package: " + applicationInfo.packageName
12252                                + " activity: " + intent.activity.className
12253                                + " origPrio: " + intent.getPriority());
12254                    }
12255                    intent.setPriority(0);
12256                    return;
12257                }
12258            }
12259
12260            // find matching schemes subsets
12261            final Iterator<String> schemesIterator = intent.schemesIterator();
12262            if (schemesIterator != null) {
12263                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12264                        schemesIterator);
12265                if (intentListCopy.size() == 0) {
12266                    // no more intents to match; we're not equivalent
12267                    if (DEBUG_FILTERS) {
12268                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12269                                + " package: " + applicationInfo.packageName
12270                                + " activity: " + intent.activity.className
12271                                + " origPrio: " + intent.getPriority());
12272                    }
12273                    intent.setPriority(0);
12274                    return;
12275                }
12276            }
12277
12278            // find matching authorities subsets
12279            final Iterator<IntentFilter.AuthorityEntry>
12280                    authoritiesIterator = intent.authoritiesIterator();
12281            if (authoritiesIterator != null) {
12282                getIntentListSubset(intentListCopy,
12283                        new AuthoritiesIterGenerator(),
12284                        authoritiesIterator);
12285                if (intentListCopy.size() == 0) {
12286                    // no more intents to match; we're not equivalent
12287                    if (DEBUG_FILTERS) {
12288                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12289                                + " package: " + applicationInfo.packageName
12290                                + " activity: " + intent.activity.className
12291                                + " origPrio: " + intent.getPriority());
12292                    }
12293                    intent.setPriority(0);
12294                    return;
12295                }
12296            }
12297
12298            // we found matching filter(s); app gets the max priority of all intents
12299            int cappedPriority = 0;
12300            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12301                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12302            }
12303            if (intent.getPriority() > cappedPriority) {
12304                if (DEBUG_FILTERS) {
12305                    Slog.i(TAG, "Found matching filter(s);"
12306                            + " cap priority to " + cappedPriority + ";"
12307                            + " package: " + applicationInfo.packageName
12308                            + " activity: " + intent.activity.className
12309                            + " origPrio: " + intent.getPriority());
12310                }
12311                intent.setPriority(cappedPriority);
12312                return;
12313            }
12314            // all this for nothing; the requested priority was <= what was on the system
12315        }
12316
12317        public final void addActivity(PackageParser.Activity a, String type) {
12318            mActivities.put(a.getComponentName(), a);
12319            if (DEBUG_SHOW_INFO)
12320                Log.v(
12321                TAG, "  " + type + " " +
12322                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12323            if (DEBUG_SHOW_INFO)
12324                Log.v(TAG, "    Class=" + a.info.name);
12325            final int NI = a.intents.size();
12326            for (int j=0; j<NI; j++) {
12327                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12328                if ("activity".equals(type)) {
12329                    final PackageSetting ps =
12330                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12331                    final List<PackageParser.Activity> systemActivities =
12332                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12333                    adjustPriority(systemActivities, intent);
12334                }
12335                if (DEBUG_SHOW_INFO) {
12336                    Log.v(TAG, "    IntentFilter:");
12337                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12338                }
12339                if (!intent.debugCheck()) {
12340                    Log.w(TAG, "==> For Activity " + a.info.name);
12341                }
12342                addFilter(intent);
12343            }
12344        }
12345
12346        public final void removeActivity(PackageParser.Activity a, String type) {
12347            mActivities.remove(a.getComponentName());
12348            if (DEBUG_SHOW_INFO) {
12349                Log.v(TAG, "  " + type + " "
12350                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12351                                : a.info.name) + ":");
12352                Log.v(TAG, "    Class=" + a.info.name);
12353            }
12354            final int NI = a.intents.size();
12355            for (int j=0; j<NI; j++) {
12356                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12357                if (DEBUG_SHOW_INFO) {
12358                    Log.v(TAG, "    IntentFilter:");
12359                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12360                }
12361                removeFilter(intent);
12362            }
12363        }
12364
12365        @Override
12366        protected boolean allowFilterResult(
12367                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12368            ActivityInfo filterAi = filter.activity.info;
12369            for (int i=dest.size()-1; i>=0; i--) {
12370                ActivityInfo destAi = dest.get(i).activityInfo;
12371                if (destAi.name == filterAi.name
12372                        && destAi.packageName == filterAi.packageName) {
12373                    return false;
12374                }
12375            }
12376            return true;
12377        }
12378
12379        @Override
12380        protected ActivityIntentInfo[] newArray(int size) {
12381            return new ActivityIntentInfo[size];
12382        }
12383
12384        @Override
12385        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12386            if (!sUserManager.exists(userId)) return true;
12387            PackageParser.Package p = filter.activity.owner;
12388            if (p != null) {
12389                PackageSetting ps = (PackageSetting)p.mExtras;
12390                if (ps != null) {
12391                    // System apps are never considered stopped for purposes of
12392                    // filtering, because there may be no way for the user to
12393                    // actually re-launch them.
12394                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12395                            && ps.getStopped(userId);
12396                }
12397            }
12398            return false;
12399        }
12400
12401        @Override
12402        protected boolean isPackageForFilter(String packageName,
12403                PackageParser.ActivityIntentInfo info) {
12404            return packageName.equals(info.activity.owner.packageName);
12405        }
12406
12407        @Override
12408        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12409                int match, int userId) {
12410            if (!sUserManager.exists(userId)) return null;
12411            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12412                return null;
12413            }
12414            final PackageParser.Activity activity = info.activity;
12415            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12416            if (ps == null) {
12417                return null;
12418            }
12419            final PackageUserState userState = ps.readUserState(userId);
12420            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
12421            if (ai == null) {
12422                return null;
12423            }
12424            final boolean matchVisibleToInstantApp =
12425                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12426            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12427            // throw out filters that aren't visible to ephemeral apps
12428            if (matchVisibleToInstantApp
12429                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12430                return null;
12431            }
12432            // throw out ephemeral filters if we're not explicitly requesting them
12433            if (!isInstantApp && userState.instantApp) {
12434                return null;
12435            }
12436            // throw out instant app filters if updates are available; will trigger
12437            // instant app resolution
12438            if (userState.instantApp && ps.isUpdateAvailable()) {
12439                return null;
12440            }
12441            final ResolveInfo res = new ResolveInfo();
12442            res.activityInfo = ai;
12443            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12444                res.filter = info;
12445            }
12446            if (info != null) {
12447                res.handleAllWebDataURI = info.handleAllWebDataURI();
12448            }
12449            res.priority = info.getPriority();
12450            res.preferredOrder = activity.owner.mPreferredOrder;
12451            //System.out.println("Result: " + res.activityInfo.className +
12452            //                   " = " + res.priority);
12453            res.match = match;
12454            res.isDefault = info.hasDefault;
12455            res.labelRes = info.labelRes;
12456            res.nonLocalizedLabel = info.nonLocalizedLabel;
12457            if (userNeedsBadging(userId)) {
12458                res.noResourceId = true;
12459            } else {
12460                res.icon = info.icon;
12461            }
12462            res.iconResourceId = info.icon;
12463            res.system = res.activityInfo.applicationInfo.isSystemApp();
12464            res.instantAppAvailable = userState.instantApp;
12465            return res;
12466        }
12467
12468        @Override
12469        protected void sortResults(List<ResolveInfo> results) {
12470            Collections.sort(results, mResolvePrioritySorter);
12471        }
12472
12473        @Override
12474        protected void dumpFilter(PrintWriter out, String prefix,
12475                PackageParser.ActivityIntentInfo filter) {
12476            out.print(prefix); out.print(
12477                    Integer.toHexString(System.identityHashCode(filter.activity)));
12478                    out.print(' ');
12479                    filter.activity.printComponentShortName(out);
12480                    out.print(" filter ");
12481                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12482        }
12483
12484        @Override
12485        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12486            return filter.activity;
12487        }
12488
12489        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12490            PackageParser.Activity activity = (PackageParser.Activity)label;
12491            out.print(prefix); out.print(
12492                    Integer.toHexString(System.identityHashCode(activity)));
12493                    out.print(' ');
12494                    activity.printComponentShortName(out);
12495            if (count > 1) {
12496                out.print(" ("); out.print(count); out.print(" filters)");
12497            }
12498            out.println();
12499        }
12500
12501        // Keys are String (activity class name), values are Activity.
12502        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12503                = new ArrayMap<ComponentName, PackageParser.Activity>();
12504        private int mFlags;
12505    }
12506
12507    private final class ServiceIntentResolver
12508            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12509        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12510                boolean defaultOnly, int userId) {
12511            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12512            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12513        }
12514
12515        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12516                int userId) {
12517            if (!sUserManager.exists(userId)) return null;
12518            mFlags = flags;
12519            return super.queryIntent(intent, resolvedType,
12520                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12521                    userId);
12522        }
12523
12524        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12525                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12526            if (!sUserManager.exists(userId)) return null;
12527            if (packageServices == null) {
12528                return null;
12529            }
12530            mFlags = flags;
12531            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12532            final int N = packageServices.size();
12533            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12534                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12535
12536            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12537            for (int i = 0; i < N; ++i) {
12538                intentFilters = packageServices.get(i).intents;
12539                if (intentFilters != null && intentFilters.size() > 0) {
12540                    PackageParser.ServiceIntentInfo[] array =
12541                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12542                    intentFilters.toArray(array);
12543                    listCut.add(array);
12544                }
12545            }
12546            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12547        }
12548
12549        public final void addService(PackageParser.Service s) {
12550            mServices.put(s.getComponentName(), s);
12551            if (DEBUG_SHOW_INFO) {
12552                Log.v(TAG, "  "
12553                        + (s.info.nonLocalizedLabel != null
12554                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12555                Log.v(TAG, "    Class=" + s.info.name);
12556            }
12557            final int NI = s.intents.size();
12558            int j;
12559            for (j=0; j<NI; j++) {
12560                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12561                if (DEBUG_SHOW_INFO) {
12562                    Log.v(TAG, "    IntentFilter:");
12563                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12564                }
12565                if (!intent.debugCheck()) {
12566                    Log.w(TAG, "==> For Service " + s.info.name);
12567                }
12568                addFilter(intent);
12569            }
12570        }
12571
12572        public final void removeService(PackageParser.Service s) {
12573            mServices.remove(s.getComponentName());
12574            if (DEBUG_SHOW_INFO) {
12575                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12576                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12577                Log.v(TAG, "    Class=" + s.info.name);
12578            }
12579            final int NI = s.intents.size();
12580            int j;
12581            for (j=0; j<NI; j++) {
12582                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12583                if (DEBUG_SHOW_INFO) {
12584                    Log.v(TAG, "    IntentFilter:");
12585                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12586                }
12587                removeFilter(intent);
12588            }
12589        }
12590
12591        @Override
12592        protected boolean allowFilterResult(
12593                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12594            ServiceInfo filterSi = filter.service.info;
12595            for (int i=dest.size()-1; i>=0; i--) {
12596                ServiceInfo destAi = dest.get(i).serviceInfo;
12597                if (destAi.name == filterSi.name
12598                        && destAi.packageName == filterSi.packageName) {
12599                    return false;
12600                }
12601            }
12602            return true;
12603        }
12604
12605        @Override
12606        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12607            return new PackageParser.ServiceIntentInfo[size];
12608        }
12609
12610        @Override
12611        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12612            if (!sUserManager.exists(userId)) return true;
12613            PackageParser.Package p = filter.service.owner;
12614            if (p != null) {
12615                PackageSetting ps = (PackageSetting)p.mExtras;
12616                if (ps != null) {
12617                    // System apps are never considered stopped for purposes of
12618                    // filtering, because there may be no way for the user to
12619                    // actually re-launch them.
12620                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12621                            && ps.getStopped(userId);
12622                }
12623            }
12624            return false;
12625        }
12626
12627        @Override
12628        protected boolean isPackageForFilter(String packageName,
12629                PackageParser.ServiceIntentInfo info) {
12630            return packageName.equals(info.service.owner.packageName);
12631        }
12632
12633        @Override
12634        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12635                int match, int userId) {
12636            if (!sUserManager.exists(userId)) return null;
12637            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12638            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12639                return null;
12640            }
12641            final PackageParser.Service service = info.service;
12642            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12643            if (ps == null) {
12644                return null;
12645            }
12646            final PackageUserState userState = ps.readUserState(userId);
12647            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12648                    userState, userId);
12649            if (si == null) {
12650                return null;
12651            }
12652            final boolean matchVisibleToInstantApp =
12653                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12654            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12655            // throw out filters that aren't visible to ephemeral apps
12656            if (matchVisibleToInstantApp
12657                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12658                return null;
12659            }
12660            // throw out ephemeral filters if we're not explicitly requesting them
12661            if (!isInstantApp && userState.instantApp) {
12662                return null;
12663            }
12664            // throw out instant app filters if updates are available; will trigger
12665            // instant app resolution
12666            if (userState.instantApp && ps.isUpdateAvailable()) {
12667                return null;
12668            }
12669            final ResolveInfo res = new ResolveInfo();
12670            res.serviceInfo = si;
12671            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12672                res.filter = filter;
12673            }
12674            res.priority = info.getPriority();
12675            res.preferredOrder = service.owner.mPreferredOrder;
12676            res.match = match;
12677            res.isDefault = info.hasDefault;
12678            res.labelRes = info.labelRes;
12679            res.nonLocalizedLabel = info.nonLocalizedLabel;
12680            res.icon = info.icon;
12681            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12682            return res;
12683        }
12684
12685        @Override
12686        protected void sortResults(List<ResolveInfo> results) {
12687            Collections.sort(results, mResolvePrioritySorter);
12688        }
12689
12690        @Override
12691        protected void dumpFilter(PrintWriter out, String prefix,
12692                PackageParser.ServiceIntentInfo filter) {
12693            out.print(prefix); out.print(
12694                    Integer.toHexString(System.identityHashCode(filter.service)));
12695                    out.print(' ');
12696                    filter.service.printComponentShortName(out);
12697                    out.print(" filter ");
12698                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12699        }
12700
12701        @Override
12702        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12703            return filter.service;
12704        }
12705
12706        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12707            PackageParser.Service service = (PackageParser.Service)label;
12708            out.print(prefix); out.print(
12709                    Integer.toHexString(System.identityHashCode(service)));
12710                    out.print(' ');
12711                    service.printComponentShortName(out);
12712            if (count > 1) {
12713                out.print(" ("); out.print(count); out.print(" filters)");
12714            }
12715            out.println();
12716        }
12717
12718//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12719//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12720//            final List<ResolveInfo> retList = Lists.newArrayList();
12721//            while (i.hasNext()) {
12722//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12723//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12724//                    retList.add(resolveInfo);
12725//                }
12726//            }
12727//            return retList;
12728//        }
12729
12730        // Keys are String (activity class name), values are Activity.
12731        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12732                = new ArrayMap<ComponentName, PackageParser.Service>();
12733        private int mFlags;
12734    }
12735
12736    private final class ProviderIntentResolver
12737            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12738        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12739                boolean defaultOnly, int userId) {
12740            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12741            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12742        }
12743
12744        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12745                int userId) {
12746            if (!sUserManager.exists(userId))
12747                return null;
12748            mFlags = flags;
12749            return super.queryIntent(intent, resolvedType,
12750                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12751                    userId);
12752        }
12753
12754        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12755                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12756            if (!sUserManager.exists(userId))
12757                return null;
12758            if (packageProviders == null) {
12759                return null;
12760            }
12761            mFlags = flags;
12762            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12763            final int N = packageProviders.size();
12764            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12765                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12766
12767            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12768            for (int i = 0; i < N; ++i) {
12769                intentFilters = packageProviders.get(i).intents;
12770                if (intentFilters != null && intentFilters.size() > 0) {
12771                    PackageParser.ProviderIntentInfo[] array =
12772                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12773                    intentFilters.toArray(array);
12774                    listCut.add(array);
12775                }
12776            }
12777            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12778        }
12779
12780        public final void addProvider(PackageParser.Provider p) {
12781            if (mProviders.containsKey(p.getComponentName())) {
12782                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12783                return;
12784            }
12785
12786            mProviders.put(p.getComponentName(), p);
12787            if (DEBUG_SHOW_INFO) {
12788                Log.v(TAG, "  "
12789                        + (p.info.nonLocalizedLabel != null
12790                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12791                Log.v(TAG, "    Class=" + p.info.name);
12792            }
12793            final int NI = p.intents.size();
12794            int j;
12795            for (j = 0; j < NI; j++) {
12796                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12797                if (DEBUG_SHOW_INFO) {
12798                    Log.v(TAG, "    IntentFilter:");
12799                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12800                }
12801                if (!intent.debugCheck()) {
12802                    Log.w(TAG, "==> For Provider " + p.info.name);
12803                }
12804                addFilter(intent);
12805            }
12806        }
12807
12808        public final void removeProvider(PackageParser.Provider p) {
12809            mProviders.remove(p.getComponentName());
12810            if (DEBUG_SHOW_INFO) {
12811                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12812                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12813                Log.v(TAG, "    Class=" + p.info.name);
12814            }
12815            final int NI = p.intents.size();
12816            int j;
12817            for (j = 0; j < NI; j++) {
12818                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12819                if (DEBUG_SHOW_INFO) {
12820                    Log.v(TAG, "    IntentFilter:");
12821                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12822                }
12823                removeFilter(intent);
12824            }
12825        }
12826
12827        @Override
12828        protected boolean allowFilterResult(
12829                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12830            ProviderInfo filterPi = filter.provider.info;
12831            for (int i = dest.size() - 1; i >= 0; i--) {
12832                ProviderInfo destPi = dest.get(i).providerInfo;
12833                if (destPi.name == filterPi.name
12834                        && destPi.packageName == filterPi.packageName) {
12835                    return false;
12836                }
12837            }
12838            return true;
12839        }
12840
12841        @Override
12842        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12843            return new PackageParser.ProviderIntentInfo[size];
12844        }
12845
12846        @Override
12847        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12848            if (!sUserManager.exists(userId))
12849                return true;
12850            PackageParser.Package p = filter.provider.owner;
12851            if (p != null) {
12852                PackageSetting ps = (PackageSetting) p.mExtras;
12853                if (ps != null) {
12854                    // System apps are never considered stopped for purposes of
12855                    // filtering, because there may be no way for the user to
12856                    // actually re-launch them.
12857                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12858                            && ps.getStopped(userId);
12859                }
12860            }
12861            return false;
12862        }
12863
12864        @Override
12865        protected boolean isPackageForFilter(String packageName,
12866                PackageParser.ProviderIntentInfo info) {
12867            return packageName.equals(info.provider.owner.packageName);
12868        }
12869
12870        @Override
12871        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12872                int match, int userId) {
12873            if (!sUserManager.exists(userId))
12874                return null;
12875            final PackageParser.ProviderIntentInfo info = filter;
12876            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12877                return null;
12878            }
12879            final PackageParser.Provider provider = info.provider;
12880            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12881            if (ps == null) {
12882                return null;
12883            }
12884            final PackageUserState userState = ps.readUserState(userId);
12885            final boolean matchVisibleToInstantApp =
12886                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12887            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12888            // throw out filters that aren't visible to instant applications
12889            if (matchVisibleToInstantApp
12890                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12891                return null;
12892            }
12893            // throw out instant application filters if we're not explicitly requesting them
12894            if (!isInstantApp && userState.instantApp) {
12895                return null;
12896            }
12897            // throw out instant application filters if updates are available; will trigger
12898            // instant application resolution
12899            if (userState.instantApp && ps.isUpdateAvailable()) {
12900                return null;
12901            }
12902            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12903                    userState, userId);
12904            if (pi == null) {
12905                return null;
12906            }
12907            final ResolveInfo res = new ResolveInfo();
12908            res.providerInfo = pi;
12909            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12910                res.filter = filter;
12911            }
12912            res.priority = info.getPriority();
12913            res.preferredOrder = provider.owner.mPreferredOrder;
12914            res.match = match;
12915            res.isDefault = info.hasDefault;
12916            res.labelRes = info.labelRes;
12917            res.nonLocalizedLabel = info.nonLocalizedLabel;
12918            res.icon = info.icon;
12919            res.system = res.providerInfo.applicationInfo.isSystemApp();
12920            return res;
12921        }
12922
12923        @Override
12924        protected void sortResults(List<ResolveInfo> results) {
12925            Collections.sort(results, mResolvePrioritySorter);
12926        }
12927
12928        @Override
12929        protected void dumpFilter(PrintWriter out, String prefix,
12930                PackageParser.ProviderIntentInfo filter) {
12931            out.print(prefix);
12932            out.print(
12933                    Integer.toHexString(System.identityHashCode(filter.provider)));
12934            out.print(' ');
12935            filter.provider.printComponentShortName(out);
12936            out.print(" filter ");
12937            out.println(Integer.toHexString(System.identityHashCode(filter)));
12938        }
12939
12940        @Override
12941        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12942            return filter.provider;
12943        }
12944
12945        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12946            PackageParser.Provider provider = (PackageParser.Provider)label;
12947            out.print(prefix); out.print(
12948                    Integer.toHexString(System.identityHashCode(provider)));
12949                    out.print(' ');
12950                    provider.printComponentShortName(out);
12951            if (count > 1) {
12952                out.print(" ("); out.print(count); out.print(" filters)");
12953            }
12954            out.println();
12955        }
12956
12957        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12958                = new ArrayMap<ComponentName, PackageParser.Provider>();
12959        private int mFlags;
12960    }
12961
12962    static final class EphemeralIntentResolver
12963            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12964        /**
12965         * The result that has the highest defined order. Ordering applies on a
12966         * per-package basis. Mapping is from package name to Pair of order and
12967         * EphemeralResolveInfo.
12968         * <p>
12969         * NOTE: This is implemented as a field variable for convenience and efficiency.
12970         * By having a field variable, we're able to track filter ordering as soon as
12971         * a non-zero order is defined. Otherwise, multiple loops across the result set
12972         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12973         * this needs to be contained entirely within {@link #filterResults}.
12974         */
12975        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12976
12977        @Override
12978        protected AuxiliaryResolveInfo[] newArray(int size) {
12979            return new AuxiliaryResolveInfo[size];
12980        }
12981
12982        @Override
12983        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12984            return true;
12985        }
12986
12987        @Override
12988        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12989                int userId) {
12990            if (!sUserManager.exists(userId)) {
12991                return null;
12992            }
12993            final String packageName = responseObj.resolveInfo.getPackageName();
12994            final Integer order = responseObj.getOrder();
12995            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12996                    mOrderResult.get(packageName);
12997            // ordering is enabled and this item's order isn't high enough
12998            if (lastOrderResult != null && lastOrderResult.first >= order) {
12999                return null;
13000            }
13001            final InstantAppResolveInfo res = responseObj.resolveInfo;
13002            if (order > 0) {
13003                // non-zero order, enable ordering
13004                mOrderResult.put(packageName, new Pair<>(order, res));
13005            }
13006            return responseObj;
13007        }
13008
13009        @Override
13010        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13011            // only do work if ordering is enabled [most of the time it won't be]
13012            if (mOrderResult.size() == 0) {
13013                return;
13014            }
13015            int resultSize = results.size();
13016            for (int i = 0; i < resultSize; i++) {
13017                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13018                final String packageName = info.getPackageName();
13019                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13020                if (savedInfo == null) {
13021                    // package doesn't having ordering
13022                    continue;
13023                }
13024                if (savedInfo.second == info) {
13025                    // circled back to the highest ordered item; remove from order list
13026                    mOrderResult.remove(savedInfo);
13027                    if (mOrderResult.size() == 0) {
13028                        // no more ordered items
13029                        break;
13030                    }
13031                    continue;
13032                }
13033                // item has a worse order, remove it from the result list
13034                results.remove(i);
13035                resultSize--;
13036                i--;
13037            }
13038        }
13039    }
13040
13041    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13042            new Comparator<ResolveInfo>() {
13043        public int compare(ResolveInfo r1, ResolveInfo r2) {
13044            int v1 = r1.priority;
13045            int v2 = r2.priority;
13046            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13047            if (v1 != v2) {
13048                return (v1 > v2) ? -1 : 1;
13049            }
13050            v1 = r1.preferredOrder;
13051            v2 = r2.preferredOrder;
13052            if (v1 != v2) {
13053                return (v1 > v2) ? -1 : 1;
13054            }
13055            if (r1.isDefault != r2.isDefault) {
13056                return r1.isDefault ? -1 : 1;
13057            }
13058            v1 = r1.match;
13059            v2 = r2.match;
13060            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13061            if (v1 != v2) {
13062                return (v1 > v2) ? -1 : 1;
13063            }
13064            if (r1.system != r2.system) {
13065                return r1.system ? -1 : 1;
13066            }
13067            if (r1.activityInfo != null) {
13068                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13069            }
13070            if (r1.serviceInfo != null) {
13071                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13072            }
13073            if (r1.providerInfo != null) {
13074                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13075            }
13076            return 0;
13077        }
13078    };
13079
13080    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13081            new Comparator<ProviderInfo>() {
13082        public int compare(ProviderInfo p1, ProviderInfo p2) {
13083            final int v1 = p1.initOrder;
13084            final int v2 = p2.initOrder;
13085            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13086        }
13087    };
13088
13089    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13090            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13091            final int[] userIds) {
13092        mHandler.post(new Runnable() {
13093            @Override
13094            public void run() {
13095                try {
13096                    final IActivityManager am = ActivityManager.getService();
13097                    if (am == null) return;
13098                    final int[] resolvedUserIds;
13099                    if (userIds == null) {
13100                        resolvedUserIds = am.getRunningUserIds();
13101                    } else {
13102                        resolvedUserIds = userIds;
13103                    }
13104                    for (int id : resolvedUserIds) {
13105                        final Intent intent = new Intent(action,
13106                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13107                        if (extras != null) {
13108                            intent.putExtras(extras);
13109                        }
13110                        if (targetPkg != null) {
13111                            intent.setPackage(targetPkg);
13112                        }
13113                        // Modify the UID when posting to other users
13114                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13115                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13116                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13117                            intent.putExtra(Intent.EXTRA_UID, uid);
13118                        }
13119                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13120                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13121                        if (DEBUG_BROADCASTS) {
13122                            RuntimeException here = new RuntimeException("here");
13123                            here.fillInStackTrace();
13124                            Slog.d(TAG, "Sending to user " + id + ": "
13125                                    + intent.toShortString(false, true, false, false)
13126                                    + " " + intent.getExtras(), here);
13127                        }
13128                        am.broadcastIntent(null, intent, null, finishedReceiver,
13129                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13130                                null, finishedReceiver != null, false, id);
13131                    }
13132                } catch (RemoteException ex) {
13133                }
13134            }
13135        });
13136    }
13137
13138    /**
13139     * Check if the external storage media is available. This is true if there
13140     * is a mounted external storage medium or if the external storage is
13141     * emulated.
13142     */
13143    private boolean isExternalMediaAvailable() {
13144        return mMediaMounted || Environment.isExternalStorageEmulated();
13145    }
13146
13147    @Override
13148    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13149        // writer
13150        synchronized (mPackages) {
13151            if (!isExternalMediaAvailable()) {
13152                // If the external storage is no longer mounted at this point,
13153                // the caller may not have been able to delete all of this
13154                // packages files and can not delete any more.  Bail.
13155                return null;
13156            }
13157            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13158            if (lastPackage != null) {
13159                pkgs.remove(lastPackage);
13160            }
13161            if (pkgs.size() > 0) {
13162                return pkgs.get(0);
13163            }
13164        }
13165        return null;
13166    }
13167
13168    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13169        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13170                userId, andCode ? 1 : 0, packageName);
13171        if (mSystemReady) {
13172            msg.sendToTarget();
13173        } else {
13174            if (mPostSystemReadyMessages == null) {
13175                mPostSystemReadyMessages = new ArrayList<>();
13176            }
13177            mPostSystemReadyMessages.add(msg);
13178        }
13179    }
13180
13181    void startCleaningPackages() {
13182        // reader
13183        if (!isExternalMediaAvailable()) {
13184            return;
13185        }
13186        synchronized (mPackages) {
13187            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13188                return;
13189            }
13190        }
13191        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13192        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13193        IActivityManager am = ActivityManager.getService();
13194        if (am != null) {
13195            int dcsUid = -1;
13196            synchronized (mPackages) {
13197                if (!mDefaultContainerWhitelisted) {
13198                    mDefaultContainerWhitelisted = true;
13199                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13200                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13201                }
13202            }
13203            try {
13204                if (dcsUid > 0) {
13205                    am.backgroundWhitelistUid(dcsUid);
13206                }
13207                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13208                        UserHandle.USER_SYSTEM);
13209            } catch (RemoteException e) {
13210            }
13211        }
13212    }
13213
13214    @Override
13215    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13216            int installFlags, String installerPackageName, int userId) {
13217        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13218
13219        final int callingUid = Binder.getCallingUid();
13220        enforceCrossUserPermission(callingUid, userId,
13221                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13222
13223        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13224            try {
13225                if (observer != null) {
13226                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13227                }
13228            } catch (RemoteException re) {
13229            }
13230            return;
13231        }
13232
13233        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13234            installFlags |= PackageManager.INSTALL_FROM_ADB;
13235
13236        } else {
13237            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13238            // about installerPackageName.
13239
13240            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13241            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13242        }
13243
13244        UserHandle user;
13245        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13246            user = UserHandle.ALL;
13247        } else {
13248            user = new UserHandle(userId);
13249        }
13250
13251        // Only system components can circumvent runtime permissions when installing.
13252        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13253                && mContext.checkCallingOrSelfPermission(Manifest.permission
13254                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13255            throw new SecurityException("You need the "
13256                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13257                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13258        }
13259
13260        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13261                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13262            throw new IllegalArgumentException(
13263                    "New installs into ASEC containers no longer supported");
13264        }
13265
13266        final File originFile = new File(originPath);
13267        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13268
13269        final Message msg = mHandler.obtainMessage(INIT_COPY);
13270        final VerificationInfo verificationInfo = new VerificationInfo(
13271                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13272        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13273                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13274                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13275                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13276        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13277        msg.obj = params;
13278
13279        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13280                System.identityHashCode(msg.obj));
13281        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13282                System.identityHashCode(msg.obj));
13283
13284        mHandler.sendMessage(msg);
13285    }
13286
13287
13288    /**
13289     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13290     * it is acting on behalf on an enterprise or the user).
13291     *
13292     * Note that the ordering of the conditionals in this method is important. The checks we perform
13293     * are as follows, in this order:
13294     *
13295     * 1) If the install is being performed by a system app, we can trust the app to have set the
13296     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13297     *    what it is.
13298     * 2) If the install is being performed by a device or profile owner app, the install reason
13299     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13300     *    set the install reason correctly. If the app targets an older SDK version where install
13301     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13302     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13303     * 3) In all other cases, the install is being performed by a regular app that is neither part
13304     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13305     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13306     *    set to enterprise policy and if so, change it to unknown instead.
13307     */
13308    private int fixUpInstallReason(String installerPackageName, int installerUid,
13309            int installReason) {
13310        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13311                == PERMISSION_GRANTED) {
13312            // If the install is being performed by a system app, we trust that app to have set the
13313            // install reason correctly.
13314            return installReason;
13315        }
13316
13317        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13318            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13319        if (dpm != null) {
13320            ComponentName owner = null;
13321            try {
13322                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13323                if (owner == null) {
13324                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13325                }
13326            } catch (RemoteException e) {
13327            }
13328            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13329                // If the install is being performed by a device or profile owner, the install
13330                // reason should be enterprise policy.
13331                return PackageManager.INSTALL_REASON_POLICY;
13332            }
13333        }
13334
13335        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13336            // If the install is being performed by a regular app (i.e. neither system app nor
13337            // device or profile owner), we have no reason to believe that the app is acting on
13338            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13339            // change it to unknown instead.
13340            return PackageManager.INSTALL_REASON_UNKNOWN;
13341        }
13342
13343        // If the install is being performed by a regular app and the install reason was set to any
13344        // value but enterprise policy, leave the install reason unchanged.
13345        return installReason;
13346    }
13347
13348    void installStage(String packageName, File stagedDir, String stagedCid,
13349            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13350            String installerPackageName, int installerUid, UserHandle user,
13351            Certificate[][] certificates) {
13352        if (DEBUG_EPHEMERAL) {
13353            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13354                Slog.d(TAG, "Ephemeral install of " + packageName);
13355            }
13356        }
13357        final VerificationInfo verificationInfo = new VerificationInfo(
13358                sessionParams.originatingUri, sessionParams.referrerUri,
13359                sessionParams.originatingUid, installerUid);
13360
13361        final OriginInfo origin;
13362        if (stagedDir != null) {
13363            origin = OriginInfo.fromStagedFile(stagedDir);
13364        } else {
13365            origin = OriginInfo.fromStagedContainer(stagedCid);
13366        }
13367
13368        final Message msg = mHandler.obtainMessage(INIT_COPY);
13369        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13370                sessionParams.installReason);
13371        final InstallParams params = new InstallParams(origin, null, observer,
13372                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13373                verificationInfo, user, sessionParams.abiOverride,
13374                sessionParams.grantedRuntimePermissions, certificates, installReason);
13375        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13376        msg.obj = params;
13377
13378        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13379                System.identityHashCode(msg.obj));
13380        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13381                System.identityHashCode(msg.obj));
13382
13383        mHandler.sendMessage(msg);
13384    }
13385
13386    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13387            int userId) {
13388        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13389        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13390    }
13391
13392    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
13393        if (ArrayUtils.isEmpty(userIds)) {
13394            return;
13395        }
13396        Bundle extras = new Bundle(1);
13397        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13398        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13399
13400        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_ADDED, packageName,
13401                extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, userIds);
13402        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13403                extras, 0, null, null, userIds);
13404        if (isSystem) {
13405            mHandler.post(() -> {
13406                        for (int userId : userIds) {
13407                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13408                        }
13409                    }
13410            );
13411        }
13412    }
13413
13414    /**
13415     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13416     * automatically without needing an explicit launch.
13417     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13418     */
13419    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13420        // If user is not running, the app didn't miss any broadcast
13421        if (!mUserManagerInternal.isUserRunning(userId)) {
13422            return;
13423        }
13424        final IActivityManager am = ActivityManager.getService();
13425        try {
13426            // Deliver LOCKED_BOOT_COMPLETED first
13427            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13428                    .setPackage(packageName);
13429            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13430            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13431                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13432
13433            // Deliver BOOT_COMPLETED only if user is unlocked
13434            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13435                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13436                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13437                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13438            }
13439        } catch (RemoteException e) {
13440            throw e.rethrowFromSystemServer();
13441        }
13442    }
13443
13444    @Override
13445    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13446            int userId) {
13447        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13448        PackageSetting pkgSetting;
13449        final int uid = Binder.getCallingUid();
13450        enforceCrossUserPermission(uid, userId,
13451                true /* requireFullPermission */, true /* checkShell */,
13452                "setApplicationHiddenSetting for user " + userId);
13453
13454        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13455            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13456            return false;
13457        }
13458
13459        long callingId = Binder.clearCallingIdentity();
13460        try {
13461            boolean sendAdded = false;
13462            boolean sendRemoved = false;
13463            // writer
13464            synchronized (mPackages) {
13465                pkgSetting = mSettings.mPackages.get(packageName);
13466                if (pkgSetting == null) {
13467                    return false;
13468                }
13469                // Do not allow "android" is being disabled
13470                if ("android".equals(packageName)) {
13471                    Slog.w(TAG, "Cannot hide package: android");
13472                    return false;
13473                }
13474                // Cannot hide static shared libs as they are considered
13475                // a part of the using app (emulating static linking). Also
13476                // static libs are installed always on internal storage.
13477                PackageParser.Package pkg = mPackages.get(packageName);
13478                if (pkg != null && pkg.staticSharedLibName != null) {
13479                    Slog.w(TAG, "Cannot hide package: " + packageName
13480                            + " providing static shared library: "
13481                            + pkg.staticSharedLibName);
13482                    return false;
13483                }
13484                // Only allow protected packages to hide themselves.
13485                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13486                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13487                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13488                    return false;
13489                }
13490
13491                if (pkgSetting.getHidden(userId) != hidden) {
13492                    pkgSetting.setHidden(hidden, userId);
13493                    mSettings.writePackageRestrictionsLPr(userId);
13494                    if (hidden) {
13495                        sendRemoved = true;
13496                    } else {
13497                        sendAdded = true;
13498                    }
13499                }
13500            }
13501            if (sendAdded) {
13502                sendPackageAddedForUser(packageName, pkgSetting, userId);
13503                return true;
13504            }
13505            if (sendRemoved) {
13506                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13507                        "hiding pkg");
13508                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13509                return true;
13510            }
13511        } finally {
13512            Binder.restoreCallingIdentity(callingId);
13513        }
13514        return false;
13515    }
13516
13517    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13518            int userId) {
13519        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13520        info.removedPackage = packageName;
13521        info.removedUsers = new int[] {userId};
13522        info.broadcastUsers = new int[] {userId};
13523        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13524        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13525    }
13526
13527    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13528        if (pkgList.length > 0) {
13529            Bundle extras = new Bundle(1);
13530            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13531
13532            sendPackageBroadcast(
13533                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13534                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13535                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13536                    new int[] {userId});
13537        }
13538    }
13539
13540    /**
13541     * Returns true if application is not found or there was an error. Otherwise it returns
13542     * the hidden state of the package for the given user.
13543     */
13544    @Override
13545    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13546        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13547        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13548                true /* requireFullPermission */, false /* checkShell */,
13549                "getApplicationHidden for user " + userId);
13550        PackageSetting pkgSetting;
13551        long callingId = Binder.clearCallingIdentity();
13552        try {
13553            // writer
13554            synchronized (mPackages) {
13555                pkgSetting = mSettings.mPackages.get(packageName);
13556                if (pkgSetting == null) {
13557                    return true;
13558                }
13559                return pkgSetting.getHidden(userId);
13560            }
13561        } finally {
13562            Binder.restoreCallingIdentity(callingId);
13563        }
13564    }
13565
13566    /**
13567     * @hide
13568     */
13569    @Override
13570    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13571            int installReason) {
13572        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13573                null);
13574        PackageSetting pkgSetting;
13575        final int uid = Binder.getCallingUid();
13576        enforceCrossUserPermission(uid, userId,
13577                true /* requireFullPermission */, true /* checkShell */,
13578                "installExistingPackage for user " + userId);
13579        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13580            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13581        }
13582
13583        long callingId = Binder.clearCallingIdentity();
13584        try {
13585            boolean installed = false;
13586            final boolean instantApp =
13587                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13588            final boolean fullApp =
13589                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13590
13591            // writer
13592            synchronized (mPackages) {
13593                pkgSetting = mSettings.mPackages.get(packageName);
13594                if (pkgSetting == null) {
13595                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13596                }
13597                if (!pkgSetting.getInstalled(userId)) {
13598                    pkgSetting.setInstalled(true, userId);
13599                    pkgSetting.setHidden(false, userId);
13600                    pkgSetting.setInstallReason(installReason, userId);
13601                    mSettings.writePackageRestrictionsLPr(userId);
13602                    mSettings.writeKernelMappingLPr(pkgSetting);
13603                    installed = true;
13604                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13605                    // upgrade app from instant to full; we don't allow app downgrade
13606                    installed = true;
13607                }
13608                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13609            }
13610
13611            if (installed) {
13612                if (pkgSetting.pkg != null) {
13613                    synchronized (mInstallLock) {
13614                        // We don't need to freeze for a brand new install
13615                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13616                    }
13617                }
13618                sendPackageAddedForUser(packageName, pkgSetting, userId);
13619                synchronized (mPackages) {
13620                    updateSequenceNumberLP(packageName, new int[]{ userId });
13621                }
13622            }
13623        } finally {
13624            Binder.restoreCallingIdentity(callingId);
13625        }
13626
13627        return PackageManager.INSTALL_SUCCEEDED;
13628    }
13629
13630    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13631            boolean instantApp, boolean fullApp) {
13632        // no state specified; do nothing
13633        if (!instantApp && !fullApp) {
13634            return;
13635        }
13636        if (userId != UserHandle.USER_ALL) {
13637            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13638                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13639            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13640                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13641            }
13642        } else {
13643            for (int currentUserId : sUserManager.getUserIds()) {
13644                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13645                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13646                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13647                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13648                }
13649            }
13650        }
13651    }
13652
13653    boolean isUserRestricted(int userId, String restrictionKey) {
13654        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13655        if (restrictions.getBoolean(restrictionKey, false)) {
13656            Log.w(TAG, "User is restricted: " + restrictionKey);
13657            return true;
13658        }
13659        return false;
13660    }
13661
13662    @Override
13663    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13664            int userId) {
13665        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13666        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13667                true /* requireFullPermission */, true /* checkShell */,
13668                "setPackagesSuspended for user " + userId);
13669
13670        if (ArrayUtils.isEmpty(packageNames)) {
13671            return packageNames;
13672        }
13673
13674        // List of package names for whom the suspended state has changed.
13675        List<String> changedPackages = new ArrayList<>(packageNames.length);
13676        // List of package names for whom the suspended state is not set as requested in this
13677        // method.
13678        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13679        long callingId = Binder.clearCallingIdentity();
13680        try {
13681            for (int i = 0; i < packageNames.length; i++) {
13682                String packageName = packageNames[i];
13683                boolean changed = false;
13684                final int appId;
13685                synchronized (mPackages) {
13686                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13687                    if (pkgSetting == null) {
13688                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13689                                + "\". Skipping suspending/un-suspending.");
13690                        unactionedPackages.add(packageName);
13691                        continue;
13692                    }
13693                    appId = pkgSetting.appId;
13694                    if (pkgSetting.getSuspended(userId) != suspended) {
13695                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13696                            unactionedPackages.add(packageName);
13697                            continue;
13698                        }
13699                        pkgSetting.setSuspended(suspended, userId);
13700                        mSettings.writePackageRestrictionsLPr(userId);
13701                        changed = true;
13702                        changedPackages.add(packageName);
13703                    }
13704                }
13705
13706                if (changed && suspended) {
13707                    killApplication(packageName, UserHandle.getUid(userId, appId),
13708                            "suspending package");
13709                }
13710            }
13711        } finally {
13712            Binder.restoreCallingIdentity(callingId);
13713        }
13714
13715        if (!changedPackages.isEmpty()) {
13716            sendPackagesSuspendedForUser(changedPackages.toArray(
13717                    new String[changedPackages.size()]), userId, suspended);
13718        }
13719
13720        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13721    }
13722
13723    @Override
13724    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13725        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13726                true /* requireFullPermission */, false /* checkShell */,
13727                "isPackageSuspendedForUser for user " + userId);
13728        synchronized (mPackages) {
13729            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13730            if (pkgSetting == null) {
13731                throw new IllegalArgumentException("Unknown target package: " + packageName);
13732            }
13733            return pkgSetting.getSuspended(userId);
13734        }
13735    }
13736
13737    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13738        if (isPackageDeviceAdmin(packageName, userId)) {
13739            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13740                    + "\": has an active device admin");
13741            return false;
13742        }
13743
13744        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13745        if (packageName.equals(activeLauncherPackageName)) {
13746            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13747                    + "\": contains the active launcher");
13748            return false;
13749        }
13750
13751        if (packageName.equals(mRequiredInstallerPackage)) {
13752            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13753                    + "\": required for package installation");
13754            return false;
13755        }
13756
13757        if (packageName.equals(mRequiredUninstallerPackage)) {
13758            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13759                    + "\": required for package uninstallation");
13760            return false;
13761        }
13762
13763        if (packageName.equals(mRequiredVerifierPackage)) {
13764            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13765                    + "\": required for package verification");
13766            return false;
13767        }
13768
13769        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13770            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13771                    + "\": is the default dialer");
13772            return false;
13773        }
13774
13775        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13776            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13777                    + "\": protected package");
13778            return false;
13779        }
13780
13781        // Cannot suspend static shared libs as they are considered
13782        // a part of the using app (emulating static linking). Also
13783        // static libs are installed always on internal storage.
13784        PackageParser.Package pkg = mPackages.get(packageName);
13785        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13786            Slog.w(TAG, "Cannot suspend package: " + packageName
13787                    + " providing static shared library: "
13788                    + pkg.staticSharedLibName);
13789            return false;
13790        }
13791
13792        return true;
13793    }
13794
13795    private String getActiveLauncherPackageName(int userId) {
13796        Intent intent = new Intent(Intent.ACTION_MAIN);
13797        intent.addCategory(Intent.CATEGORY_HOME);
13798        ResolveInfo resolveInfo = resolveIntent(
13799                intent,
13800                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13801                PackageManager.MATCH_DEFAULT_ONLY,
13802                userId);
13803
13804        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13805    }
13806
13807    private String getDefaultDialerPackageName(int userId) {
13808        synchronized (mPackages) {
13809            return mSettings.getDefaultDialerPackageNameLPw(userId);
13810        }
13811    }
13812
13813    @Override
13814    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13815        mContext.enforceCallingOrSelfPermission(
13816                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13817                "Only package verification agents can verify applications");
13818
13819        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13820        final PackageVerificationResponse response = new PackageVerificationResponse(
13821                verificationCode, Binder.getCallingUid());
13822        msg.arg1 = id;
13823        msg.obj = response;
13824        mHandler.sendMessage(msg);
13825    }
13826
13827    @Override
13828    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13829            long millisecondsToDelay) {
13830        mContext.enforceCallingOrSelfPermission(
13831                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13832                "Only package verification agents can extend verification timeouts");
13833
13834        final PackageVerificationState state = mPendingVerification.get(id);
13835        final PackageVerificationResponse response = new PackageVerificationResponse(
13836                verificationCodeAtTimeout, Binder.getCallingUid());
13837
13838        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13839            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13840        }
13841        if (millisecondsToDelay < 0) {
13842            millisecondsToDelay = 0;
13843        }
13844        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13845                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13846            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13847        }
13848
13849        if ((state != null) && !state.timeoutExtended()) {
13850            state.extendTimeout();
13851
13852            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13853            msg.arg1 = id;
13854            msg.obj = response;
13855            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13856        }
13857    }
13858
13859    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13860            int verificationCode, UserHandle user) {
13861        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13862        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13863        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13864        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13865        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13866
13867        mContext.sendBroadcastAsUser(intent, user,
13868                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13869    }
13870
13871    private ComponentName matchComponentForVerifier(String packageName,
13872            List<ResolveInfo> receivers) {
13873        ActivityInfo targetReceiver = null;
13874
13875        final int NR = receivers.size();
13876        for (int i = 0; i < NR; i++) {
13877            final ResolveInfo info = receivers.get(i);
13878            if (info.activityInfo == null) {
13879                continue;
13880            }
13881
13882            if (packageName.equals(info.activityInfo.packageName)) {
13883                targetReceiver = info.activityInfo;
13884                break;
13885            }
13886        }
13887
13888        if (targetReceiver == null) {
13889            return null;
13890        }
13891
13892        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13893    }
13894
13895    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13896            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13897        if (pkgInfo.verifiers.length == 0) {
13898            return null;
13899        }
13900
13901        final int N = pkgInfo.verifiers.length;
13902        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13903        for (int i = 0; i < N; i++) {
13904            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13905
13906            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13907                    receivers);
13908            if (comp == null) {
13909                continue;
13910            }
13911
13912            final int verifierUid = getUidForVerifier(verifierInfo);
13913            if (verifierUid == -1) {
13914                continue;
13915            }
13916
13917            if (DEBUG_VERIFY) {
13918                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13919                        + " with the correct signature");
13920            }
13921            sufficientVerifiers.add(comp);
13922            verificationState.addSufficientVerifier(verifierUid);
13923        }
13924
13925        return sufficientVerifiers;
13926    }
13927
13928    private int getUidForVerifier(VerifierInfo verifierInfo) {
13929        synchronized (mPackages) {
13930            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13931            if (pkg == null) {
13932                return -1;
13933            } else if (pkg.mSignatures.length != 1) {
13934                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13935                        + " has more than one signature; ignoring");
13936                return -1;
13937            }
13938
13939            /*
13940             * If the public key of the package's signature does not match
13941             * our expected public key, then this is a different package and
13942             * we should skip.
13943             */
13944
13945            final byte[] expectedPublicKey;
13946            try {
13947                final Signature verifierSig = pkg.mSignatures[0];
13948                final PublicKey publicKey = verifierSig.getPublicKey();
13949                expectedPublicKey = publicKey.getEncoded();
13950            } catch (CertificateException e) {
13951                return -1;
13952            }
13953
13954            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13955
13956            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13957                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13958                        + " does not have the expected public key; ignoring");
13959                return -1;
13960            }
13961
13962            return pkg.applicationInfo.uid;
13963        }
13964    }
13965
13966    @Override
13967    public void finishPackageInstall(int token, boolean didLaunch) {
13968        enforceSystemOrRoot("Only the system is allowed to finish installs");
13969
13970        if (DEBUG_INSTALL) {
13971            Slog.v(TAG, "BM finishing package install for " + token);
13972        }
13973        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13974
13975        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13976        mHandler.sendMessage(msg);
13977    }
13978
13979    /**
13980     * Get the verification agent timeout.
13981     *
13982     * @return verification timeout in milliseconds
13983     */
13984    private long getVerificationTimeout() {
13985        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13986                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13987                DEFAULT_VERIFICATION_TIMEOUT);
13988    }
13989
13990    /**
13991     * Get the default verification agent response code.
13992     *
13993     * @return default verification response code
13994     */
13995    private int getDefaultVerificationResponse() {
13996        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13997                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13998                DEFAULT_VERIFICATION_RESPONSE);
13999    }
14000
14001    /**
14002     * Check whether or not package verification has been enabled.
14003     *
14004     * @return true if verification should be performed
14005     */
14006    private boolean isVerificationEnabled(int userId, int installFlags) {
14007        if (!DEFAULT_VERIFY_ENABLE) {
14008            return false;
14009        }
14010
14011        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14012
14013        // Check if installing from ADB
14014        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14015            // Do not run verification in a test harness environment
14016            if (ActivityManager.isRunningInTestHarness()) {
14017                return false;
14018            }
14019            if (ensureVerifyAppsEnabled) {
14020                return true;
14021            }
14022            // Check if the developer does not want package verification for ADB installs
14023            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14024                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14025                return false;
14026            }
14027        }
14028
14029        if (ensureVerifyAppsEnabled) {
14030            return true;
14031        }
14032
14033        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14034                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14035    }
14036
14037    @Override
14038    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14039            throws RemoteException {
14040        mContext.enforceCallingOrSelfPermission(
14041                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14042                "Only intentfilter verification agents can verify applications");
14043
14044        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14045        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14046                Binder.getCallingUid(), verificationCode, failedDomains);
14047        msg.arg1 = id;
14048        msg.obj = response;
14049        mHandler.sendMessage(msg);
14050    }
14051
14052    @Override
14053    public int getIntentVerificationStatus(String packageName, int userId) {
14054        synchronized (mPackages) {
14055            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14056        }
14057    }
14058
14059    @Override
14060    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14061        mContext.enforceCallingOrSelfPermission(
14062                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14063
14064        boolean result = false;
14065        synchronized (mPackages) {
14066            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14067        }
14068        if (result) {
14069            scheduleWritePackageRestrictionsLocked(userId);
14070        }
14071        return result;
14072    }
14073
14074    @Override
14075    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14076            String packageName) {
14077        synchronized (mPackages) {
14078            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14079        }
14080    }
14081
14082    @Override
14083    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14084        if (TextUtils.isEmpty(packageName)) {
14085            return ParceledListSlice.emptyList();
14086        }
14087        synchronized (mPackages) {
14088            PackageParser.Package pkg = mPackages.get(packageName);
14089            if (pkg == null || pkg.activities == null) {
14090                return ParceledListSlice.emptyList();
14091            }
14092            final int count = pkg.activities.size();
14093            ArrayList<IntentFilter> result = new ArrayList<>();
14094            for (int n=0; n<count; n++) {
14095                PackageParser.Activity activity = pkg.activities.get(n);
14096                if (activity.intents != null && activity.intents.size() > 0) {
14097                    result.addAll(activity.intents);
14098                }
14099            }
14100            return new ParceledListSlice<>(result);
14101        }
14102    }
14103
14104    @Override
14105    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14106        mContext.enforceCallingOrSelfPermission(
14107                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14108
14109        synchronized (mPackages) {
14110            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14111            if (packageName != null) {
14112                result |= updateIntentVerificationStatus(packageName,
14113                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
14114                        userId);
14115                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
14116                        packageName, userId);
14117            }
14118            return result;
14119        }
14120    }
14121
14122    @Override
14123    public String getDefaultBrowserPackageName(int userId) {
14124        synchronized (mPackages) {
14125            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14126        }
14127    }
14128
14129    /**
14130     * Get the "allow unknown sources" setting.
14131     *
14132     * @return the current "allow unknown sources" setting
14133     */
14134    private int getUnknownSourcesSettings() {
14135        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14136                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14137                -1);
14138    }
14139
14140    @Override
14141    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14142        final int uid = Binder.getCallingUid();
14143        // writer
14144        synchronized (mPackages) {
14145            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14146            if (targetPackageSetting == null) {
14147                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14148            }
14149
14150            PackageSetting installerPackageSetting;
14151            if (installerPackageName != null) {
14152                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14153                if (installerPackageSetting == null) {
14154                    throw new IllegalArgumentException("Unknown installer package: "
14155                            + installerPackageName);
14156                }
14157            } else {
14158                installerPackageSetting = null;
14159            }
14160
14161            Signature[] callerSignature;
14162            Object obj = mSettings.getUserIdLPr(uid);
14163            if (obj != null) {
14164                if (obj instanceof SharedUserSetting) {
14165                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14166                } else if (obj instanceof PackageSetting) {
14167                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14168                } else {
14169                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14170                }
14171            } else {
14172                throw new SecurityException("Unknown calling UID: " + uid);
14173            }
14174
14175            // Verify: can't set installerPackageName to a package that is
14176            // not signed with the same cert as the caller.
14177            if (installerPackageSetting != null) {
14178                if (compareSignatures(callerSignature,
14179                        installerPackageSetting.signatures.mSignatures)
14180                        != PackageManager.SIGNATURE_MATCH) {
14181                    throw new SecurityException(
14182                            "Caller does not have same cert as new installer package "
14183                            + installerPackageName);
14184                }
14185            }
14186
14187            // Verify: if target already has an installer package, it must
14188            // be signed with the same cert as the caller.
14189            if (targetPackageSetting.installerPackageName != null) {
14190                PackageSetting setting = mSettings.mPackages.get(
14191                        targetPackageSetting.installerPackageName);
14192                // If the currently set package isn't valid, then it's always
14193                // okay to change it.
14194                if (setting != null) {
14195                    if (compareSignatures(callerSignature,
14196                            setting.signatures.mSignatures)
14197                            != PackageManager.SIGNATURE_MATCH) {
14198                        throw new SecurityException(
14199                                "Caller does not have same cert as old installer package "
14200                                + targetPackageSetting.installerPackageName);
14201                    }
14202                }
14203            }
14204
14205            // Okay!
14206            targetPackageSetting.installerPackageName = installerPackageName;
14207            if (installerPackageName != null) {
14208                mSettings.mInstallerPackages.add(installerPackageName);
14209            }
14210            scheduleWriteSettingsLocked();
14211        }
14212    }
14213
14214    @Override
14215    public void setApplicationCategoryHint(String packageName, int categoryHint,
14216            String callerPackageName) {
14217        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14218                callerPackageName);
14219        synchronized (mPackages) {
14220            PackageSetting ps = mSettings.mPackages.get(packageName);
14221            if (ps == null) {
14222                throw new IllegalArgumentException("Unknown target package " + packageName);
14223            }
14224
14225            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14226                throw new IllegalArgumentException("Calling package " + callerPackageName
14227                        + " is not installer for " + packageName);
14228            }
14229
14230            if (ps.categoryHint != categoryHint) {
14231                ps.categoryHint = categoryHint;
14232                scheduleWriteSettingsLocked();
14233            }
14234        }
14235    }
14236
14237    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14238        // Queue up an async operation since the package installation may take a little while.
14239        mHandler.post(new Runnable() {
14240            public void run() {
14241                mHandler.removeCallbacks(this);
14242                 // Result object to be returned
14243                PackageInstalledInfo res = new PackageInstalledInfo();
14244                res.setReturnCode(currentStatus);
14245                res.uid = -1;
14246                res.pkg = null;
14247                res.removedInfo = null;
14248                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14249                    args.doPreInstall(res.returnCode);
14250                    synchronized (mInstallLock) {
14251                        installPackageTracedLI(args, res);
14252                    }
14253                    args.doPostInstall(res.returnCode, res.uid);
14254                }
14255
14256                // A restore should be performed at this point if (a) the install
14257                // succeeded, (b) the operation is not an update, and (c) the new
14258                // package has not opted out of backup participation.
14259                final boolean update = res.removedInfo != null
14260                        && res.removedInfo.removedPackage != null;
14261                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14262                boolean doRestore = !update
14263                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14264
14265                // Set up the post-install work request bookkeeping.  This will be used
14266                // and cleaned up by the post-install event handling regardless of whether
14267                // there's a restore pass performed.  Token values are >= 1.
14268                int token;
14269                if (mNextInstallToken < 0) mNextInstallToken = 1;
14270                token = mNextInstallToken++;
14271
14272                PostInstallData data = new PostInstallData(args, res);
14273                mRunningInstalls.put(token, data);
14274                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14275
14276                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14277                    // Pass responsibility to the Backup Manager.  It will perform a
14278                    // restore if appropriate, then pass responsibility back to the
14279                    // Package Manager to run the post-install observer callbacks
14280                    // and broadcasts.
14281                    IBackupManager bm = IBackupManager.Stub.asInterface(
14282                            ServiceManager.getService(Context.BACKUP_SERVICE));
14283                    if (bm != null) {
14284                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14285                                + " to BM for possible restore");
14286                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14287                        try {
14288                            // TODO: http://b/22388012
14289                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14290                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14291                            } else {
14292                                doRestore = false;
14293                            }
14294                        } catch (RemoteException e) {
14295                            // can't happen; the backup manager is local
14296                        } catch (Exception e) {
14297                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14298                            doRestore = false;
14299                        }
14300                    } else {
14301                        Slog.e(TAG, "Backup Manager not found!");
14302                        doRestore = false;
14303                    }
14304                }
14305
14306                if (!doRestore) {
14307                    // No restore possible, or the Backup Manager was mysteriously not
14308                    // available -- just fire the post-install work request directly.
14309                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14310
14311                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14312
14313                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14314                    mHandler.sendMessage(msg);
14315                }
14316            }
14317        });
14318    }
14319
14320    /**
14321     * Callback from PackageSettings whenever an app is first transitioned out of the
14322     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14323     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14324     * here whether the app is the target of an ongoing install, and only send the
14325     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14326     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14327     * handling.
14328     */
14329    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14330        // Serialize this with the rest of the install-process message chain.  In the
14331        // restore-at-install case, this Runnable will necessarily run before the
14332        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14333        // are coherent.  In the non-restore case, the app has already completed install
14334        // and been launched through some other means, so it is not in a problematic
14335        // state for observers to see the FIRST_LAUNCH signal.
14336        mHandler.post(new Runnable() {
14337            @Override
14338            public void run() {
14339                for (int i = 0; i < mRunningInstalls.size(); i++) {
14340                    final PostInstallData data = mRunningInstalls.valueAt(i);
14341                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14342                        continue;
14343                    }
14344                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14345                        // right package; but is it for the right user?
14346                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14347                            if (userId == data.res.newUsers[uIndex]) {
14348                                if (DEBUG_BACKUP) {
14349                                    Slog.i(TAG, "Package " + pkgName
14350                                            + " being restored so deferring FIRST_LAUNCH");
14351                                }
14352                                return;
14353                            }
14354                        }
14355                    }
14356                }
14357                // didn't find it, so not being restored
14358                if (DEBUG_BACKUP) {
14359                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14360                }
14361                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14362            }
14363        });
14364    }
14365
14366    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14367        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14368                installerPkg, null, userIds);
14369    }
14370
14371    private abstract class HandlerParams {
14372        private static final int MAX_RETRIES = 4;
14373
14374        /**
14375         * Number of times startCopy() has been attempted and had a non-fatal
14376         * error.
14377         */
14378        private int mRetries = 0;
14379
14380        /** User handle for the user requesting the information or installation. */
14381        private final UserHandle mUser;
14382        String traceMethod;
14383        int traceCookie;
14384
14385        HandlerParams(UserHandle user) {
14386            mUser = user;
14387        }
14388
14389        UserHandle getUser() {
14390            return mUser;
14391        }
14392
14393        HandlerParams setTraceMethod(String traceMethod) {
14394            this.traceMethod = traceMethod;
14395            return this;
14396        }
14397
14398        HandlerParams setTraceCookie(int traceCookie) {
14399            this.traceCookie = traceCookie;
14400            return this;
14401        }
14402
14403        final boolean startCopy() {
14404            boolean res;
14405            try {
14406                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14407
14408                if (++mRetries > MAX_RETRIES) {
14409                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14410                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14411                    handleServiceError();
14412                    return false;
14413                } else {
14414                    handleStartCopy();
14415                    res = true;
14416                }
14417            } catch (RemoteException e) {
14418                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14419                mHandler.sendEmptyMessage(MCS_RECONNECT);
14420                res = false;
14421            }
14422            handleReturnCode();
14423            return res;
14424        }
14425
14426        final void serviceError() {
14427            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14428            handleServiceError();
14429            handleReturnCode();
14430        }
14431
14432        abstract void handleStartCopy() throws RemoteException;
14433        abstract void handleServiceError();
14434        abstract void handleReturnCode();
14435    }
14436
14437    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14438        for (File path : paths) {
14439            try {
14440                mcs.clearDirectory(path.getAbsolutePath());
14441            } catch (RemoteException e) {
14442            }
14443        }
14444    }
14445
14446    static class OriginInfo {
14447        /**
14448         * Location where install is coming from, before it has been
14449         * copied/renamed into place. This could be a single monolithic APK
14450         * file, or a cluster directory. This location may be untrusted.
14451         */
14452        final File file;
14453        final String cid;
14454
14455        /**
14456         * Flag indicating that {@link #file} or {@link #cid} has already been
14457         * staged, meaning downstream users don't need to defensively copy the
14458         * contents.
14459         */
14460        final boolean staged;
14461
14462        /**
14463         * Flag indicating that {@link #file} or {@link #cid} is an already
14464         * installed app that is being moved.
14465         */
14466        final boolean existing;
14467
14468        final String resolvedPath;
14469        final File resolvedFile;
14470
14471        static OriginInfo fromNothing() {
14472            return new OriginInfo(null, null, false, false);
14473        }
14474
14475        static OriginInfo fromUntrustedFile(File file) {
14476            return new OriginInfo(file, null, false, false);
14477        }
14478
14479        static OriginInfo fromExistingFile(File file) {
14480            return new OriginInfo(file, null, false, true);
14481        }
14482
14483        static OriginInfo fromStagedFile(File file) {
14484            return new OriginInfo(file, null, true, false);
14485        }
14486
14487        static OriginInfo fromStagedContainer(String cid) {
14488            return new OriginInfo(null, cid, true, false);
14489        }
14490
14491        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14492            this.file = file;
14493            this.cid = cid;
14494            this.staged = staged;
14495            this.existing = existing;
14496
14497            if (cid != null) {
14498                resolvedPath = PackageHelper.getSdDir(cid);
14499                resolvedFile = new File(resolvedPath);
14500            } else if (file != null) {
14501                resolvedPath = file.getAbsolutePath();
14502                resolvedFile = file;
14503            } else {
14504                resolvedPath = null;
14505                resolvedFile = null;
14506            }
14507        }
14508    }
14509
14510    static class MoveInfo {
14511        final int moveId;
14512        final String fromUuid;
14513        final String toUuid;
14514        final String packageName;
14515        final String dataAppName;
14516        final int appId;
14517        final String seinfo;
14518        final int targetSdkVersion;
14519
14520        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14521                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14522            this.moveId = moveId;
14523            this.fromUuid = fromUuid;
14524            this.toUuid = toUuid;
14525            this.packageName = packageName;
14526            this.dataAppName = dataAppName;
14527            this.appId = appId;
14528            this.seinfo = seinfo;
14529            this.targetSdkVersion = targetSdkVersion;
14530        }
14531    }
14532
14533    static class VerificationInfo {
14534        /** A constant used to indicate that a uid value is not present. */
14535        public static final int NO_UID = -1;
14536
14537        /** URI referencing where the package was downloaded from. */
14538        final Uri originatingUri;
14539
14540        /** HTTP referrer URI associated with the originatingURI. */
14541        final Uri referrer;
14542
14543        /** UID of the application that the install request originated from. */
14544        final int originatingUid;
14545
14546        /** UID of application requesting the install */
14547        final int installerUid;
14548
14549        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14550            this.originatingUri = originatingUri;
14551            this.referrer = referrer;
14552            this.originatingUid = originatingUid;
14553            this.installerUid = installerUid;
14554        }
14555    }
14556
14557    class InstallParams extends HandlerParams {
14558        final OriginInfo origin;
14559        final MoveInfo move;
14560        final IPackageInstallObserver2 observer;
14561        int installFlags;
14562        final String installerPackageName;
14563        final String volumeUuid;
14564        private InstallArgs mArgs;
14565        private int mRet;
14566        final String packageAbiOverride;
14567        final String[] grantedRuntimePermissions;
14568        final VerificationInfo verificationInfo;
14569        final Certificate[][] certificates;
14570        final int installReason;
14571
14572        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14573                int installFlags, String installerPackageName, String volumeUuid,
14574                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14575                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14576            super(user);
14577            this.origin = origin;
14578            this.move = move;
14579            this.observer = observer;
14580            this.installFlags = installFlags;
14581            this.installerPackageName = installerPackageName;
14582            this.volumeUuid = volumeUuid;
14583            this.verificationInfo = verificationInfo;
14584            this.packageAbiOverride = packageAbiOverride;
14585            this.grantedRuntimePermissions = grantedPermissions;
14586            this.certificates = certificates;
14587            this.installReason = installReason;
14588        }
14589
14590        @Override
14591        public String toString() {
14592            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14593                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14594        }
14595
14596        private int installLocationPolicy(PackageInfoLite pkgLite) {
14597            String packageName = pkgLite.packageName;
14598            int installLocation = pkgLite.installLocation;
14599            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14600            // reader
14601            synchronized (mPackages) {
14602                // Currently installed package which the new package is attempting to replace or
14603                // null if no such package is installed.
14604                PackageParser.Package installedPkg = mPackages.get(packageName);
14605                // Package which currently owns the data which the new package will own if installed.
14606                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14607                // will be null whereas dataOwnerPkg will contain information about the package
14608                // which was uninstalled while keeping its data.
14609                PackageParser.Package dataOwnerPkg = installedPkg;
14610                if (dataOwnerPkg  == null) {
14611                    PackageSetting ps = mSettings.mPackages.get(packageName);
14612                    if (ps != null) {
14613                        dataOwnerPkg = ps.pkg;
14614                    }
14615                }
14616
14617                if (dataOwnerPkg != null) {
14618                    // If installed, the package will get access to data left on the device by its
14619                    // predecessor. As a security measure, this is permited only if this is not a
14620                    // version downgrade or if the predecessor package is marked as debuggable and
14621                    // a downgrade is explicitly requested.
14622                    //
14623                    // On debuggable platform builds, downgrades are permitted even for
14624                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14625                    // not offer security guarantees and thus it's OK to disable some security
14626                    // mechanisms to make debugging/testing easier on those builds. However, even on
14627                    // debuggable builds downgrades of packages are permitted only if requested via
14628                    // installFlags. This is because we aim to keep the behavior of debuggable
14629                    // platform builds as close as possible to the behavior of non-debuggable
14630                    // platform builds.
14631                    final boolean downgradeRequested =
14632                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14633                    final boolean packageDebuggable =
14634                                (dataOwnerPkg.applicationInfo.flags
14635                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14636                    final boolean downgradePermitted =
14637                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14638                    if (!downgradePermitted) {
14639                        try {
14640                            checkDowngrade(dataOwnerPkg, pkgLite);
14641                        } catch (PackageManagerException e) {
14642                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14643                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14644                        }
14645                    }
14646                }
14647
14648                if (installedPkg != null) {
14649                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14650                        // Check for updated system application.
14651                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14652                            if (onSd) {
14653                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14654                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14655                            }
14656                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14657                        } else {
14658                            if (onSd) {
14659                                // Install flag overrides everything.
14660                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14661                            }
14662                            // If current upgrade specifies particular preference
14663                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14664                                // Application explicitly specified internal.
14665                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14666                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14667                                // App explictly prefers external. Let policy decide
14668                            } else {
14669                                // Prefer previous location
14670                                if (isExternal(installedPkg)) {
14671                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14672                                }
14673                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14674                            }
14675                        }
14676                    } else {
14677                        // Invalid install. Return error code
14678                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14679                    }
14680                }
14681            }
14682            // All the special cases have been taken care of.
14683            // Return result based on recommended install location.
14684            if (onSd) {
14685                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14686            }
14687            return pkgLite.recommendedInstallLocation;
14688        }
14689
14690        /*
14691         * Invoke remote method to get package information and install
14692         * location values. Override install location based on default
14693         * policy if needed and then create install arguments based
14694         * on the install location.
14695         */
14696        public void handleStartCopy() throws RemoteException {
14697            int ret = PackageManager.INSTALL_SUCCEEDED;
14698
14699            // If we're already staged, we've firmly committed to an install location
14700            if (origin.staged) {
14701                if (origin.file != null) {
14702                    installFlags |= PackageManager.INSTALL_INTERNAL;
14703                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14704                } else if (origin.cid != null) {
14705                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14706                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14707                } else {
14708                    throw new IllegalStateException("Invalid stage location");
14709                }
14710            }
14711
14712            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14713            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14714            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14715            PackageInfoLite pkgLite = null;
14716
14717            if (onInt && onSd) {
14718                // Check if both bits are set.
14719                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14720                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14721            } else if (onSd && ephemeral) {
14722                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14723                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14724            } else {
14725                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14726                        packageAbiOverride);
14727
14728                if (DEBUG_EPHEMERAL && ephemeral) {
14729                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14730                }
14731
14732                /*
14733                 * If we have too little free space, try to free cache
14734                 * before giving up.
14735                 */
14736                if (!origin.staged && pkgLite.recommendedInstallLocation
14737                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14738                    // TODO: focus freeing disk space on the target device
14739                    final StorageManager storage = StorageManager.from(mContext);
14740                    final long lowThreshold = storage.getStorageLowBytes(
14741                            Environment.getDataDirectory());
14742
14743                    final long sizeBytes = mContainerService.calculateInstalledSize(
14744                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14745
14746                    try {
14747                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14748                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14749                                installFlags, packageAbiOverride);
14750                    } catch (InstallerException e) {
14751                        Slog.w(TAG, "Failed to free cache", e);
14752                    }
14753
14754                    /*
14755                     * The cache free must have deleted the file we
14756                     * downloaded to install.
14757                     *
14758                     * TODO: fix the "freeCache" call to not delete
14759                     *       the file we care about.
14760                     */
14761                    if (pkgLite.recommendedInstallLocation
14762                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14763                        pkgLite.recommendedInstallLocation
14764                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14765                    }
14766                }
14767            }
14768
14769            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14770                int loc = pkgLite.recommendedInstallLocation;
14771                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14772                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14773                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14774                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14775                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14776                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14777                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14778                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14779                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14780                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14781                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14782                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14783                } else {
14784                    // Override with defaults if needed.
14785                    loc = installLocationPolicy(pkgLite);
14786                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14787                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14788                    } else if (!onSd && !onInt) {
14789                        // Override install location with flags
14790                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14791                            // Set the flag to install on external media.
14792                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14793                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14794                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14795                            if (DEBUG_EPHEMERAL) {
14796                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14797                            }
14798                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14799                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14800                                    |PackageManager.INSTALL_INTERNAL);
14801                        } else {
14802                            // Make sure the flag for installing on external
14803                            // media is unset
14804                            installFlags |= PackageManager.INSTALL_INTERNAL;
14805                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14806                        }
14807                    }
14808                }
14809            }
14810
14811            final InstallArgs args = createInstallArgs(this);
14812            mArgs = args;
14813
14814            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14815                // TODO: http://b/22976637
14816                // Apps installed for "all" users use the device owner to verify the app
14817                UserHandle verifierUser = getUser();
14818                if (verifierUser == UserHandle.ALL) {
14819                    verifierUser = UserHandle.SYSTEM;
14820                }
14821
14822                /*
14823                 * Determine if we have any installed package verifiers. If we
14824                 * do, then we'll defer to them to verify the packages.
14825                 */
14826                final int requiredUid = mRequiredVerifierPackage == null ? -1
14827                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14828                                verifierUser.getIdentifier());
14829                if (!origin.existing && requiredUid != -1
14830                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14831                    final Intent verification = new Intent(
14832                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14833                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14834                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14835                            PACKAGE_MIME_TYPE);
14836                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14837
14838                    // Query all live verifiers based on current user state
14839                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14840                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14841
14842                    if (DEBUG_VERIFY) {
14843                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14844                                + verification.toString() + " with " + pkgLite.verifiers.length
14845                                + " optional verifiers");
14846                    }
14847
14848                    final int verificationId = mPendingVerificationToken++;
14849
14850                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14851
14852                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14853                            installerPackageName);
14854
14855                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14856                            installFlags);
14857
14858                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14859                            pkgLite.packageName);
14860
14861                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14862                            pkgLite.versionCode);
14863
14864                    if (verificationInfo != null) {
14865                        if (verificationInfo.originatingUri != null) {
14866                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14867                                    verificationInfo.originatingUri);
14868                        }
14869                        if (verificationInfo.referrer != null) {
14870                            verification.putExtra(Intent.EXTRA_REFERRER,
14871                                    verificationInfo.referrer);
14872                        }
14873                        if (verificationInfo.originatingUid >= 0) {
14874                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14875                                    verificationInfo.originatingUid);
14876                        }
14877                        if (verificationInfo.installerUid >= 0) {
14878                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14879                                    verificationInfo.installerUid);
14880                        }
14881                    }
14882
14883                    final PackageVerificationState verificationState = new PackageVerificationState(
14884                            requiredUid, args);
14885
14886                    mPendingVerification.append(verificationId, verificationState);
14887
14888                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14889                            receivers, verificationState);
14890
14891                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14892                    final long idleDuration = getVerificationTimeout();
14893
14894                    /*
14895                     * If any sufficient verifiers were listed in the package
14896                     * manifest, attempt to ask them.
14897                     */
14898                    if (sufficientVerifiers != null) {
14899                        final int N = sufficientVerifiers.size();
14900                        if (N == 0) {
14901                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14902                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14903                        } else {
14904                            for (int i = 0; i < N; i++) {
14905                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14906                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14907                                        verifierComponent.getPackageName(), idleDuration,
14908                                        verifierUser.getIdentifier(), false, "package verifier");
14909
14910                                final Intent sufficientIntent = new Intent(verification);
14911                                sufficientIntent.setComponent(verifierComponent);
14912                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14913                            }
14914                        }
14915                    }
14916
14917                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14918                            mRequiredVerifierPackage, receivers);
14919                    if (ret == PackageManager.INSTALL_SUCCEEDED
14920                            && mRequiredVerifierPackage != null) {
14921                        Trace.asyncTraceBegin(
14922                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14923                        /*
14924                         * Send the intent to the required verification agent,
14925                         * but only start the verification timeout after the
14926                         * target BroadcastReceivers have run.
14927                         */
14928                        verification.setComponent(requiredVerifierComponent);
14929                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14930                                mRequiredVerifierPackage, idleDuration,
14931                                verifierUser.getIdentifier(), false, "package verifier");
14932                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14933                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14934                                new BroadcastReceiver() {
14935                                    @Override
14936                                    public void onReceive(Context context, Intent intent) {
14937                                        final Message msg = mHandler
14938                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14939                                        msg.arg1 = verificationId;
14940                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14941                                    }
14942                                }, null, 0, null, null);
14943
14944                        /*
14945                         * We don't want the copy to proceed until verification
14946                         * succeeds, so null out this field.
14947                         */
14948                        mArgs = null;
14949                    }
14950                } else {
14951                    /*
14952                     * No package verification is enabled, so immediately start
14953                     * the remote call to initiate copy using temporary file.
14954                     */
14955                    ret = args.copyApk(mContainerService, true);
14956                }
14957            }
14958
14959            mRet = ret;
14960        }
14961
14962        @Override
14963        void handleReturnCode() {
14964            // If mArgs is null, then MCS couldn't be reached. When it
14965            // reconnects, it will try again to install. At that point, this
14966            // will succeed.
14967            if (mArgs != null) {
14968                processPendingInstall(mArgs, mRet);
14969            }
14970        }
14971
14972        @Override
14973        void handleServiceError() {
14974            mArgs = createInstallArgs(this);
14975            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14976        }
14977
14978        public boolean isForwardLocked() {
14979            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14980        }
14981    }
14982
14983    /**
14984     * Used during creation of InstallArgs
14985     *
14986     * @param installFlags package installation flags
14987     * @return true if should be installed on external storage
14988     */
14989    private static boolean installOnExternalAsec(int installFlags) {
14990        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14991            return false;
14992        }
14993        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14994            return true;
14995        }
14996        return false;
14997    }
14998
14999    /**
15000     * Used during creation of InstallArgs
15001     *
15002     * @param installFlags package installation flags
15003     * @return true if should be installed as forward locked
15004     */
15005    private static boolean installForwardLocked(int installFlags) {
15006        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15007    }
15008
15009    private InstallArgs createInstallArgs(InstallParams params) {
15010        if (params.move != null) {
15011            return new MoveInstallArgs(params);
15012        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15013            return new AsecInstallArgs(params);
15014        } else {
15015            return new FileInstallArgs(params);
15016        }
15017    }
15018
15019    /**
15020     * Create args that describe an existing installed package. Typically used
15021     * when cleaning up old installs, or used as a move source.
15022     */
15023    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15024            String resourcePath, String[] instructionSets) {
15025        final boolean isInAsec;
15026        if (installOnExternalAsec(installFlags)) {
15027            /* Apps on SD card are always in ASEC containers. */
15028            isInAsec = true;
15029        } else if (installForwardLocked(installFlags)
15030                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15031            /*
15032             * Forward-locked apps are only in ASEC containers if they're the
15033             * new style
15034             */
15035            isInAsec = true;
15036        } else {
15037            isInAsec = false;
15038        }
15039
15040        if (isInAsec) {
15041            return new AsecInstallArgs(codePath, instructionSets,
15042                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15043        } else {
15044            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15045        }
15046    }
15047
15048    static abstract class InstallArgs {
15049        /** @see InstallParams#origin */
15050        final OriginInfo origin;
15051        /** @see InstallParams#move */
15052        final MoveInfo move;
15053
15054        final IPackageInstallObserver2 observer;
15055        // Always refers to PackageManager flags only
15056        final int installFlags;
15057        final String installerPackageName;
15058        final String volumeUuid;
15059        final UserHandle user;
15060        final String abiOverride;
15061        final String[] installGrantPermissions;
15062        /** If non-null, drop an async trace when the install completes */
15063        final String traceMethod;
15064        final int traceCookie;
15065        final Certificate[][] certificates;
15066        final int installReason;
15067
15068        // The list of instruction sets supported by this app. This is currently
15069        // only used during the rmdex() phase to clean up resources. We can get rid of this
15070        // if we move dex files under the common app path.
15071        /* nullable */ String[] instructionSets;
15072
15073        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15074                int installFlags, String installerPackageName, String volumeUuid,
15075                UserHandle user, String[] instructionSets,
15076                String abiOverride, String[] installGrantPermissions,
15077                String traceMethod, int traceCookie, Certificate[][] certificates,
15078                int installReason) {
15079            this.origin = origin;
15080            this.move = move;
15081            this.installFlags = installFlags;
15082            this.observer = observer;
15083            this.installerPackageName = installerPackageName;
15084            this.volumeUuid = volumeUuid;
15085            this.user = user;
15086            this.instructionSets = instructionSets;
15087            this.abiOverride = abiOverride;
15088            this.installGrantPermissions = installGrantPermissions;
15089            this.traceMethod = traceMethod;
15090            this.traceCookie = traceCookie;
15091            this.certificates = certificates;
15092            this.installReason = installReason;
15093        }
15094
15095        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15096        abstract int doPreInstall(int status);
15097
15098        /**
15099         * Rename package into final resting place. All paths on the given
15100         * scanned package should be updated to reflect the rename.
15101         */
15102        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15103        abstract int doPostInstall(int status, int uid);
15104
15105        /** @see PackageSettingBase#codePathString */
15106        abstract String getCodePath();
15107        /** @see PackageSettingBase#resourcePathString */
15108        abstract String getResourcePath();
15109
15110        // Need installer lock especially for dex file removal.
15111        abstract void cleanUpResourcesLI();
15112        abstract boolean doPostDeleteLI(boolean delete);
15113
15114        /**
15115         * Called before the source arguments are copied. This is used mostly
15116         * for MoveParams when it needs to read the source file to put it in the
15117         * destination.
15118         */
15119        int doPreCopy() {
15120            return PackageManager.INSTALL_SUCCEEDED;
15121        }
15122
15123        /**
15124         * Called after the source arguments are copied. This is used mostly for
15125         * MoveParams when it needs to read the source file to put it in the
15126         * destination.
15127         */
15128        int doPostCopy(int uid) {
15129            return PackageManager.INSTALL_SUCCEEDED;
15130        }
15131
15132        protected boolean isFwdLocked() {
15133            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15134        }
15135
15136        protected boolean isExternalAsec() {
15137            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15138        }
15139
15140        protected boolean isEphemeral() {
15141            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15142        }
15143
15144        UserHandle getUser() {
15145            return user;
15146        }
15147    }
15148
15149    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15150        if (!allCodePaths.isEmpty()) {
15151            if (instructionSets == null) {
15152                throw new IllegalStateException("instructionSet == null");
15153            }
15154            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15155            for (String codePath : allCodePaths) {
15156                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15157                    try {
15158                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15159                    } catch (InstallerException ignored) {
15160                    }
15161                }
15162            }
15163        }
15164    }
15165
15166    /**
15167     * Logic to handle installation of non-ASEC applications, including copying
15168     * and renaming logic.
15169     */
15170    class FileInstallArgs extends InstallArgs {
15171        private File codeFile;
15172        private File resourceFile;
15173
15174        // Example topology:
15175        // /data/app/com.example/base.apk
15176        // /data/app/com.example/split_foo.apk
15177        // /data/app/com.example/lib/arm/libfoo.so
15178        // /data/app/com.example/lib/arm64/libfoo.so
15179        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15180
15181        /** New install */
15182        FileInstallArgs(InstallParams params) {
15183            super(params.origin, params.move, params.observer, params.installFlags,
15184                    params.installerPackageName, params.volumeUuid,
15185                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15186                    params.grantedRuntimePermissions,
15187                    params.traceMethod, params.traceCookie, params.certificates,
15188                    params.installReason);
15189            if (isFwdLocked()) {
15190                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15191            }
15192        }
15193
15194        /** Existing install */
15195        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15196            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15197                    null, null, null, 0, null /*certificates*/,
15198                    PackageManager.INSTALL_REASON_UNKNOWN);
15199            this.codeFile = (codePath != null) ? new File(codePath) : null;
15200            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15201        }
15202
15203        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15204            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15205            try {
15206                return doCopyApk(imcs, temp);
15207            } finally {
15208                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15209            }
15210        }
15211
15212        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15213            if (origin.staged) {
15214                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15215                codeFile = origin.file;
15216                resourceFile = origin.file;
15217                return PackageManager.INSTALL_SUCCEEDED;
15218            }
15219
15220            try {
15221                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15222                final File tempDir =
15223                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15224                codeFile = tempDir;
15225                resourceFile = tempDir;
15226            } catch (IOException e) {
15227                Slog.w(TAG, "Failed to create copy file: " + e);
15228                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15229            }
15230
15231            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15232                @Override
15233                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15234                    if (!FileUtils.isValidExtFilename(name)) {
15235                        throw new IllegalArgumentException("Invalid filename: " + name);
15236                    }
15237                    try {
15238                        final File file = new File(codeFile, name);
15239                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15240                                O_RDWR | O_CREAT, 0644);
15241                        Os.chmod(file.getAbsolutePath(), 0644);
15242                        return new ParcelFileDescriptor(fd);
15243                    } catch (ErrnoException e) {
15244                        throw new RemoteException("Failed to open: " + e.getMessage());
15245                    }
15246                }
15247            };
15248
15249            int ret = PackageManager.INSTALL_SUCCEEDED;
15250            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15251            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15252                Slog.e(TAG, "Failed to copy package");
15253                return ret;
15254            }
15255
15256            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15257            NativeLibraryHelper.Handle handle = null;
15258            try {
15259                handle = NativeLibraryHelper.Handle.create(codeFile);
15260                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15261                        abiOverride);
15262            } catch (IOException e) {
15263                Slog.e(TAG, "Copying native libraries failed", e);
15264                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15265            } finally {
15266                IoUtils.closeQuietly(handle);
15267            }
15268
15269            return ret;
15270        }
15271
15272        int doPreInstall(int status) {
15273            if (status != PackageManager.INSTALL_SUCCEEDED) {
15274                cleanUp();
15275            }
15276            return status;
15277        }
15278
15279        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15280            if (status != PackageManager.INSTALL_SUCCEEDED) {
15281                cleanUp();
15282                return false;
15283            }
15284
15285            final File targetDir = codeFile.getParentFile();
15286            final File beforeCodeFile = codeFile;
15287            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15288
15289            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15290            try {
15291                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15292            } catch (ErrnoException e) {
15293                Slog.w(TAG, "Failed to rename", e);
15294                return false;
15295            }
15296
15297            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15298                Slog.w(TAG, "Failed to restorecon");
15299                return false;
15300            }
15301
15302            // Reflect the rename internally
15303            codeFile = afterCodeFile;
15304            resourceFile = afterCodeFile;
15305
15306            // Reflect the rename in scanned details
15307            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15308            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15309                    afterCodeFile, pkg.baseCodePath));
15310            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15311                    afterCodeFile, pkg.splitCodePaths));
15312
15313            // Reflect the rename in app info
15314            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15315            pkg.setApplicationInfoCodePath(pkg.codePath);
15316            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15317            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15318            pkg.setApplicationInfoResourcePath(pkg.codePath);
15319            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15320            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15321
15322            return true;
15323        }
15324
15325        int doPostInstall(int status, int uid) {
15326            if (status != PackageManager.INSTALL_SUCCEEDED) {
15327                cleanUp();
15328            }
15329            return status;
15330        }
15331
15332        @Override
15333        String getCodePath() {
15334            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15335        }
15336
15337        @Override
15338        String getResourcePath() {
15339            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15340        }
15341
15342        private boolean cleanUp() {
15343            if (codeFile == null || !codeFile.exists()) {
15344                return false;
15345            }
15346
15347            removeCodePathLI(codeFile);
15348
15349            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15350                resourceFile.delete();
15351            }
15352
15353            return true;
15354        }
15355
15356        void cleanUpResourcesLI() {
15357            // Try enumerating all code paths before deleting
15358            List<String> allCodePaths = Collections.EMPTY_LIST;
15359            if (codeFile != null && codeFile.exists()) {
15360                try {
15361                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15362                    allCodePaths = pkg.getAllCodePaths();
15363                } catch (PackageParserException e) {
15364                    // Ignored; we tried our best
15365                }
15366            }
15367
15368            cleanUp();
15369            removeDexFiles(allCodePaths, instructionSets);
15370        }
15371
15372        boolean doPostDeleteLI(boolean delete) {
15373            // XXX err, shouldn't we respect the delete flag?
15374            cleanUpResourcesLI();
15375            return true;
15376        }
15377    }
15378
15379    private boolean isAsecExternal(String cid) {
15380        final String asecPath = PackageHelper.getSdFilesystem(cid);
15381        return !asecPath.startsWith(mAsecInternalPath);
15382    }
15383
15384    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15385            PackageManagerException {
15386        if (copyRet < 0) {
15387            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15388                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15389                throw new PackageManagerException(copyRet, message);
15390            }
15391        }
15392    }
15393
15394    /**
15395     * Extract the StorageManagerService "container ID" from the full code path of an
15396     * .apk.
15397     */
15398    static String cidFromCodePath(String fullCodePath) {
15399        int eidx = fullCodePath.lastIndexOf("/");
15400        String subStr1 = fullCodePath.substring(0, eidx);
15401        int sidx = subStr1.lastIndexOf("/");
15402        return subStr1.substring(sidx+1, eidx);
15403    }
15404
15405    /**
15406     * Logic to handle installation of ASEC applications, including copying and
15407     * renaming logic.
15408     */
15409    class AsecInstallArgs extends InstallArgs {
15410        static final String RES_FILE_NAME = "pkg.apk";
15411        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15412
15413        String cid;
15414        String packagePath;
15415        String resourcePath;
15416
15417        /** New install */
15418        AsecInstallArgs(InstallParams params) {
15419            super(params.origin, params.move, params.observer, params.installFlags,
15420                    params.installerPackageName, params.volumeUuid,
15421                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15422                    params.grantedRuntimePermissions,
15423                    params.traceMethod, params.traceCookie, params.certificates,
15424                    params.installReason);
15425        }
15426
15427        /** Existing install */
15428        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15429                        boolean isExternal, boolean isForwardLocked) {
15430            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15431                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15432                    instructionSets, null, null, null, 0, null /*certificates*/,
15433                    PackageManager.INSTALL_REASON_UNKNOWN);
15434            // Hackily pretend we're still looking at a full code path
15435            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15436                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15437            }
15438
15439            // Extract cid from fullCodePath
15440            int eidx = fullCodePath.lastIndexOf("/");
15441            String subStr1 = fullCodePath.substring(0, eidx);
15442            int sidx = subStr1.lastIndexOf("/");
15443            cid = subStr1.substring(sidx+1, eidx);
15444            setMountPath(subStr1);
15445        }
15446
15447        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15448            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15449                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15450                    instructionSets, null, null, null, 0, null /*certificates*/,
15451                    PackageManager.INSTALL_REASON_UNKNOWN);
15452            this.cid = cid;
15453            setMountPath(PackageHelper.getSdDir(cid));
15454        }
15455
15456        void createCopyFile() {
15457            cid = mInstallerService.allocateExternalStageCidLegacy();
15458        }
15459
15460        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15461            if (origin.staged && origin.cid != null) {
15462                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15463                cid = origin.cid;
15464                setMountPath(PackageHelper.getSdDir(cid));
15465                return PackageManager.INSTALL_SUCCEEDED;
15466            }
15467
15468            if (temp) {
15469                createCopyFile();
15470            } else {
15471                /*
15472                 * Pre-emptively destroy the container since it's destroyed if
15473                 * copying fails due to it existing anyway.
15474                 */
15475                PackageHelper.destroySdDir(cid);
15476            }
15477
15478            final String newMountPath = imcs.copyPackageToContainer(
15479                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15480                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15481
15482            if (newMountPath != null) {
15483                setMountPath(newMountPath);
15484                return PackageManager.INSTALL_SUCCEEDED;
15485            } else {
15486                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15487            }
15488        }
15489
15490        @Override
15491        String getCodePath() {
15492            return packagePath;
15493        }
15494
15495        @Override
15496        String getResourcePath() {
15497            return resourcePath;
15498        }
15499
15500        int doPreInstall(int status) {
15501            if (status != PackageManager.INSTALL_SUCCEEDED) {
15502                // Destroy container
15503                PackageHelper.destroySdDir(cid);
15504            } else {
15505                boolean mounted = PackageHelper.isContainerMounted(cid);
15506                if (!mounted) {
15507                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15508                            Process.SYSTEM_UID);
15509                    if (newMountPath != null) {
15510                        setMountPath(newMountPath);
15511                    } else {
15512                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15513                    }
15514                }
15515            }
15516            return status;
15517        }
15518
15519        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15520            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15521            String newMountPath = null;
15522            if (PackageHelper.isContainerMounted(cid)) {
15523                // Unmount the container
15524                if (!PackageHelper.unMountSdDir(cid)) {
15525                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15526                    return false;
15527                }
15528            }
15529            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15530                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15531                        " which might be stale. Will try to clean up.");
15532                // Clean up the stale container and proceed to recreate.
15533                if (!PackageHelper.destroySdDir(newCacheId)) {
15534                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15535                    return false;
15536                }
15537                // Successfully cleaned up stale container. Try to rename again.
15538                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15539                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15540                            + " inspite of cleaning it up.");
15541                    return false;
15542                }
15543            }
15544            if (!PackageHelper.isContainerMounted(newCacheId)) {
15545                Slog.w(TAG, "Mounting container " + newCacheId);
15546                newMountPath = PackageHelper.mountSdDir(newCacheId,
15547                        getEncryptKey(), Process.SYSTEM_UID);
15548            } else {
15549                newMountPath = PackageHelper.getSdDir(newCacheId);
15550            }
15551            if (newMountPath == null) {
15552                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15553                return false;
15554            }
15555            Log.i(TAG, "Succesfully renamed " + cid +
15556                    " to " + newCacheId +
15557                    " at new path: " + newMountPath);
15558            cid = newCacheId;
15559
15560            final File beforeCodeFile = new File(packagePath);
15561            setMountPath(newMountPath);
15562            final File afterCodeFile = new File(packagePath);
15563
15564            // Reflect the rename in scanned details
15565            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15566            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15567                    afterCodeFile, pkg.baseCodePath));
15568            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15569                    afterCodeFile, pkg.splitCodePaths));
15570
15571            // Reflect the rename in app info
15572            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15573            pkg.setApplicationInfoCodePath(pkg.codePath);
15574            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15575            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15576            pkg.setApplicationInfoResourcePath(pkg.codePath);
15577            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15578            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15579
15580            return true;
15581        }
15582
15583        private void setMountPath(String mountPath) {
15584            final File mountFile = new File(mountPath);
15585
15586            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15587            if (monolithicFile.exists()) {
15588                packagePath = monolithicFile.getAbsolutePath();
15589                if (isFwdLocked()) {
15590                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15591                } else {
15592                    resourcePath = packagePath;
15593                }
15594            } else {
15595                packagePath = mountFile.getAbsolutePath();
15596                resourcePath = packagePath;
15597            }
15598        }
15599
15600        int doPostInstall(int status, int uid) {
15601            if (status != PackageManager.INSTALL_SUCCEEDED) {
15602                cleanUp();
15603            } else {
15604                final int groupOwner;
15605                final String protectedFile;
15606                if (isFwdLocked()) {
15607                    groupOwner = UserHandle.getSharedAppGid(uid);
15608                    protectedFile = RES_FILE_NAME;
15609                } else {
15610                    groupOwner = -1;
15611                    protectedFile = null;
15612                }
15613
15614                if (uid < Process.FIRST_APPLICATION_UID
15615                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15616                    Slog.e(TAG, "Failed to finalize " + cid);
15617                    PackageHelper.destroySdDir(cid);
15618                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15619                }
15620
15621                boolean mounted = PackageHelper.isContainerMounted(cid);
15622                if (!mounted) {
15623                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15624                }
15625            }
15626            return status;
15627        }
15628
15629        private void cleanUp() {
15630            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15631
15632            // Destroy secure container
15633            PackageHelper.destroySdDir(cid);
15634        }
15635
15636        private List<String> getAllCodePaths() {
15637            final File codeFile = new File(getCodePath());
15638            if (codeFile != null && codeFile.exists()) {
15639                try {
15640                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15641                    return pkg.getAllCodePaths();
15642                } catch (PackageParserException e) {
15643                    // Ignored; we tried our best
15644                }
15645            }
15646            return Collections.EMPTY_LIST;
15647        }
15648
15649        void cleanUpResourcesLI() {
15650            // Enumerate all code paths before deleting
15651            cleanUpResourcesLI(getAllCodePaths());
15652        }
15653
15654        private void cleanUpResourcesLI(List<String> allCodePaths) {
15655            cleanUp();
15656            removeDexFiles(allCodePaths, instructionSets);
15657        }
15658
15659        String getPackageName() {
15660            return getAsecPackageName(cid);
15661        }
15662
15663        boolean doPostDeleteLI(boolean delete) {
15664            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15665            final List<String> allCodePaths = getAllCodePaths();
15666            boolean mounted = PackageHelper.isContainerMounted(cid);
15667            if (mounted) {
15668                // Unmount first
15669                if (PackageHelper.unMountSdDir(cid)) {
15670                    mounted = false;
15671                }
15672            }
15673            if (!mounted && delete) {
15674                cleanUpResourcesLI(allCodePaths);
15675            }
15676            return !mounted;
15677        }
15678
15679        @Override
15680        int doPreCopy() {
15681            if (isFwdLocked()) {
15682                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15683                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15684                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15685                }
15686            }
15687
15688            return PackageManager.INSTALL_SUCCEEDED;
15689        }
15690
15691        @Override
15692        int doPostCopy(int uid) {
15693            if (isFwdLocked()) {
15694                if (uid < Process.FIRST_APPLICATION_UID
15695                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15696                                RES_FILE_NAME)) {
15697                    Slog.e(TAG, "Failed to finalize " + cid);
15698                    PackageHelper.destroySdDir(cid);
15699                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15700                }
15701            }
15702
15703            return PackageManager.INSTALL_SUCCEEDED;
15704        }
15705    }
15706
15707    /**
15708     * Logic to handle movement of existing installed applications.
15709     */
15710    class MoveInstallArgs extends InstallArgs {
15711        private File codeFile;
15712        private File resourceFile;
15713
15714        /** New install */
15715        MoveInstallArgs(InstallParams params) {
15716            super(params.origin, params.move, params.observer, params.installFlags,
15717                    params.installerPackageName, params.volumeUuid,
15718                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15719                    params.grantedRuntimePermissions,
15720                    params.traceMethod, params.traceCookie, params.certificates,
15721                    params.installReason);
15722        }
15723
15724        int copyApk(IMediaContainerService imcs, boolean temp) {
15725            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15726                    + move.fromUuid + " to " + move.toUuid);
15727            synchronized (mInstaller) {
15728                try {
15729                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15730                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15731                } catch (InstallerException e) {
15732                    Slog.w(TAG, "Failed to move app", e);
15733                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15734                }
15735            }
15736
15737            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15738            resourceFile = codeFile;
15739            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15740
15741            return PackageManager.INSTALL_SUCCEEDED;
15742        }
15743
15744        int doPreInstall(int status) {
15745            if (status != PackageManager.INSTALL_SUCCEEDED) {
15746                cleanUp(move.toUuid);
15747            }
15748            return status;
15749        }
15750
15751        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15752            if (status != PackageManager.INSTALL_SUCCEEDED) {
15753                cleanUp(move.toUuid);
15754                return false;
15755            }
15756
15757            // Reflect the move in app info
15758            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15759            pkg.setApplicationInfoCodePath(pkg.codePath);
15760            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15761            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15762            pkg.setApplicationInfoResourcePath(pkg.codePath);
15763            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15764            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15765
15766            return true;
15767        }
15768
15769        int doPostInstall(int status, int uid) {
15770            if (status == PackageManager.INSTALL_SUCCEEDED) {
15771                cleanUp(move.fromUuid);
15772            } else {
15773                cleanUp(move.toUuid);
15774            }
15775            return status;
15776        }
15777
15778        @Override
15779        String getCodePath() {
15780            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15781        }
15782
15783        @Override
15784        String getResourcePath() {
15785            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15786        }
15787
15788        private boolean cleanUp(String volumeUuid) {
15789            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15790                    move.dataAppName);
15791            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15792            final int[] userIds = sUserManager.getUserIds();
15793            synchronized (mInstallLock) {
15794                // Clean up both app data and code
15795                // All package moves are frozen until finished
15796                for (int userId : userIds) {
15797                    try {
15798                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15799                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15800                    } catch (InstallerException e) {
15801                        Slog.w(TAG, String.valueOf(e));
15802                    }
15803                }
15804                removeCodePathLI(codeFile);
15805            }
15806            return true;
15807        }
15808
15809        void cleanUpResourcesLI() {
15810            throw new UnsupportedOperationException();
15811        }
15812
15813        boolean doPostDeleteLI(boolean delete) {
15814            throw new UnsupportedOperationException();
15815        }
15816    }
15817
15818    static String getAsecPackageName(String packageCid) {
15819        int idx = packageCid.lastIndexOf("-");
15820        if (idx == -1) {
15821            return packageCid;
15822        }
15823        return packageCid.substring(0, idx);
15824    }
15825
15826    // Utility method used to create code paths based on package name and available index.
15827    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15828        String idxStr = "";
15829        int idx = 1;
15830        // Fall back to default value of idx=1 if prefix is not
15831        // part of oldCodePath
15832        if (oldCodePath != null) {
15833            String subStr = oldCodePath;
15834            // Drop the suffix right away
15835            if (suffix != null && subStr.endsWith(suffix)) {
15836                subStr = subStr.substring(0, subStr.length() - suffix.length());
15837            }
15838            // If oldCodePath already contains prefix find out the
15839            // ending index to either increment or decrement.
15840            int sidx = subStr.lastIndexOf(prefix);
15841            if (sidx != -1) {
15842                subStr = subStr.substring(sidx + prefix.length());
15843                if (subStr != null) {
15844                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15845                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15846                    }
15847                    try {
15848                        idx = Integer.parseInt(subStr);
15849                        if (idx <= 1) {
15850                            idx++;
15851                        } else {
15852                            idx--;
15853                        }
15854                    } catch(NumberFormatException e) {
15855                    }
15856                }
15857            }
15858        }
15859        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15860        return prefix + idxStr;
15861    }
15862
15863    private File getNextCodePath(File targetDir, String packageName) {
15864        File result;
15865        SecureRandom random = new SecureRandom();
15866        byte[] bytes = new byte[16];
15867        do {
15868            random.nextBytes(bytes);
15869            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15870            result = new File(targetDir, packageName + "-" + suffix);
15871        } while (result.exists());
15872        return result;
15873    }
15874
15875    // Utility method that returns the relative package path with respect
15876    // to the installation directory. Like say for /data/data/com.test-1.apk
15877    // string com.test-1 is returned.
15878    static String deriveCodePathName(String codePath) {
15879        if (codePath == null) {
15880            return null;
15881        }
15882        final File codeFile = new File(codePath);
15883        final String name = codeFile.getName();
15884        if (codeFile.isDirectory()) {
15885            return name;
15886        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15887            final int lastDot = name.lastIndexOf('.');
15888            return name.substring(0, lastDot);
15889        } else {
15890            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15891            return null;
15892        }
15893    }
15894
15895    static class PackageInstalledInfo {
15896        String name;
15897        int uid;
15898        // The set of users that originally had this package installed.
15899        int[] origUsers;
15900        // The set of users that now have this package installed.
15901        int[] newUsers;
15902        PackageParser.Package pkg;
15903        int returnCode;
15904        String returnMsg;
15905        PackageRemovedInfo removedInfo;
15906        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15907
15908        public void setError(int code, String msg) {
15909            setReturnCode(code);
15910            setReturnMessage(msg);
15911            Slog.w(TAG, msg);
15912        }
15913
15914        public void setError(String msg, PackageParserException e) {
15915            setReturnCode(e.error);
15916            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15917            Slog.w(TAG, msg, e);
15918        }
15919
15920        public void setError(String msg, PackageManagerException e) {
15921            returnCode = e.error;
15922            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15923            Slog.w(TAG, msg, e);
15924        }
15925
15926        public void setReturnCode(int returnCode) {
15927            this.returnCode = returnCode;
15928            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15929            for (int i = 0; i < childCount; i++) {
15930                addedChildPackages.valueAt(i).returnCode = returnCode;
15931            }
15932        }
15933
15934        private void setReturnMessage(String returnMsg) {
15935            this.returnMsg = returnMsg;
15936            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15937            for (int i = 0; i < childCount; i++) {
15938                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15939            }
15940        }
15941
15942        // In some error cases we want to convey more info back to the observer
15943        String origPackage;
15944        String origPermission;
15945    }
15946
15947    /*
15948     * Install a non-existing package.
15949     */
15950    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15951            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15952            PackageInstalledInfo res, int installReason) {
15953        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15954
15955        // Remember this for later, in case we need to rollback this install
15956        String pkgName = pkg.packageName;
15957
15958        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15959
15960        synchronized(mPackages) {
15961            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15962            if (renamedPackage != null) {
15963                // A package with the same name is already installed, though
15964                // it has been renamed to an older name.  The package we
15965                // are trying to install should be installed as an update to
15966                // the existing one, but that has not been requested, so bail.
15967                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15968                        + " without first uninstalling package running as "
15969                        + renamedPackage);
15970                return;
15971            }
15972            if (mPackages.containsKey(pkgName)) {
15973                // Don't allow installation over an existing package with the same name.
15974                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15975                        + " without first uninstalling.");
15976                return;
15977            }
15978        }
15979
15980        try {
15981            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15982                    System.currentTimeMillis(), user);
15983
15984            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15985
15986            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15987                prepareAppDataAfterInstallLIF(newPackage);
15988
15989            } else {
15990                // Remove package from internal structures, but keep around any
15991                // data that might have already existed
15992                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15993                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15994            }
15995        } catch (PackageManagerException e) {
15996            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15997        }
15998
15999        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16000    }
16001
16002    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16003        // Can't rotate keys during boot or if sharedUser.
16004        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16005                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16006            return false;
16007        }
16008        // app is using upgradeKeySets; make sure all are valid
16009        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16010        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16011        for (int i = 0; i < upgradeKeySets.length; i++) {
16012            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16013                Slog.wtf(TAG, "Package "
16014                         + (oldPs.name != null ? oldPs.name : "<null>")
16015                         + " contains upgrade-key-set reference to unknown key-set: "
16016                         + upgradeKeySets[i]
16017                         + " reverting to signatures check.");
16018                return false;
16019            }
16020        }
16021        return true;
16022    }
16023
16024    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16025        // Upgrade keysets are being used.  Determine if new package has a superset of the
16026        // required keys.
16027        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16028        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16029        for (int i = 0; i < upgradeKeySets.length; i++) {
16030            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16031            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16032                return true;
16033            }
16034        }
16035        return false;
16036    }
16037
16038    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16039        try (DigestInputStream digestStream =
16040                new DigestInputStream(new FileInputStream(file), digest)) {
16041            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16042        }
16043    }
16044
16045    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16046            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16047            int installReason) {
16048        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16049
16050        final PackageParser.Package oldPackage;
16051        final String pkgName = pkg.packageName;
16052        final int[] allUsers;
16053        final int[] installedUsers;
16054
16055        synchronized(mPackages) {
16056            oldPackage = mPackages.get(pkgName);
16057            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16058
16059            // don't allow upgrade to target a release SDK from a pre-release SDK
16060            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16061                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16062            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16063                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16064            if (oldTargetsPreRelease
16065                    && !newTargetsPreRelease
16066                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16067                Slog.w(TAG, "Can't install package targeting released sdk");
16068                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16069                return;
16070            }
16071
16072            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16073
16074            // verify signatures are valid
16075            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16076                if (!checkUpgradeKeySetLP(ps, pkg)) {
16077                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16078                            "New package not signed by keys specified by upgrade-keysets: "
16079                                    + pkgName);
16080                    return;
16081                }
16082            } else {
16083                // default to original signature matching
16084                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16085                        != PackageManager.SIGNATURE_MATCH) {
16086                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16087                            "New package has a different signature: " + pkgName);
16088                    return;
16089                }
16090            }
16091
16092            // don't allow a system upgrade unless the upgrade hash matches
16093            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16094                byte[] digestBytes = null;
16095                try {
16096                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16097                    updateDigest(digest, new File(pkg.baseCodePath));
16098                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16099                        for (String path : pkg.splitCodePaths) {
16100                            updateDigest(digest, new File(path));
16101                        }
16102                    }
16103                    digestBytes = digest.digest();
16104                } catch (NoSuchAlgorithmException | IOException e) {
16105                    res.setError(INSTALL_FAILED_INVALID_APK,
16106                            "Could not compute hash: " + pkgName);
16107                    return;
16108                }
16109                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16110                    res.setError(INSTALL_FAILED_INVALID_APK,
16111                            "New package fails restrict-update check: " + pkgName);
16112                    return;
16113                }
16114                // retain upgrade restriction
16115                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16116            }
16117
16118            // Check for shared user id changes
16119            String invalidPackageName =
16120                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16121            if (invalidPackageName != null) {
16122                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16123                        "Package " + invalidPackageName + " tried to change user "
16124                                + oldPackage.mSharedUserId);
16125                return;
16126            }
16127
16128            // In case of rollback, remember per-user/profile install state
16129            allUsers = sUserManager.getUserIds();
16130            installedUsers = ps.queryInstalledUsers(allUsers, true);
16131
16132            // don't allow an upgrade from full to ephemeral
16133            if (isInstantApp) {
16134                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16135                    for (int currentUser : allUsers) {
16136                        if (!ps.getInstantApp(currentUser)) {
16137                            // can't downgrade from full to instant
16138                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16139                                    + " for user: " + currentUser);
16140                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16141                            return;
16142                        }
16143                    }
16144                } else if (!ps.getInstantApp(user.getIdentifier())) {
16145                    // can't downgrade from full to instant
16146                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16147                            + " for user: " + user.getIdentifier());
16148                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16149                    return;
16150                }
16151            }
16152        }
16153
16154        // Update what is removed
16155        res.removedInfo = new PackageRemovedInfo(this);
16156        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16157        res.removedInfo.removedPackage = oldPackage.packageName;
16158        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16159        res.removedInfo.isUpdate = true;
16160        res.removedInfo.origUsers = installedUsers;
16161        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
16162        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16163        for (int i = 0; i < installedUsers.length; i++) {
16164            final int userId = installedUsers[i];
16165            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16166        }
16167
16168        final int childCount = (oldPackage.childPackages != null)
16169                ? oldPackage.childPackages.size() : 0;
16170        for (int i = 0; i < childCount; i++) {
16171            boolean childPackageUpdated = false;
16172            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16173            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16174            if (res.addedChildPackages != null) {
16175                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16176                if (childRes != null) {
16177                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16178                    childRes.removedInfo.removedPackage = childPkg.packageName;
16179                    childRes.removedInfo.isUpdate = true;
16180                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16181                    childPackageUpdated = true;
16182                }
16183            }
16184            if (!childPackageUpdated) {
16185                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16186                childRemovedRes.removedPackage = childPkg.packageName;
16187                childRemovedRes.isUpdate = false;
16188                childRemovedRes.dataRemoved = true;
16189                synchronized (mPackages) {
16190                    if (childPs != null) {
16191                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16192                    }
16193                }
16194                if (res.removedInfo.removedChildPackages == null) {
16195                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16196                }
16197                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16198            }
16199        }
16200
16201        boolean sysPkg = (isSystemApp(oldPackage));
16202        if (sysPkg) {
16203            // Set the system/privileged flags as needed
16204            final boolean privileged =
16205                    (oldPackage.applicationInfo.privateFlags
16206                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16207            final int systemPolicyFlags = policyFlags
16208                    | PackageParser.PARSE_IS_SYSTEM
16209                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16210
16211            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16212                    user, allUsers, installerPackageName, res, installReason);
16213        } else {
16214            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16215                    user, allUsers, installerPackageName, res, installReason);
16216        }
16217    }
16218
16219    public List<String> getPreviousCodePaths(String packageName) {
16220        final PackageSetting ps = mSettings.mPackages.get(packageName);
16221        final List<String> result = new ArrayList<String>();
16222        if (ps != null && ps.oldCodePaths != null) {
16223            result.addAll(ps.oldCodePaths);
16224        }
16225        return result;
16226    }
16227
16228    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16229            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16230            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16231            int installReason) {
16232        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16233                + deletedPackage);
16234
16235        String pkgName = deletedPackage.packageName;
16236        boolean deletedPkg = true;
16237        boolean addedPkg = false;
16238        boolean updatedSettings = false;
16239        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16240        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16241                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16242
16243        final long origUpdateTime = (pkg.mExtras != null)
16244                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16245
16246        // First delete the existing package while retaining the data directory
16247        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16248                res.removedInfo, true, pkg)) {
16249            // If the existing package wasn't successfully deleted
16250            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16251            deletedPkg = false;
16252        } else {
16253            // Successfully deleted the old package; proceed with replace.
16254
16255            // If deleted package lived in a container, give users a chance to
16256            // relinquish resources before killing.
16257            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16258                if (DEBUG_INSTALL) {
16259                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16260                }
16261                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16262                final ArrayList<String> pkgList = new ArrayList<String>(1);
16263                pkgList.add(deletedPackage.applicationInfo.packageName);
16264                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16265            }
16266
16267            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16268                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16269            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16270
16271            try {
16272                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16273                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16274                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16275                        installReason);
16276
16277                // Update the in-memory copy of the previous code paths.
16278                PackageSetting ps = mSettings.mPackages.get(pkgName);
16279                if (!killApp) {
16280                    if (ps.oldCodePaths == null) {
16281                        ps.oldCodePaths = new ArraySet<>();
16282                    }
16283                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16284                    if (deletedPackage.splitCodePaths != null) {
16285                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16286                    }
16287                } else {
16288                    ps.oldCodePaths = null;
16289                }
16290                if (ps.childPackageNames != null) {
16291                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16292                        final String childPkgName = ps.childPackageNames.get(i);
16293                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16294                        childPs.oldCodePaths = ps.oldCodePaths;
16295                    }
16296                }
16297                // set instant app status, but, only if it's explicitly specified
16298                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16299                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16300                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16301                prepareAppDataAfterInstallLIF(newPackage);
16302                addedPkg = true;
16303                mDexManager.notifyPackageUpdated(newPackage.packageName,
16304                        newPackage.baseCodePath, newPackage.splitCodePaths);
16305            } catch (PackageManagerException e) {
16306                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16307            }
16308        }
16309
16310        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16311            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16312
16313            // Revert all internal state mutations and added folders for the failed install
16314            if (addedPkg) {
16315                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16316                        res.removedInfo, true, null);
16317            }
16318
16319            // Restore the old package
16320            if (deletedPkg) {
16321                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16322                File restoreFile = new File(deletedPackage.codePath);
16323                // Parse old package
16324                boolean oldExternal = isExternal(deletedPackage);
16325                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16326                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16327                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16328                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16329                try {
16330                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16331                            null);
16332                } catch (PackageManagerException e) {
16333                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16334                            + e.getMessage());
16335                    return;
16336                }
16337
16338                synchronized (mPackages) {
16339                    // Ensure the installer package name up to date
16340                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16341
16342                    // Update permissions for restored package
16343                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16344
16345                    mSettings.writeLPr();
16346                }
16347
16348                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16349            }
16350        } else {
16351            synchronized (mPackages) {
16352                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16353                if (ps != null) {
16354                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16355                    if (res.removedInfo.removedChildPackages != null) {
16356                        final int childCount = res.removedInfo.removedChildPackages.size();
16357                        // Iterate in reverse as we may modify the collection
16358                        for (int i = childCount - 1; i >= 0; i--) {
16359                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16360                            if (res.addedChildPackages.containsKey(childPackageName)) {
16361                                res.removedInfo.removedChildPackages.removeAt(i);
16362                            } else {
16363                                PackageRemovedInfo childInfo = res.removedInfo
16364                                        .removedChildPackages.valueAt(i);
16365                                childInfo.removedForAllUsers = mPackages.get(
16366                                        childInfo.removedPackage) == null;
16367                            }
16368                        }
16369                    }
16370                }
16371            }
16372        }
16373    }
16374
16375    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16376            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16377            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16378            int installReason) {
16379        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16380                + ", old=" + deletedPackage);
16381
16382        final boolean disabledSystem;
16383
16384        // Remove existing system package
16385        removePackageLI(deletedPackage, true);
16386
16387        synchronized (mPackages) {
16388            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16389        }
16390        if (!disabledSystem) {
16391            // We didn't need to disable the .apk as a current system package,
16392            // which means we are replacing another update that is already
16393            // installed.  We need to make sure to delete the older one's .apk.
16394            res.removedInfo.args = createInstallArgsForExisting(0,
16395                    deletedPackage.applicationInfo.getCodePath(),
16396                    deletedPackage.applicationInfo.getResourcePath(),
16397                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16398        } else {
16399            res.removedInfo.args = null;
16400        }
16401
16402        // Successfully disabled the old package. Now proceed with re-installation
16403        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16404                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16405        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16406
16407        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16408        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16409                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16410
16411        PackageParser.Package newPackage = null;
16412        try {
16413            // Add the package to the internal data structures
16414            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16415
16416            // Set the update and install times
16417            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16418            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16419                    System.currentTimeMillis());
16420
16421            // Update the package dynamic state if succeeded
16422            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16423                // Now that the install succeeded make sure we remove data
16424                // directories for any child package the update removed.
16425                final int deletedChildCount = (deletedPackage.childPackages != null)
16426                        ? deletedPackage.childPackages.size() : 0;
16427                final int newChildCount = (newPackage.childPackages != null)
16428                        ? newPackage.childPackages.size() : 0;
16429                for (int i = 0; i < deletedChildCount; i++) {
16430                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16431                    boolean childPackageDeleted = true;
16432                    for (int j = 0; j < newChildCount; j++) {
16433                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16434                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16435                            childPackageDeleted = false;
16436                            break;
16437                        }
16438                    }
16439                    if (childPackageDeleted) {
16440                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16441                                deletedChildPkg.packageName);
16442                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16443                            PackageRemovedInfo removedChildRes = res.removedInfo
16444                                    .removedChildPackages.get(deletedChildPkg.packageName);
16445                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16446                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16447                        }
16448                    }
16449                }
16450
16451                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16452                        installReason);
16453                prepareAppDataAfterInstallLIF(newPackage);
16454
16455                mDexManager.notifyPackageUpdated(newPackage.packageName,
16456                            newPackage.baseCodePath, newPackage.splitCodePaths);
16457            }
16458        } catch (PackageManagerException e) {
16459            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16460            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16461        }
16462
16463        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16464            // Re installation failed. Restore old information
16465            // Remove new pkg information
16466            if (newPackage != null) {
16467                removeInstalledPackageLI(newPackage, true);
16468            }
16469            // Add back the old system package
16470            try {
16471                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16472            } catch (PackageManagerException e) {
16473                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16474            }
16475
16476            synchronized (mPackages) {
16477                if (disabledSystem) {
16478                    enableSystemPackageLPw(deletedPackage);
16479                }
16480
16481                // Ensure the installer package name up to date
16482                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16483
16484                // Update permissions for restored package
16485                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16486
16487                mSettings.writeLPr();
16488            }
16489
16490            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16491                    + " after failed upgrade");
16492        }
16493    }
16494
16495    /**
16496     * Checks whether the parent or any of the child packages have a change shared
16497     * user. For a package to be a valid update the shred users of the parent and
16498     * the children should match. We may later support changing child shared users.
16499     * @param oldPkg The updated package.
16500     * @param newPkg The update package.
16501     * @return The shared user that change between the versions.
16502     */
16503    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16504            PackageParser.Package newPkg) {
16505        // Check parent shared user
16506        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16507            return newPkg.packageName;
16508        }
16509        // Check child shared users
16510        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16511        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16512        for (int i = 0; i < newChildCount; i++) {
16513            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16514            // If this child was present, did it have the same shared user?
16515            for (int j = 0; j < oldChildCount; j++) {
16516                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16517                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16518                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16519                    return newChildPkg.packageName;
16520                }
16521            }
16522        }
16523        return null;
16524    }
16525
16526    private void removeNativeBinariesLI(PackageSetting ps) {
16527        // Remove the lib path for the parent package
16528        if (ps != null) {
16529            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16530            // Remove the lib path for the child packages
16531            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16532            for (int i = 0; i < childCount; i++) {
16533                PackageSetting childPs = null;
16534                synchronized (mPackages) {
16535                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16536                }
16537                if (childPs != null) {
16538                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16539                            .legacyNativeLibraryPathString);
16540                }
16541            }
16542        }
16543    }
16544
16545    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16546        // Enable the parent package
16547        mSettings.enableSystemPackageLPw(pkg.packageName);
16548        // Enable the child packages
16549        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16550        for (int i = 0; i < childCount; i++) {
16551            PackageParser.Package childPkg = pkg.childPackages.get(i);
16552            mSettings.enableSystemPackageLPw(childPkg.packageName);
16553        }
16554    }
16555
16556    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16557            PackageParser.Package newPkg) {
16558        // Disable the parent package (parent always replaced)
16559        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16560        // Disable the child packages
16561        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16562        for (int i = 0; i < childCount; i++) {
16563            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16564            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16565            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16566        }
16567        return disabled;
16568    }
16569
16570    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16571            String installerPackageName) {
16572        // Enable the parent package
16573        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16574        // Enable the child packages
16575        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16576        for (int i = 0; i < childCount; i++) {
16577            PackageParser.Package childPkg = pkg.childPackages.get(i);
16578            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16579        }
16580    }
16581
16582    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16583        // Collect all used permissions in the UID
16584        ArraySet<String> usedPermissions = new ArraySet<>();
16585        final int packageCount = su.packages.size();
16586        for (int i = 0; i < packageCount; i++) {
16587            PackageSetting ps = su.packages.valueAt(i);
16588            if (ps.pkg == null) {
16589                continue;
16590            }
16591            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16592            for (int j = 0; j < requestedPermCount; j++) {
16593                String permission = ps.pkg.requestedPermissions.get(j);
16594                BasePermission bp = mSettings.mPermissions.get(permission);
16595                if (bp != null) {
16596                    usedPermissions.add(permission);
16597                }
16598            }
16599        }
16600
16601        PermissionsState permissionsState = su.getPermissionsState();
16602        // Prune install permissions
16603        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16604        final int installPermCount = installPermStates.size();
16605        for (int i = installPermCount - 1; i >= 0;  i--) {
16606            PermissionState permissionState = installPermStates.get(i);
16607            if (!usedPermissions.contains(permissionState.getName())) {
16608                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16609                if (bp != null) {
16610                    permissionsState.revokeInstallPermission(bp);
16611                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16612                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16613                }
16614            }
16615        }
16616
16617        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16618
16619        // Prune runtime permissions
16620        for (int userId : allUserIds) {
16621            List<PermissionState> runtimePermStates = permissionsState
16622                    .getRuntimePermissionStates(userId);
16623            final int runtimePermCount = runtimePermStates.size();
16624            for (int i = runtimePermCount - 1; i >= 0; i--) {
16625                PermissionState permissionState = runtimePermStates.get(i);
16626                if (!usedPermissions.contains(permissionState.getName())) {
16627                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16628                    if (bp != null) {
16629                        permissionsState.revokeRuntimePermission(bp, userId);
16630                        permissionsState.updatePermissionFlags(bp, userId,
16631                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16632                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16633                                runtimePermissionChangedUserIds, userId);
16634                    }
16635                }
16636            }
16637        }
16638
16639        return runtimePermissionChangedUserIds;
16640    }
16641
16642    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16643            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16644        // Update the parent package setting
16645        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16646                res, user, installReason);
16647        // Update the child packages setting
16648        final int childCount = (newPackage.childPackages != null)
16649                ? newPackage.childPackages.size() : 0;
16650        for (int i = 0; i < childCount; i++) {
16651            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16652            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16653            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16654                    childRes.origUsers, childRes, user, installReason);
16655        }
16656    }
16657
16658    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16659            String installerPackageName, int[] allUsers, int[] installedForUsers,
16660            PackageInstalledInfo res, UserHandle user, int installReason) {
16661        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16662
16663        String pkgName = newPackage.packageName;
16664        synchronized (mPackages) {
16665            //write settings. the installStatus will be incomplete at this stage.
16666            //note that the new package setting would have already been
16667            //added to mPackages. It hasn't been persisted yet.
16668            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16669            // TODO: Remove this write? It's also written at the end of this method
16670            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16671            mSettings.writeLPr();
16672            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16673        }
16674
16675        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16676        synchronized (mPackages) {
16677            updatePermissionsLPw(newPackage.packageName, newPackage,
16678                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16679                            ? UPDATE_PERMISSIONS_ALL : 0));
16680            // For system-bundled packages, we assume that installing an upgraded version
16681            // of the package implies that the user actually wants to run that new code,
16682            // so we enable the package.
16683            PackageSetting ps = mSettings.mPackages.get(pkgName);
16684            final int userId = user.getIdentifier();
16685            if (ps != null) {
16686                if (isSystemApp(newPackage)) {
16687                    if (DEBUG_INSTALL) {
16688                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16689                    }
16690                    // Enable system package for requested users
16691                    if (res.origUsers != null) {
16692                        for (int origUserId : res.origUsers) {
16693                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16694                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16695                                        origUserId, installerPackageName);
16696                            }
16697                        }
16698                    }
16699                    // Also convey the prior install/uninstall state
16700                    if (allUsers != null && installedForUsers != null) {
16701                        for (int currentUserId : allUsers) {
16702                            final boolean installed = ArrayUtils.contains(
16703                                    installedForUsers, currentUserId);
16704                            if (DEBUG_INSTALL) {
16705                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16706                            }
16707                            ps.setInstalled(installed, currentUserId);
16708                        }
16709                        // these install state changes will be persisted in the
16710                        // upcoming call to mSettings.writeLPr().
16711                    }
16712                }
16713                // It's implied that when a user requests installation, they want the app to be
16714                // installed and enabled.
16715                if (userId != UserHandle.USER_ALL) {
16716                    ps.setInstalled(true, userId);
16717                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16718                }
16719
16720                // When replacing an existing package, preserve the original install reason for all
16721                // users that had the package installed before.
16722                final Set<Integer> previousUserIds = new ArraySet<>();
16723                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16724                    final int installReasonCount = res.removedInfo.installReasons.size();
16725                    for (int i = 0; i < installReasonCount; i++) {
16726                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16727                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16728                        ps.setInstallReason(previousInstallReason, previousUserId);
16729                        previousUserIds.add(previousUserId);
16730                    }
16731                }
16732
16733                // Set install reason for users that are having the package newly installed.
16734                if (userId == UserHandle.USER_ALL) {
16735                    for (int currentUserId : sUserManager.getUserIds()) {
16736                        if (!previousUserIds.contains(currentUserId)) {
16737                            ps.setInstallReason(installReason, currentUserId);
16738                        }
16739                    }
16740                } else if (!previousUserIds.contains(userId)) {
16741                    ps.setInstallReason(installReason, userId);
16742                }
16743                mSettings.writeKernelMappingLPr(ps);
16744            }
16745            res.name = pkgName;
16746            res.uid = newPackage.applicationInfo.uid;
16747            res.pkg = newPackage;
16748            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16749            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16750            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16751            //to update install status
16752            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16753            mSettings.writeLPr();
16754            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16755        }
16756
16757        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16758    }
16759
16760    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16761        try {
16762            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16763            installPackageLI(args, res);
16764        } finally {
16765            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16766        }
16767    }
16768
16769    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16770        final int installFlags = args.installFlags;
16771        final String installerPackageName = args.installerPackageName;
16772        final String volumeUuid = args.volumeUuid;
16773        final File tmpPackageFile = new File(args.getCodePath());
16774        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16775        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16776                || (args.volumeUuid != null));
16777        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16778        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16779        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16780        boolean replace = false;
16781        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16782        if (args.move != null) {
16783            // moving a complete application; perform an initial scan on the new install location
16784            scanFlags |= SCAN_INITIAL;
16785        }
16786        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16787            scanFlags |= SCAN_DONT_KILL_APP;
16788        }
16789        if (instantApp) {
16790            scanFlags |= SCAN_AS_INSTANT_APP;
16791        }
16792        if (fullApp) {
16793            scanFlags |= SCAN_AS_FULL_APP;
16794        }
16795
16796        // Result object to be returned
16797        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16798
16799        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16800
16801        // Sanity check
16802        if (instantApp && (forwardLocked || onExternal)) {
16803            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16804                    + " external=" + onExternal);
16805            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16806            return;
16807        }
16808
16809        // Retrieve PackageSettings and parse package
16810        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16811                | PackageParser.PARSE_ENFORCE_CODE
16812                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16813                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16814                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16815                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16816        PackageParser pp = new PackageParser();
16817        pp.setSeparateProcesses(mSeparateProcesses);
16818        pp.setDisplayMetrics(mMetrics);
16819        pp.setCallback(mPackageParserCallback);
16820
16821        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16822        final PackageParser.Package pkg;
16823        try {
16824            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16825        } catch (PackageParserException e) {
16826            res.setError("Failed parse during installPackageLI", e);
16827            return;
16828        } finally {
16829            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16830        }
16831
16832        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16833        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16834            Slog.w(TAG, "Instant app package " + pkg.packageName
16835                    + " does not target O, this will be a fatal error.");
16836            // STOPSHIP: Make this a fatal error
16837            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16838        }
16839        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16840            Slog.w(TAG, "Instant app package " + pkg.packageName
16841                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16842            // STOPSHIP: Make this a fatal error
16843            pkg.applicationInfo.targetSandboxVersion = 2;
16844        }
16845
16846        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16847            // Static shared libraries have synthetic package names
16848            renameStaticSharedLibraryPackage(pkg);
16849
16850            // No static shared libs on external storage
16851            if (onExternal) {
16852                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16853                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16854                        "Packages declaring static-shared libs cannot be updated");
16855                return;
16856            }
16857        }
16858
16859        // If we are installing a clustered package add results for the children
16860        if (pkg.childPackages != null) {
16861            synchronized (mPackages) {
16862                final int childCount = pkg.childPackages.size();
16863                for (int i = 0; i < childCount; i++) {
16864                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16865                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16866                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16867                    childRes.pkg = childPkg;
16868                    childRes.name = childPkg.packageName;
16869                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16870                    if (childPs != null) {
16871                        childRes.origUsers = childPs.queryInstalledUsers(
16872                                sUserManager.getUserIds(), true);
16873                    }
16874                    if ((mPackages.containsKey(childPkg.packageName))) {
16875                        childRes.removedInfo = new PackageRemovedInfo(this);
16876                        childRes.removedInfo.removedPackage = childPkg.packageName;
16877                    }
16878                    if (res.addedChildPackages == null) {
16879                        res.addedChildPackages = new ArrayMap<>();
16880                    }
16881                    res.addedChildPackages.put(childPkg.packageName, childRes);
16882                }
16883            }
16884        }
16885
16886        // If package doesn't declare API override, mark that we have an install
16887        // time CPU ABI override.
16888        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16889            pkg.cpuAbiOverride = args.abiOverride;
16890        }
16891
16892        String pkgName = res.name = pkg.packageName;
16893        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16894            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16895                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16896                return;
16897            }
16898        }
16899
16900        try {
16901            // either use what we've been given or parse directly from the APK
16902            if (args.certificates != null) {
16903                try {
16904                    PackageParser.populateCertificates(pkg, args.certificates);
16905                } catch (PackageParserException e) {
16906                    // there was something wrong with the certificates we were given;
16907                    // try to pull them from the APK
16908                    PackageParser.collectCertificates(pkg, parseFlags);
16909                }
16910            } else {
16911                PackageParser.collectCertificates(pkg, parseFlags);
16912            }
16913        } catch (PackageParserException e) {
16914            res.setError("Failed collect during installPackageLI", e);
16915            return;
16916        }
16917
16918        // Get rid of all references to package scan path via parser.
16919        pp = null;
16920        String oldCodePath = null;
16921        boolean systemApp = false;
16922        synchronized (mPackages) {
16923            // Check if installing already existing package
16924            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16925                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16926                if (pkg.mOriginalPackages != null
16927                        && pkg.mOriginalPackages.contains(oldName)
16928                        && mPackages.containsKey(oldName)) {
16929                    // This package is derived from an original package,
16930                    // and this device has been updating from that original
16931                    // name.  We must continue using the original name, so
16932                    // rename the new package here.
16933                    pkg.setPackageName(oldName);
16934                    pkgName = pkg.packageName;
16935                    replace = true;
16936                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16937                            + oldName + " pkgName=" + pkgName);
16938                } else if (mPackages.containsKey(pkgName)) {
16939                    // This package, under its official name, already exists
16940                    // on the device; we should replace it.
16941                    replace = true;
16942                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16943                }
16944
16945                // Child packages are installed through the parent package
16946                if (pkg.parentPackage != null) {
16947                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16948                            "Package " + pkg.packageName + " is child of package "
16949                                    + pkg.parentPackage.parentPackage + ". Child packages "
16950                                    + "can be updated only through the parent package.");
16951                    return;
16952                }
16953
16954                if (replace) {
16955                    // Prevent apps opting out from runtime permissions
16956                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16957                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16958                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16959                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16960                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16961                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16962                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16963                                        + " doesn't support runtime permissions but the old"
16964                                        + " target SDK " + oldTargetSdk + " does.");
16965                        return;
16966                    }
16967                    // Prevent apps from downgrading their targetSandbox.
16968                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16969                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16970                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16971                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16972                                "Package " + pkg.packageName + " new target sandbox "
16973                                + newTargetSandbox + " is incompatible with the previous value of"
16974                                + oldTargetSandbox + ".");
16975                        return;
16976                    }
16977
16978                    // Prevent installing of child packages
16979                    if (oldPackage.parentPackage != null) {
16980                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16981                                "Package " + pkg.packageName + " is child of package "
16982                                        + oldPackage.parentPackage + ". Child packages "
16983                                        + "can be updated only through the parent package.");
16984                        return;
16985                    }
16986                }
16987            }
16988
16989            PackageSetting ps = mSettings.mPackages.get(pkgName);
16990            if (ps != null) {
16991                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16992
16993                // Static shared libs have same package with different versions where
16994                // we internally use a synthetic package name to allow multiple versions
16995                // of the same package, therefore we need to compare signatures against
16996                // the package setting for the latest library version.
16997                PackageSetting signatureCheckPs = ps;
16998                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16999                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17000                    if (libraryEntry != null) {
17001                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17002                    }
17003                }
17004
17005                // Quick sanity check that we're signed correctly if updating;
17006                // we'll check this again later when scanning, but we want to
17007                // bail early here before tripping over redefined permissions.
17008                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17009                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17010                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17011                                + pkg.packageName + " upgrade keys do not match the "
17012                                + "previously installed version");
17013                        return;
17014                    }
17015                } else {
17016                    try {
17017                        verifySignaturesLP(signatureCheckPs, pkg);
17018                    } catch (PackageManagerException e) {
17019                        res.setError(e.error, e.getMessage());
17020                        return;
17021                    }
17022                }
17023
17024                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17025                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17026                    systemApp = (ps.pkg.applicationInfo.flags &
17027                            ApplicationInfo.FLAG_SYSTEM) != 0;
17028                }
17029                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17030            }
17031
17032            int N = pkg.permissions.size();
17033            for (int i = N-1; i >= 0; i--) {
17034                PackageParser.Permission perm = pkg.permissions.get(i);
17035                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17036
17037                // Don't allow anyone but the platform to define ephemeral permissions.
17038                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17039                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17040                    Slog.w(TAG, "Package " + pkg.packageName
17041                            + " attempting to delcare ephemeral permission "
17042                            + perm.info.name + "; Removing ephemeral.");
17043                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17044                }
17045                // Check whether the newly-scanned package wants to define an already-defined perm
17046                if (bp != null) {
17047                    // If the defining package is signed with our cert, it's okay.  This
17048                    // also includes the "updating the same package" case, of course.
17049                    // "updating same package" could also involve key-rotation.
17050                    final boolean sigsOk;
17051                    if (bp.sourcePackage.equals(pkg.packageName)
17052                            && (bp.packageSetting instanceof PackageSetting)
17053                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17054                                    scanFlags))) {
17055                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17056                    } else {
17057                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17058                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17059                    }
17060                    if (!sigsOk) {
17061                        // If the owning package is the system itself, we log but allow
17062                        // install to proceed; we fail the install on all other permission
17063                        // redefinitions.
17064                        if (!bp.sourcePackage.equals("android")) {
17065                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17066                                    + pkg.packageName + " attempting to redeclare permission "
17067                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17068                            res.origPermission = perm.info.name;
17069                            res.origPackage = bp.sourcePackage;
17070                            return;
17071                        } else {
17072                            Slog.w(TAG, "Package " + pkg.packageName
17073                                    + " attempting to redeclare system permission "
17074                                    + perm.info.name + "; ignoring new declaration");
17075                            pkg.permissions.remove(i);
17076                        }
17077                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17078                        // Prevent apps to change protection level to dangerous from any other
17079                        // type as this would allow a privilege escalation where an app adds a
17080                        // normal/signature permission in other app's group and later redefines
17081                        // it as dangerous leading to the group auto-grant.
17082                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17083                                == PermissionInfo.PROTECTION_DANGEROUS) {
17084                            if (bp != null && !bp.isRuntime()) {
17085                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17086                                        + "non-runtime permission " + perm.info.name
17087                                        + " to runtime; keeping old protection level");
17088                                perm.info.protectionLevel = bp.protectionLevel;
17089                            }
17090                        }
17091                    }
17092                }
17093            }
17094        }
17095
17096        if (systemApp) {
17097            if (onExternal) {
17098                // Abort update; system app can't be replaced with app on sdcard
17099                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17100                        "Cannot install updates to system apps on sdcard");
17101                return;
17102            } else if (instantApp) {
17103                // Abort update; system app can't be replaced with an instant app
17104                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17105                        "Cannot update a system app with an instant app");
17106                return;
17107            }
17108        }
17109
17110        if (args.move != null) {
17111            // We did an in-place move, so dex is ready to roll
17112            scanFlags |= SCAN_NO_DEX;
17113            scanFlags |= SCAN_MOVE;
17114
17115            synchronized (mPackages) {
17116                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17117                if (ps == null) {
17118                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17119                            "Missing settings for moved package " + pkgName);
17120                }
17121
17122                // We moved the entire application as-is, so bring over the
17123                // previously derived ABI information.
17124                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17125                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17126            }
17127
17128        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17129            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17130            scanFlags |= SCAN_NO_DEX;
17131
17132            try {
17133                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17134                    args.abiOverride : pkg.cpuAbiOverride);
17135                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17136                        true /*extractLibs*/, mAppLib32InstallDir);
17137            } catch (PackageManagerException pme) {
17138                Slog.e(TAG, "Error deriving application ABI", pme);
17139                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17140                return;
17141            }
17142
17143            // Shared libraries for the package need to be updated.
17144            synchronized (mPackages) {
17145                try {
17146                    updateSharedLibrariesLPr(pkg, null);
17147                } catch (PackageManagerException e) {
17148                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17149                }
17150            }
17151
17152            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17153            // Do not run PackageDexOptimizer through the local performDexOpt
17154            // method because `pkg` may not be in `mPackages` yet.
17155            //
17156            // Also, don't fail application installs if the dexopt step fails.
17157            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17158                    null /* instructionSets */, false /* checkProfiles */,
17159                    getCompilerFilterForReason(REASON_INSTALL),
17160                    getOrCreateCompilerPackageStats(pkg),
17161                    mDexManager.isUsedByOtherApps(pkg.packageName));
17162            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17163
17164            // Notify BackgroundDexOptService that the package has been changed.
17165            // If this is an update of a package which used to fail to compile,
17166            // BDOS will remove it from its blacklist.
17167            // TODO: Layering violation
17168            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17169        }
17170
17171        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17172            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17173            return;
17174        }
17175
17176        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17177
17178        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17179                "installPackageLI")) {
17180            if (replace) {
17181                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17182                    // Static libs have a synthetic package name containing the version
17183                    // and cannot be updated as an update would get a new package name,
17184                    // unless this is the exact same version code which is useful for
17185                    // development.
17186                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17187                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17188                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17189                                + "static-shared libs cannot be updated");
17190                        return;
17191                    }
17192                }
17193                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17194                        installerPackageName, res, args.installReason);
17195            } else {
17196                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17197                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17198            }
17199        }
17200
17201        synchronized (mPackages) {
17202            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17203            if (ps != null) {
17204                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17205                ps.setUpdateAvailable(false /*updateAvailable*/);
17206            }
17207
17208            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17209            for (int i = 0; i < childCount; i++) {
17210                PackageParser.Package childPkg = pkg.childPackages.get(i);
17211                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17212                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17213                if (childPs != null) {
17214                    childRes.newUsers = childPs.queryInstalledUsers(
17215                            sUserManager.getUserIds(), true);
17216                }
17217            }
17218
17219            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17220                updateSequenceNumberLP(pkgName, res.newUsers);
17221                updateInstantAppInstallerLocked(pkgName);
17222            }
17223        }
17224    }
17225
17226    private void startIntentFilterVerifications(int userId, boolean replacing,
17227            PackageParser.Package pkg) {
17228        if (mIntentFilterVerifierComponent == null) {
17229            Slog.w(TAG, "No IntentFilter verification will not be done as "
17230                    + "there is no IntentFilterVerifier available!");
17231            return;
17232        }
17233
17234        final int verifierUid = getPackageUid(
17235                mIntentFilterVerifierComponent.getPackageName(),
17236                MATCH_DEBUG_TRIAGED_MISSING,
17237                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17238
17239        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17240        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17241        mHandler.sendMessage(msg);
17242
17243        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17244        for (int i = 0; i < childCount; i++) {
17245            PackageParser.Package childPkg = pkg.childPackages.get(i);
17246            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17247            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17248            mHandler.sendMessage(msg);
17249        }
17250    }
17251
17252    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17253            PackageParser.Package pkg) {
17254        int size = pkg.activities.size();
17255        if (size == 0) {
17256            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17257                    "No activity, so no need to verify any IntentFilter!");
17258            return;
17259        }
17260
17261        final boolean hasDomainURLs = hasDomainURLs(pkg);
17262        if (!hasDomainURLs) {
17263            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17264                    "No domain URLs, so no need to verify any IntentFilter!");
17265            return;
17266        }
17267
17268        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17269                + " if any IntentFilter from the " + size
17270                + " Activities needs verification ...");
17271
17272        int count = 0;
17273        final String packageName = pkg.packageName;
17274
17275        synchronized (mPackages) {
17276            // If this is a new install and we see that we've already run verification for this
17277            // package, we have nothing to do: it means the state was restored from backup.
17278            if (!replacing) {
17279                IntentFilterVerificationInfo ivi =
17280                        mSettings.getIntentFilterVerificationLPr(packageName);
17281                if (ivi != null) {
17282                    if (DEBUG_DOMAIN_VERIFICATION) {
17283                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17284                                + ivi.getStatusString());
17285                    }
17286                    return;
17287                }
17288            }
17289
17290            // If any filters need to be verified, then all need to be.
17291            boolean needToVerify = false;
17292            for (PackageParser.Activity a : pkg.activities) {
17293                for (ActivityIntentInfo filter : a.intents) {
17294                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17295                        if (DEBUG_DOMAIN_VERIFICATION) {
17296                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17297                        }
17298                        needToVerify = true;
17299                        break;
17300                    }
17301                }
17302            }
17303
17304            if (needToVerify) {
17305                final int verificationId = mIntentFilterVerificationToken++;
17306                for (PackageParser.Activity a : pkg.activities) {
17307                    for (ActivityIntentInfo filter : a.intents) {
17308                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17309                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17310                                    "Verification needed for IntentFilter:" + filter.toString());
17311                            mIntentFilterVerifier.addOneIntentFilterVerification(
17312                                    verifierUid, userId, verificationId, filter, packageName);
17313                            count++;
17314                        }
17315                    }
17316                }
17317            }
17318        }
17319
17320        if (count > 0) {
17321            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17322                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17323                    +  " for userId:" + userId);
17324            mIntentFilterVerifier.startVerifications(userId);
17325        } else {
17326            if (DEBUG_DOMAIN_VERIFICATION) {
17327                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17328            }
17329        }
17330    }
17331
17332    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17333        final ComponentName cn  = filter.activity.getComponentName();
17334        final String packageName = cn.getPackageName();
17335
17336        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17337                packageName);
17338        if (ivi == null) {
17339            return true;
17340        }
17341        int status = ivi.getStatus();
17342        switch (status) {
17343            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17344            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17345                return true;
17346
17347            default:
17348                // Nothing to do
17349                return false;
17350        }
17351    }
17352
17353    private static boolean isMultiArch(ApplicationInfo info) {
17354        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17355    }
17356
17357    private static boolean isExternal(PackageParser.Package pkg) {
17358        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17359    }
17360
17361    private static boolean isExternal(PackageSetting ps) {
17362        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17363    }
17364
17365    private static boolean isSystemApp(PackageParser.Package pkg) {
17366        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17367    }
17368
17369    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17370        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17371    }
17372
17373    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17374        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17375    }
17376
17377    private static boolean isSystemApp(PackageSetting ps) {
17378        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17379    }
17380
17381    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17382        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17383    }
17384
17385    private int packageFlagsToInstallFlags(PackageSetting ps) {
17386        int installFlags = 0;
17387        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17388            // This existing package was an external ASEC install when we have
17389            // the external flag without a UUID
17390            installFlags |= PackageManager.INSTALL_EXTERNAL;
17391        }
17392        if (ps.isForwardLocked()) {
17393            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17394        }
17395        return installFlags;
17396    }
17397
17398    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17399        if (isExternal(pkg)) {
17400            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17401                return StorageManager.UUID_PRIMARY_PHYSICAL;
17402            } else {
17403                return pkg.volumeUuid;
17404            }
17405        } else {
17406            return StorageManager.UUID_PRIVATE_INTERNAL;
17407        }
17408    }
17409
17410    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17411        if (isExternal(pkg)) {
17412            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17413                return mSettings.getExternalVersion();
17414            } else {
17415                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17416            }
17417        } else {
17418            return mSettings.getInternalVersion();
17419        }
17420    }
17421
17422    private void deleteTempPackageFiles() {
17423        final FilenameFilter filter = new FilenameFilter() {
17424            public boolean accept(File dir, String name) {
17425                return name.startsWith("vmdl") && name.endsWith(".tmp");
17426            }
17427        };
17428        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17429            file.delete();
17430        }
17431    }
17432
17433    @Override
17434    public void deletePackageAsUser(String packageName, int versionCode,
17435            IPackageDeleteObserver observer, int userId, int flags) {
17436        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17437                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17438    }
17439
17440    @Override
17441    public void deletePackageVersioned(VersionedPackage versionedPackage,
17442            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17443        mContext.enforceCallingOrSelfPermission(
17444                android.Manifest.permission.DELETE_PACKAGES, null);
17445        Preconditions.checkNotNull(versionedPackage);
17446        Preconditions.checkNotNull(observer);
17447        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17448                PackageManager.VERSION_CODE_HIGHEST,
17449                Integer.MAX_VALUE, "versionCode must be >= -1");
17450
17451        final String packageName = versionedPackage.getPackageName();
17452        // TODO: We will change version code to long, so in the new API it is long
17453        final int versionCode = (int) versionedPackage.getVersionCode();
17454        final String internalPackageName;
17455        synchronized (mPackages) {
17456            // Normalize package name to handle renamed packages and static libs
17457            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17458                    // TODO: We will change version code to long, so in the new API it is long
17459                    (int) versionedPackage.getVersionCode());
17460        }
17461
17462        final int uid = Binder.getCallingUid();
17463        if (!isOrphaned(internalPackageName)
17464                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17465            try {
17466                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17467                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17468                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17469                observer.onUserActionRequired(intent);
17470            } catch (RemoteException re) {
17471            }
17472            return;
17473        }
17474        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17475        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17476        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17477            mContext.enforceCallingOrSelfPermission(
17478                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17479                    "deletePackage for user " + userId);
17480        }
17481
17482        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17483            try {
17484                observer.onPackageDeleted(packageName,
17485                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17486            } catch (RemoteException re) {
17487            }
17488            return;
17489        }
17490
17491        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17492            try {
17493                observer.onPackageDeleted(packageName,
17494                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17495            } catch (RemoteException re) {
17496            }
17497            return;
17498        }
17499
17500        if (DEBUG_REMOVE) {
17501            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17502                    + " deleteAllUsers: " + deleteAllUsers + " version="
17503                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17504                    ? "VERSION_CODE_HIGHEST" : versionCode));
17505        }
17506        // Queue up an async operation since the package deletion may take a little while.
17507        mHandler.post(new Runnable() {
17508            public void run() {
17509                mHandler.removeCallbacks(this);
17510                int returnCode;
17511                if (!deleteAllUsers) {
17512                    returnCode = deletePackageX(internalPackageName, versionCode,
17513                            userId, deleteFlags);
17514                } else {
17515                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17516                            internalPackageName, users);
17517                    // If nobody is blocking uninstall, proceed with delete for all users
17518                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17519                        returnCode = deletePackageX(internalPackageName, versionCode,
17520                                userId, deleteFlags);
17521                    } else {
17522                        // Otherwise uninstall individually for users with blockUninstalls=false
17523                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17524                        for (int userId : users) {
17525                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17526                                returnCode = deletePackageX(internalPackageName, versionCode,
17527                                        userId, userFlags);
17528                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17529                                    Slog.w(TAG, "Package delete failed for user " + userId
17530                                            + ", returnCode " + returnCode);
17531                                }
17532                            }
17533                        }
17534                        // The app has only been marked uninstalled for certain users.
17535                        // We still need to report that delete was blocked
17536                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17537                    }
17538                }
17539                try {
17540                    observer.onPackageDeleted(packageName, returnCode, null);
17541                } catch (RemoteException e) {
17542                    Log.i(TAG, "Observer no longer exists.");
17543                } //end catch
17544            } //end run
17545        });
17546    }
17547
17548    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17549        if (pkg.staticSharedLibName != null) {
17550            return pkg.manifestPackageName;
17551        }
17552        return pkg.packageName;
17553    }
17554
17555    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17556        // Handle renamed packages
17557        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17558        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17559
17560        // Is this a static library?
17561        SparseArray<SharedLibraryEntry> versionedLib =
17562                mStaticLibsByDeclaringPackage.get(packageName);
17563        if (versionedLib == null || versionedLib.size() <= 0) {
17564            return packageName;
17565        }
17566
17567        // Figure out which lib versions the caller can see
17568        SparseIntArray versionsCallerCanSee = null;
17569        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17570        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17571                && callingAppId != Process.ROOT_UID) {
17572            versionsCallerCanSee = new SparseIntArray();
17573            String libName = versionedLib.valueAt(0).info.getName();
17574            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17575            if (uidPackages != null) {
17576                for (String uidPackage : uidPackages) {
17577                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17578                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17579                    if (libIdx >= 0) {
17580                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17581                        versionsCallerCanSee.append(libVersion, libVersion);
17582                    }
17583                }
17584            }
17585        }
17586
17587        // Caller can see nothing - done
17588        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17589            return packageName;
17590        }
17591
17592        // Find the version the caller can see and the app version code
17593        SharedLibraryEntry highestVersion = null;
17594        final int versionCount = versionedLib.size();
17595        for (int i = 0; i < versionCount; i++) {
17596            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17597            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17598                    // TODO: Remove cast for lib version once internally we support longs.
17599                    (int) libEntry.info.getVersion()) < 0) {
17600                continue;
17601            }
17602            // TODO: We will change version code to long, so in the new API it is long
17603            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17604            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17605                if (libVersionCode == versionCode) {
17606                    return libEntry.apk;
17607                }
17608            } else if (highestVersion == null) {
17609                highestVersion = libEntry;
17610            } else if (libVersionCode  > highestVersion.info
17611                    .getDeclaringPackage().getVersionCode()) {
17612                highestVersion = libEntry;
17613            }
17614        }
17615
17616        if (highestVersion != null) {
17617            return highestVersion.apk;
17618        }
17619
17620        return packageName;
17621    }
17622
17623    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17624        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17625              || callingUid == Process.SYSTEM_UID) {
17626            return true;
17627        }
17628        final int callingUserId = UserHandle.getUserId(callingUid);
17629        // If the caller installed the pkgName, then allow it to silently uninstall.
17630        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17631            return true;
17632        }
17633
17634        // Allow package verifier to silently uninstall.
17635        if (mRequiredVerifierPackage != null &&
17636                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17637            return true;
17638        }
17639
17640        // Allow package uninstaller to silently uninstall.
17641        if (mRequiredUninstallerPackage != null &&
17642                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17643            return true;
17644        }
17645
17646        // Allow storage manager to silently uninstall.
17647        if (mStorageManagerPackage != null &&
17648                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17649            return true;
17650        }
17651        return false;
17652    }
17653
17654    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17655        int[] result = EMPTY_INT_ARRAY;
17656        for (int userId : userIds) {
17657            if (getBlockUninstallForUser(packageName, userId)) {
17658                result = ArrayUtils.appendInt(result, userId);
17659            }
17660        }
17661        return result;
17662    }
17663
17664    @Override
17665    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17666        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17667    }
17668
17669    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17670        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17671                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17672        try {
17673            if (dpm != null) {
17674                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17675                        /* callingUserOnly =*/ false);
17676                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17677                        : deviceOwnerComponentName.getPackageName();
17678                // Does the package contains the device owner?
17679                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17680                // this check is probably not needed, since DO should be registered as a device
17681                // admin on some user too. (Original bug for this: b/17657954)
17682                if (packageName.equals(deviceOwnerPackageName)) {
17683                    return true;
17684                }
17685                // Does it contain a device admin for any user?
17686                int[] users;
17687                if (userId == UserHandle.USER_ALL) {
17688                    users = sUserManager.getUserIds();
17689                } else {
17690                    users = new int[]{userId};
17691                }
17692                for (int i = 0; i < users.length; ++i) {
17693                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17694                        return true;
17695                    }
17696                }
17697            }
17698        } catch (RemoteException e) {
17699        }
17700        return false;
17701    }
17702
17703    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17704        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17705    }
17706
17707    /**
17708     *  This method is an internal method that could be get invoked either
17709     *  to delete an installed package or to clean up a failed installation.
17710     *  After deleting an installed package, a broadcast is sent to notify any
17711     *  listeners that the package has been removed. For cleaning up a failed
17712     *  installation, the broadcast is not necessary since the package's
17713     *  installation wouldn't have sent the initial broadcast either
17714     *  The key steps in deleting a package are
17715     *  deleting the package information in internal structures like mPackages,
17716     *  deleting the packages base directories through installd
17717     *  updating mSettings to reflect current status
17718     *  persisting settings for later use
17719     *  sending a broadcast if necessary
17720     */
17721    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17722        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17723        final boolean res;
17724
17725        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17726                ? UserHandle.USER_ALL : userId;
17727
17728        if (isPackageDeviceAdmin(packageName, removeUser)) {
17729            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17730            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17731        }
17732
17733        PackageSetting uninstalledPs = null;
17734        PackageParser.Package pkg = null;
17735
17736        // for the uninstall-updates case and restricted profiles, remember the per-
17737        // user handle installed state
17738        int[] allUsers;
17739        synchronized (mPackages) {
17740            uninstalledPs = mSettings.mPackages.get(packageName);
17741            if (uninstalledPs == null) {
17742                Slog.w(TAG, "Not removing non-existent package " + packageName);
17743                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17744            }
17745
17746            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17747                    && uninstalledPs.versionCode != versionCode) {
17748                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17749                        + uninstalledPs.versionCode + " != " + versionCode);
17750                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17751            }
17752
17753            // Static shared libs can be declared by any package, so let us not
17754            // allow removing a package if it provides a lib others depend on.
17755            pkg = mPackages.get(packageName);
17756            if (pkg != null && pkg.staticSharedLibName != null) {
17757                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17758                        pkg.staticSharedLibVersion);
17759                if (libEntry != null) {
17760                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17761                            libEntry.info, 0, userId);
17762                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17763                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17764                                + " hosting lib " + libEntry.info.getName() + " version "
17765                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17766                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17767                    }
17768                }
17769            }
17770
17771            allUsers = sUserManager.getUserIds();
17772            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17773        }
17774
17775        final int freezeUser;
17776        if (isUpdatedSystemApp(uninstalledPs)
17777                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17778            // We're downgrading a system app, which will apply to all users, so
17779            // freeze them all during the downgrade
17780            freezeUser = UserHandle.USER_ALL;
17781        } else {
17782            freezeUser = removeUser;
17783        }
17784
17785        synchronized (mInstallLock) {
17786            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17787            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17788                    deleteFlags, "deletePackageX")) {
17789                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17790                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17791            }
17792            synchronized (mPackages) {
17793                if (res) {
17794                    if (pkg != null) {
17795                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17796                    }
17797                    updateSequenceNumberLP(packageName, info.removedUsers);
17798                    updateInstantAppInstallerLocked(packageName);
17799                }
17800            }
17801        }
17802
17803        if (res) {
17804            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17805            info.sendPackageRemovedBroadcasts(killApp);
17806            info.sendSystemPackageUpdatedBroadcasts();
17807            info.sendSystemPackageAppearedBroadcasts();
17808        }
17809        // Force a gc here.
17810        Runtime.getRuntime().gc();
17811        // Delete the resources here after sending the broadcast to let
17812        // other processes clean up before deleting resources.
17813        if (info.args != null) {
17814            synchronized (mInstallLock) {
17815                info.args.doPostDeleteLI(true);
17816            }
17817        }
17818
17819        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17820    }
17821
17822    static class PackageRemovedInfo {
17823        final PackageSender packageSender;
17824        String removedPackage;
17825        int uid = -1;
17826        int removedAppId = -1;
17827        int[] origUsers;
17828        int[] removedUsers = null;
17829        int[] broadcastUsers = null;
17830        SparseArray<Integer> installReasons;
17831        boolean isRemovedPackageSystemUpdate = false;
17832        boolean isUpdate;
17833        boolean dataRemoved;
17834        boolean removedForAllUsers;
17835        boolean isStaticSharedLib;
17836        // Clean up resources deleted packages.
17837        InstallArgs args = null;
17838        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17839        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17840
17841        PackageRemovedInfo(PackageSender packageSender) {
17842            this.packageSender = packageSender;
17843        }
17844
17845        void sendPackageRemovedBroadcasts(boolean killApp) {
17846            sendPackageRemovedBroadcastInternal(killApp);
17847            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17848            for (int i = 0; i < childCount; i++) {
17849                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17850                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17851            }
17852        }
17853
17854        void sendSystemPackageUpdatedBroadcasts() {
17855            if (isRemovedPackageSystemUpdate) {
17856                sendSystemPackageUpdatedBroadcastsInternal();
17857                final int childCount = (removedChildPackages != null)
17858                        ? removedChildPackages.size() : 0;
17859                for (int i = 0; i < childCount; i++) {
17860                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17861                    if (childInfo.isRemovedPackageSystemUpdate) {
17862                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17863                    }
17864                }
17865            }
17866        }
17867
17868        void sendSystemPackageAppearedBroadcasts() {
17869            final int packageCount = (appearedChildPackages != null)
17870                    ? appearedChildPackages.size() : 0;
17871            for (int i = 0; i < packageCount; i++) {
17872                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17873                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17874                    true, UserHandle.getAppId(installedInfo.uid),
17875                    installedInfo.newUsers);
17876            }
17877        }
17878
17879        private void sendSystemPackageUpdatedBroadcastsInternal() {
17880            Bundle extras = new Bundle(2);
17881            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17882            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17883            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17884                removedPackage, extras, 0, null, null, null);
17885            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17886                removedPackage, extras, 0, null, null, null);
17887            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17888                null, null, 0, removedPackage, null, null);
17889        }
17890
17891        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17892            // Don't send static shared library removal broadcasts as these
17893            // libs are visible only the the apps that depend on them an one
17894            // cannot remove the library if it has a dependency.
17895            if (isStaticSharedLib) {
17896                return;
17897            }
17898            Bundle extras = new Bundle(2);
17899            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17900            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17901            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17902            if (isUpdate || isRemovedPackageSystemUpdate) {
17903                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17904            }
17905            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17906            if (removedPackage != null) {
17907                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17908                    removedPackage, extras, 0, null, null, broadcastUsers);
17909                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17910                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17911                        removedPackage, extras,
17912                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17913                        null, null, broadcastUsers);
17914                }
17915            }
17916            if (removedAppId >= 0) {
17917                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
17918                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
17919            }
17920        }
17921
17922        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17923            removedUsers = userIds;
17924            if (removedUsers == null) {
17925                broadcastUsers = null;
17926                return;
17927            }
17928
17929            broadcastUsers = EMPTY_INT_ARRAY;
17930            for (int i = userIds.length - 1; i >= 0; --i) {
17931                final int userId = userIds[i];
17932                if (deletedPackageSetting.getInstantApp(userId)) {
17933                    continue;
17934                }
17935                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17936            }
17937        }
17938    }
17939
17940    /*
17941     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17942     * flag is not set, the data directory is removed as well.
17943     * make sure this flag is set for partially installed apps. If not its meaningless to
17944     * delete a partially installed application.
17945     */
17946    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17947            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17948        String packageName = ps.name;
17949        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17950        // Retrieve object to delete permissions for shared user later on
17951        final PackageParser.Package deletedPkg;
17952        final PackageSetting deletedPs;
17953        // reader
17954        synchronized (mPackages) {
17955            deletedPkg = mPackages.get(packageName);
17956            deletedPs = mSettings.mPackages.get(packageName);
17957            if (outInfo != null) {
17958                outInfo.removedPackage = packageName;
17959                outInfo.isStaticSharedLib = deletedPkg != null
17960                        && deletedPkg.staticSharedLibName != null;
17961                outInfo.populateUsers(deletedPs == null ? null
17962                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17963            }
17964        }
17965
17966        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17967
17968        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17969            final PackageParser.Package resolvedPkg;
17970            if (deletedPkg != null) {
17971                resolvedPkg = deletedPkg;
17972            } else {
17973                // We don't have a parsed package when it lives on an ejected
17974                // adopted storage device, so fake something together
17975                resolvedPkg = new PackageParser.Package(ps.name);
17976                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17977            }
17978            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17979                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17980            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17981            if (outInfo != null) {
17982                outInfo.dataRemoved = true;
17983            }
17984            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17985        }
17986
17987        int removedAppId = -1;
17988
17989        // writer
17990        synchronized (mPackages) {
17991            boolean installedStateChanged = false;
17992            if (deletedPs != null) {
17993                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17994                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17995                    clearDefaultBrowserIfNeeded(packageName);
17996                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17997                    removedAppId = mSettings.removePackageLPw(packageName);
17998                    if (outInfo != null) {
17999                        outInfo.removedAppId = removedAppId;
18000                    }
18001                    updatePermissionsLPw(deletedPs.name, null, 0);
18002                    if (deletedPs.sharedUser != null) {
18003                        // Remove permissions associated with package. Since runtime
18004                        // permissions are per user we have to kill the removed package
18005                        // or packages running under the shared user of the removed
18006                        // package if revoking the permissions requested only by the removed
18007                        // package is successful and this causes a change in gids.
18008                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18009                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18010                                    userId);
18011                            if (userIdToKill == UserHandle.USER_ALL
18012                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18013                                // If gids changed for this user, kill all affected packages.
18014                                mHandler.post(new Runnable() {
18015                                    @Override
18016                                    public void run() {
18017                                        // This has to happen with no lock held.
18018                                        killApplication(deletedPs.name, deletedPs.appId,
18019                                                KILL_APP_REASON_GIDS_CHANGED);
18020                                    }
18021                                });
18022                                break;
18023                            }
18024                        }
18025                    }
18026                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18027                }
18028                // make sure to preserve per-user disabled state if this removal was just
18029                // a downgrade of a system app to the factory package
18030                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18031                    if (DEBUG_REMOVE) {
18032                        Slog.d(TAG, "Propagating install state across downgrade");
18033                    }
18034                    for (int userId : allUserHandles) {
18035                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18036                        if (DEBUG_REMOVE) {
18037                            Slog.d(TAG, "    user " + userId + " => " + installed);
18038                        }
18039                        if (installed != ps.getInstalled(userId)) {
18040                            installedStateChanged = true;
18041                        }
18042                        ps.setInstalled(installed, userId);
18043                    }
18044                }
18045            }
18046            // can downgrade to reader
18047            if (writeSettings) {
18048                // Save settings now
18049                mSettings.writeLPr();
18050            }
18051            if (installedStateChanged) {
18052                mSettings.writeKernelMappingLPr(ps);
18053            }
18054        }
18055        if (removedAppId != -1) {
18056            // A user ID was deleted here. Go through all users and remove it
18057            // from KeyStore.
18058            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18059        }
18060    }
18061
18062    static boolean locationIsPrivileged(File path) {
18063        try {
18064            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18065                    .getCanonicalPath();
18066            return path.getCanonicalPath().startsWith(privilegedAppDir);
18067        } catch (IOException e) {
18068            Slog.e(TAG, "Unable to access code path " + path);
18069        }
18070        return false;
18071    }
18072
18073    /*
18074     * Tries to delete system package.
18075     */
18076    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18077            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18078            boolean writeSettings) {
18079        if (deletedPs.parentPackageName != null) {
18080            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18081            return false;
18082        }
18083
18084        final boolean applyUserRestrictions
18085                = (allUserHandles != null) && (outInfo.origUsers != null);
18086        final PackageSetting disabledPs;
18087        // Confirm if the system package has been updated
18088        // An updated system app can be deleted. This will also have to restore
18089        // the system pkg from system partition
18090        // reader
18091        synchronized (mPackages) {
18092            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18093        }
18094
18095        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18096                + " disabledPs=" + disabledPs);
18097
18098        if (disabledPs == null) {
18099            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18100            return false;
18101        } else if (DEBUG_REMOVE) {
18102            Slog.d(TAG, "Deleting system pkg from data partition");
18103        }
18104
18105        if (DEBUG_REMOVE) {
18106            if (applyUserRestrictions) {
18107                Slog.d(TAG, "Remembering install states:");
18108                for (int userId : allUserHandles) {
18109                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18110                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18111                }
18112            }
18113        }
18114
18115        // Delete the updated package
18116        outInfo.isRemovedPackageSystemUpdate = true;
18117        if (outInfo.removedChildPackages != null) {
18118            final int childCount = (deletedPs.childPackageNames != null)
18119                    ? deletedPs.childPackageNames.size() : 0;
18120            for (int i = 0; i < childCount; i++) {
18121                String childPackageName = deletedPs.childPackageNames.get(i);
18122                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18123                        .contains(childPackageName)) {
18124                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18125                            childPackageName);
18126                    if (childInfo != null) {
18127                        childInfo.isRemovedPackageSystemUpdate = true;
18128                    }
18129                }
18130            }
18131        }
18132
18133        if (disabledPs.versionCode < deletedPs.versionCode) {
18134            // Delete data for downgrades
18135            flags &= ~PackageManager.DELETE_KEEP_DATA;
18136        } else {
18137            // Preserve data by setting flag
18138            flags |= PackageManager.DELETE_KEEP_DATA;
18139        }
18140
18141        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18142                outInfo, writeSettings, disabledPs.pkg);
18143        if (!ret) {
18144            return false;
18145        }
18146
18147        // writer
18148        synchronized (mPackages) {
18149            // Reinstate the old system package
18150            enableSystemPackageLPw(disabledPs.pkg);
18151            // Remove any native libraries from the upgraded package.
18152            removeNativeBinariesLI(deletedPs);
18153        }
18154
18155        // Install the system package
18156        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18157        int parseFlags = mDefParseFlags
18158                | PackageParser.PARSE_MUST_BE_APK
18159                | PackageParser.PARSE_IS_SYSTEM
18160                | PackageParser.PARSE_IS_SYSTEM_DIR;
18161        if (locationIsPrivileged(disabledPs.codePath)) {
18162            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18163        }
18164
18165        final PackageParser.Package newPkg;
18166        try {
18167            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18168                0 /* currentTime */, null);
18169        } catch (PackageManagerException e) {
18170            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18171                    + e.getMessage());
18172            return false;
18173        }
18174
18175        try {
18176            // update shared libraries for the newly re-installed system package
18177            updateSharedLibrariesLPr(newPkg, null);
18178        } catch (PackageManagerException e) {
18179            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18180        }
18181
18182        prepareAppDataAfterInstallLIF(newPkg);
18183
18184        // writer
18185        synchronized (mPackages) {
18186            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18187
18188            // Propagate the permissions state as we do not want to drop on the floor
18189            // runtime permissions. The update permissions method below will take
18190            // care of removing obsolete permissions and grant install permissions.
18191            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18192            updatePermissionsLPw(newPkg.packageName, newPkg,
18193                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18194
18195            if (applyUserRestrictions) {
18196                boolean installedStateChanged = false;
18197                if (DEBUG_REMOVE) {
18198                    Slog.d(TAG, "Propagating install state across reinstall");
18199                }
18200                for (int userId : allUserHandles) {
18201                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18202                    if (DEBUG_REMOVE) {
18203                        Slog.d(TAG, "    user " + userId + " => " + installed);
18204                    }
18205                    if (installed != ps.getInstalled(userId)) {
18206                        installedStateChanged = true;
18207                    }
18208                    ps.setInstalled(installed, userId);
18209
18210                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18211                }
18212                // Regardless of writeSettings we need to ensure that this restriction
18213                // state propagation is persisted
18214                mSettings.writeAllUsersPackageRestrictionsLPr();
18215                if (installedStateChanged) {
18216                    mSettings.writeKernelMappingLPr(ps);
18217                }
18218            }
18219            // can downgrade to reader here
18220            if (writeSettings) {
18221                mSettings.writeLPr();
18222            }
18223        }
18224        return true;
18225    }
18226
18227    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18228            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18229            PackageRemovedInfo outInfo, boolean writeSettings,
18230            PackageParser.Package replacingPackage) {
18231        synchronized (mPackages) {
18232            if (outInfo != null) {
18233                outInfo.uid = ps.appId;
18234            }
18235
18236            if (outInfo != null && outInfo.removedChildPackages != null) {
18237                final int childCount = (ps.childPackageNames != null)
18238                        ? ps.childPackageNames.size() : 0;
18239                for (int i = 0; i < childCount; i++) {
18240                    String childPackageName = ps.childPackageNames.get(i);
18241                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18242                    if (childPs == null) {
18243                        return false;
18244                    }
18245                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18246                            childPackageName);
18247                    if (childInfo != null) {
18248                        childInfo.uid = childPs.appId;
18249                    }
18250                }
18251            }
18252        }
18253
18254        // Delete package data from internal structures and also remove data if flag is set
18255        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18256
18257        // Delete the child packages data
18258        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18259        for (int i = 0; i < childCount; i++) {
18260            PackageSetting childPs;
18261            synchronized (mPackages) {
18262                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18263            }
18264            if (childPs != null) {
18265                PackageRemovedInfo childOutInfo = (outInfo != null
18266                        && outInfo.removedChildPackages != null)
18267                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18268                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18269                        && (replacingPackage != null
18270                        && !replacingPackage.hasChildPackage(childPs.name))
18271                        ? flags & ~DELETE_KEEP_DATA : flags;
18272                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18273                        deleteFlags, writeSettings);
18274            }
18275        }
18276
18277        // Delete application code and resources only for parent packages
18278        if (ps.parentPackageName == null) {
18279            if (deleteCodeAndResources && (outInfo != null)) {
18280                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18281                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18282                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18283            }
18284        }
18285
18286        return true;
18287    }
18288
18289    @Override
18290    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18291            int userId) {
18292        mContext.enforceCallingOrSelfPermission(
18293                android.Manifest.permission.DELETE_PACKAGES, null);
18294        synchronized (mPackages) {
18295            PackageSetting ps = mSettings.mPackages.get(packageName);
18296            if (ps == null) {
18297                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18298                return false;
18299            }
18300            // Cannot block uninstall of static shared libs as they are
18301            // considered a part of the using app (emulating static linking).
18302            // Also static libs are installed always on internal storage.
18303            PackageParser.Package pkg = mPackages.get(packageName);
18304            if (pkg != null && pkg.staticSharedLibName != null) {
18305                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18306                        + " providing static shared library: " + pkg.staticSharedLibName);
18307                return false;
18308            }
18309            if (!ps.getInstalled(userId)) {
18310                // Can't block uninstall for an app that is not installed or enabled.
18311                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18312                return false;
18313            }
18314            ps.setBlockUninstall(blockUninstall, userId);
18315            mSettings.writePackageRestrictionsLPr(userId);
18316        }
18317        return true;
18318    }
18319
18320    @Override
18321    public boolean getBlockUninstallForUser(String packageName, int userId) {
18322        synchronized (mPackages) {
18323            PackageSetting ps = mSettings.mPackages.get(packageName);
18324            if (ps == null) {
18325                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18326                return false;
18327            }
18328            return ps.getBlockUninstall(userId);
18329        }
18330    }
18331
18332    @Override
18333    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18334        int callingUid = Binder.getCallingUid();
18335        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18336            throw new SecurityException(
18337                    "setRequiredForSystemUser can only be run by the system or root");
18338        }
18339        synchronized (mPackages) {
18340            PackageSetting ps = mSettings.mPackages.get(packageName);
18341            if (ps == null) {
18342                Log.w(TAG, "Package doesn't exist: " + packageName);
18343                return false;
18344            }
18345            if (systemUserApp) {
18346                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18347            } else {
18348                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18349            }
18350            mSettings.writeLPr();
18351        }
18352        return true;
18353    }
18354
18355    /*
18356     * This method handles package deletion in general
18357     */
18358    private boolean deletePackageLIF(String packageName, UserHandle user,
18359            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18360            PackageRemovedInfo outInfo, boolean writeSettings,
18361            PackageParser.Package replacingPackage) {
18362        if (packageName == null) {
18363            Slog.w(TAG, "Attempt to delete null packageName.");
18364            return false;
18365        }
18366
18367        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18368
18369        PackageSetting ps;
18370        synchronized (mPackages) {
18371            ps = mSettings.mPackages.get(packageName);
18372            if (ps == null) {
18373                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18374                return false;
18375            }
18376
18377            if (ps.parentPackageName != null && (!isSystemApp(ps)
18378                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18379                if (DEBUG_REMOVE) {
18380                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18381                            + ((user == null) ? UserHandle.USER_ALL : user));
18382                }
18383                final int removedUserId = (user != null) ? user.getIdentifier()
18384                        : UserHandle.USER_ALL;
18385                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18386                    return false;
18387                }
18388                markPackageUninstalledForUserLPw(ps, user);
18389                scheduleWritePackageRestrictionsLocked(user);
18390                return true;
18391            }
18392        }
18393
18394        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18395                && user.getIdentifier() != UserHandle.USER_ALL)) {
18396            // The caller is asking that the package only be deleted for a single
18397            // user.  To do this, we just mark its uninstalled state and delete
18398            // its data. If this is a system app, we only allow this to happen if
18399            // they have set the special DELETE_SYSTEM_APP which requests different
18400            // semantics than normal for uninstalling system apps.
18401            markPackageUninstalledForUserLPw(ps, user);
18402
18403            if (!isSystemApp(ps)) {
18404                // Do not uninstall the APK if an app should be cached
18405                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18406                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18407                    // Other user still have this package installed, so all
18408                    // we need to do is clear this user's data and save that
18409                    // it is uninstalled.
18410                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18411                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18412                        return false;
18413                    }
18414                    scheduleWritePackageRestrictionsLocked(user);
18415                    return true;
18416                } else {
18417                    // We need to set it back to 'installed' so the uninstall
18418                    // broadcasts will be sent correctly.
18419                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18420                    ps.setInstalled(true, user.getIdentifier());
18421                    mSettings.writeKernelMappingLPr(ps);
18422                }
18423            } else {
18424                // This is a system app, so we assume that the
18425                // other users still have this package installed, so all
18426                // we need to do is clear this user's data and save that
18427                // it is uninstalled.
18428                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18429                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18430                    return false;
18431                }
18432                scheduleWritePackageRestrictionsLocked(user);
18433                return true;
18434            }
18435        }
18436
18437        // If we are deleting a composite package for all users, keep track
18438        // of result for each child.
18439        if (ps.childPackageNames != null && outInfo != null) {
18440            synchronized (mPackages) {
18441                final int childCount = ps.childPackageNames.size();
18442                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18443                for (int i = 0; i < childCount; i++) {
18444                    String childPackageName = ps.childPackageNames.get(i);
18445                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18446                    childInfo.removedPackage = childPackageName;
18447                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18448                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18449                    if (childPs != null) {
18450                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18451                    }
18452                }
18453            }
18454        }
18455
18456        boolean ret = false;
18457        if (isSystemApp(ps)) {
18458            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18459            // When an updated system application is deleted we delete the existing resources
18460            // as well and fall back to existing code in system partition
18461            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18462        } else {
18463            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18464            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18465                    outInfo, writeSettings, replacingPackage);
18466        }
18467
18468        // Take a note whether we deleted the package for all users
18469        if (outInfo != null) {
18470            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18471            if (outInfo.removedChildPackages != null) {
18472                synchronized (mPackages) {
18473                    final int childCount = outInfo.removedChildPackages.size();
18474                    for (int i = 0; i < childCount; i++) {
18475                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18476                        if (childInfo != null) {
18477                            childInfo.removedForAllUsers = mPackages.get(
18478                                    childInfo.removedPackage) == null;
18479                        }
18480                    }
18481                }
18482            }
18483            // If we uninstalled an update to a system app there may be some
18484            // child packages that appeared as they are declared in the system
18485            // app but were not declared in the update.
18486            if (isSystemApp(ps)) {
18487                synchronized (mPackages) {
18488                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18489                    final int childCount = (updatedPs.childPackageNames != null)
18490                            ? updatedPs.childPackageNames.size() : 0;
18491                    for (int i = 0; i < childCount; i++) {
18492                        String childPackageName = updatedPs.childPackageNames.get(i);
18493                        if (outInfo.removedChildPackages == null
18494                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18495                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18496                            if (childPs == null) {
18497                                continue;
18498                            }
18499                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18500                            installRes.name = childPackageName;
18501                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18502                            installRes.pkg = mPackages.get(childPackageName);
18503                            installRes.uid = childPs.pkg.applicationInfo.uid;
18504                            if (outInfo.appearedChildPackages == null) {
18505                                outInfo.appearedChildPackages = new ArrayMap<>();
18506                            }
18507                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18508                        }
18509                    }
18510                }
18511            }
18512        }
18513
18514        return ret;
18515    }
18516
18517    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18518        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18519                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18520        for (int nextUserId : userIds) {
18521            if (DEBUG_REMOVE) {
18522                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18523            }
18524            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18525                    false /*installed*/,
18526                    true /*stopped*/,
18527                    true /*notLaunched*/,
18528                    false /*hidden*/,
18529                    false /*suspended*/,
18530                    false /*instantApp*/,
18531                    null /*lastDisableAppCaller*/,
18532                    null /*enabledComponents*/,
18533                    null /*disabledComponents*/,
18534                    false /*blockUninstall*/,
18535                    ps.readUserState(nextUserId).domainVerificationStatus,
18536                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18537        }
18538        mSettings.writeKernelMappingLPr(ps);
18539    }
18540
18541    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18542            PackageRemovedInfo outInfo) {
18543        final PackageParser.Package pkg;
18544        synchronized (mPackages) {
18545            pkg = mPackages.get(ps.name);
18546        }
18547
18548        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18549                : new int[] {userId};
18550        for (int nextUserId : userIds) {
18551            if (DEBUG_REMOVE) {
18552                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18553                        + nextUserId);
18554            }
18555
18556            destroyAppDataLIF(pkg, userId,
18557                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18558            destroyAppProfilesLIF(pkg, userId);
18559            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18560            schedulePackageCleaning(ps.name, nextUserId, false);
18561            synchronized (mPackages) {
18562                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18563                    scheduleWritePackageRestrictionsLocked(nextUserId);
18564                }
18565                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18566            }
18567        }
18568
18569        if (outInfo != null) {
18570            outInfo.removedPackage = ps.name;
18571            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18572            outInfo.removedAppId = ps.appId;
18573            outInfo.removedUsers = userIds;
18574            outInfo.broadcastUsers = userIds;
18575        }
18576
18577        return true;
18578    }
18579
18580    private final class ClearStorageConnection implements ServiceConnection {
18581        IMediaContainerService mContainerService;
18582
18583        @Override
18584        public void onServiceConnected(ComponentName name, IBinder service) {
18585            synchronized (this) {
18586                mContainerService = IMediaContainerService.Stub
18587                        .asInterface(Binder.allowBlocking(service));
18588                notifyAll();
18589            }
18590        }
18591
18592        @Override
18593        public void onServiceDisconnected(ComponentName name) {
18594        }
18595    }
18596
18597    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18598        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18599
18600        final boolean mounted;
18601        if (Environment.isExternalStorageEmulated()) {
18602            mounted = true;
18603        } else {
18604            final String status = Environment.getExternalStorageState();
18605
18606            mounted = status.equals(Environment.MEDIA_MOUNTED)
18607                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18608        }
18609
18610        if (!mounted) {
18611            return;
18612        }
18613
18614        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18615        int[] users;
18616        if (userId == UserHandle.USER_ALL) {
18617            users = sUserManager.getUserIds();
18618        } else {
18619            users = new int[] { userId };
18620        }
18621        final ClearStorageConnection conn = new ClearStorageConnection();
18622        if (mContext.bindServiceAsUser(
18623                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18624            try {
18625                for (int curUser : users) {
18626                    long timeout = SystemClock.uptimeMillis() + 5000;
18627                    synchronized (conn) {
18628                        long now;
18629                        while (conn.mContainerService == null &&
18630                                (now = SystemClock.uptimeMillis()) < timeout) {
18631                            try {
18632                                conn.wait(timeout - now);
18633                            } catch (InterruptedException e) {
18634                            }
18635                        }
18636                    }
18637                    if (conn.mContainerService == null) {
18638                        return;
18639                    }
18640
18641                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18642                    clearDirectory(conn.mContainerService,
18643                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18644                    if (allData) {
18645                        clearDirectory(conn.mContainerService,
18646                                userEnv.buildExternalStorageAppDataDirs(packageName));
18647                        clearDirectory(conn.mContainerService,
18648                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18649                    }
18650                }
18651            } finally {
18652                mContext.unbindService(conn);
18653            }
18654        }
18655    }
18656
18657    @Override
18658    public void clearApplicationProfileData(String packageName) {
18659        enforceSystemOrRoot("Only the system can clear all profile data");
18660
18661        final PackageParser.Package pkg;
18662        synchronized (mPackages) {
18663            pkg = mPackages.get(packageName);
18664        }
18665
18666        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18667            synchronized (mInstallLock) {
18668                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18669            }
18670        }
18671    }
18672
18673    @Override
18674    public void clearApplicationUserData(final String packageName,
18675            final IPackageDataObserver observer, final int userId) {
18676        mContext.enforceCallingOrSelfPermission(
18677                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18678
18679        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18680                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18681
18682        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18683            throw new SecurityException("Cannot clear data for a protected package: "
18684                    + packageName);
18685        }
18686        // Queue up an async operation since the package deletion may take a little while.
18687        mHandler.post(new Runnable() {
18688            public void run() {
18689                mHandler.removeCallbacks(this);
18690                final boolean succeeded;
18691                try (PackageFreezer freezer = freezePackage(packageName,
18692                        "clearApplicationUserData")) {
18693                    synchronized (mInstallLock) {
18694                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18695                    }
18696                    clearExternalStorageDataSync(packageName, userId, true);
18697                    synchronized (mPackages) {
18698                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18699                                packageName, userId);
18700                    }
18701                }
18702                if (succeeded) {
18703                    // invoke DeviceStorageMonitor's update method to clear any notifications
18704                    DeviceStorageMonitorInternal dsm = LocalServices
18705                            .getService(DeviceStorageMonitorInternal.class);
18706                    if (dsm != null) {
18707                        dsm.checkMemory();
18708                    }
18709                }
18710                if(observer != null) {
18711                    try {
18712                        observer.onRemoveCompleted(packageName, succeeded);
18713                    } catch (RemoteException e) {
18714                        Log.i(TAG, "Observer no longer exists.");
18715                    }
18716                } //end if observer
18717            } //end run
18718        });
18719    }
18720
18721    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18722        if (packageName == null) {
18723            Slog.w(TAG, "Attempt to delete null packageName.");
18724            return false;
18725        }
18726
18727        // Try finding details about the requested package
18728        PackageParser.Package pkg;
18729        synchronized (mPackages) {
18730            pkg = mPackages.get(packageName);
18731            if (pkg == null) {
18732                final PackageSetting ps = mSettings.mPackages.get(packageName);
18733                if (ps != null) {
18734                    pkg = ps.pkg;
18735                }
18736            }
18737
18738            if (pkg == null) {
18739                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18740                return false;
18741            }
18742
18743            PackageSetting ps = (PackageSetting) pkg.mExtras;
18744            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18745        }
18746
18747        clearAppDataLIF(pkg, userId,
18748                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18749
18750        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18751        removeKeystoreDataIfNeeded(userId, appId);
18752
18753        UserManagerInternal umInternal = getUserManagerInternal();
18754        final int flags;
18755        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18756            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18757        } else if (umInternal.isUserRunning(userId)) {
18758            flags = StorageManager.FLAG_STORAGE_DE;
18759        } else {
18760            flags = 0;
18761        }
18762        prepareAppDataContentsLIF(pkg, userId, flags);
18763
18764        return true;
18765    }
18766
18767    /**
18768     * Reverts user permission state changes (permissions and flags) in
18769     * all packages for a given user.
18770     *
18771     * @param userId The device user for which to do a reset.
18772     */
18773    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18774        final int packageCount = mPackages.size();
18775        for (int i = 0; i < packageCount; i++) {
18776            PackageParser.Package pkg = mPackages.valueAt(i);
18777            PackageSetting ps = (PackageSetting) pkg.mExtras;
18778            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18779        }
18780    }
18781
18782    private void resetNetworkPolicies(int userId) {
18783        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18784    }
18785
18786    /**
18787     * Reverts user permission state changes (permissions and flags).
18788     *
18789     * @param ps The package for which to reset.
18790     * @param userId The device user for which to do a reset.
18791     */
18792    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18793            final PackageSetting ps, final int userId) {
18794        if (ps.pkg == null) {
18795            return;
18796        }
18797
18798        // These are flags that can change base on user actions.
18799        final int userSettableMask = FLAG_PERMISSION_USER_SET
18800                | FLAG_PERMISSION_USER_FIXED
18801                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18802                | FLAG_PERMISSION_REVIEW_REQUIRED;
18803
18804        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18805                | FLAG_PERMISSION_POLICY_FIXED;
18806
18807        boolean writeInstallPermissions = false;
18808        boolean writeRuntimePermissions = false;
18809
18810        final int permissionCount = ps.pkg.requestedPermissions.size();
18811        for (int i = 0; i < permissionCount; i++) {
18812            String permission = ps.pkg.requestedPermissions.get(i);
18813
18814            BasePermission bp = mSettings.mPermissions.get(permission);
18815            if (bp == null) {
18816                continue;
18817            }
18818
18819            // If shared user we just reset the state to which only this app contributed.
18820            if (ps.sharedUser != null) {
18821                boolean used = false;
18822                final int packageCount = ps.sharedUser.packages.size();
18823                for (int j = 0; j < packageCount; j++) {
18824                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18825                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18826                            && pkg.pkg.requestedPermissions.contains(permission)) {
18827                        used = true;
18828                        break;
18829                    }
18830                }
18831                if (used) {
18832                    continue;
18833                }
18834            }
18835
18836            PermissionsState permissionsState = ps.getPermissionsState();
18837
18838            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18839
18840            // Always clear the user settable flags.
18841            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18842                    bp.name) != null;
18843            // If permission review is enabled and this is a legacy app, mark the
18844            // permission as requiring a review as this is the initial state.
18845            int flags = 0;
18846            if (mPermissionReviewRequired
18847                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18848                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18849            }
18850            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18851                if (hasInstallState) {
18852                    writeInstallPermissions = true;
18853                } else {
18854                    writeRuntimePermissions = true;
18855                }
18856            }
18857
18858            // Below is only runtime permission handling.
18859            if (!bp.isRuntime()) {
18860                continue;
18861            }
18862
18863            // Never clobber system or policy.
18864            if ((oldFlags & policyOrSystemFlags) != 0) {
18865                continue;
18866            }
18867
18868            // If this permission was granted by default, make sure it is.
18869            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18870                if (permissionsState.grantRuntimePermission(bp, userId)
18871                        != PERMISSION_OPERATION_FAILURE) {
18872                    writeRuntimePermissions = true;
18873                }
18874            // If permission review is enabled the permissions for a legacy apps
18875            // are represented as constantly granted runtime ones, so don't revoke.
18876            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18877                // Otherwise, reset the permission.
18878                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18879                switch (revokeResult) {
18880                    case PERMISSION_OPERATION_SUCCESS:
18881                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18882                        writeRuntimePermissions = true;
18883                        final int appId = ps.appId;
18884                        mHandler.post(new Runnable() {
18885                            @Override
18886                            public void run() {
18887                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18888                            }
18889                        });
18890                    } break;
18891                }
18892            }
18893        }
18894
18895        // Synchronously write as we are taking permissions away.
18896        if (writeRuntimePermissions) {
18897            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18898        }
18899
18900        // Synchronously write as we are taking permissions away.
18901        if (writeInstallPermissions) {
18902            mSettings.writeLPr();
18903        }
18904    }
18905
18906    /**
18907     * Remove entries from the keystore daemon. Will only remove it if the
18908     * {@code appId} is valid.
18909     */
18910    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18911        if (appId < 0) {
18912            return;
18913        }
18914
18915        final KeyStore keyStore = KeyStore.getInstance();
18916        if (keyStore != null) {
18917            if (userId == UserHandle.USER_ALL) {
18918                for (final int individual : sUserManager.getUserIds()) {
18919                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18920                }
18921            } else {
18922                keyStore.clearUid(UserHandle.getUid(userId, appId));
18923            }
18924        } else {
18925            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18926        }
18927    }
18928
18929    @Override
18930    public void deleteApplicationCacheFiles(final String packageName,
18931            final IPackageDataObserver observer) {
18932        final int userId = UserHandle.getCallingUserId();
18933        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18934    }
18935
18936    @Override
18937    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18938            final IPackageDataObserver observer) {
18939        mContext.enforceCallingOrSelfPermission(
18940                android.Manifest.permission.DELETE_CACHE_FILES, null);
18941        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18942                /* requireFullPermission= */ true, /* checkShell= */ false,
18943                "delete application cache files");
18944
18945        final PackageParser.Package pkg;
18946        synchronized (mPackages) {
18947            pkg = mPackages.get(packageName);
18948        }
18949
18950        // Queue up an async operation since the package deletion may take a little while.
18951        mHandler.post(new Runnable() {
18952            public void run() {
18953                synchronized (mInstallLock) {
18954                    final int flags = StorageManager.FLAG_STORAGE_DE
18955                            | StorageManager.FLAG_STORAGE_CE;
18956                    // We're only clearing cache files, so we don't care if the
18957                    // app is unfrozen and still able to run
18958                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18959                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18960                }
18961                clearExternalStorageDataSync(packageName, userId, false);
18962                if (observer != null) {
18963                    try {
18964                        observer.onRemoveCompleted(packageName, true);
18965                    } catch (RemoteException e) {
18966                        Log.i(TAG, "Observer no longer exists.");
18967                    }
18968                }
18969            }
18970        });
18971    }
18972
18973    @Override
18974    public void getPackageSizeInfo(final String packageName, int userHandle,
18975            final IPackageStatsObserver observer) {
18976        throw new UnsupportedOperationException(
18977                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18978    }
18979
18980    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18981        final PackageSetting ps;
18982        synchronized (mPackages) {
18983            ps = mSettings.mPackages.get(packageName);
18984            if (ps == null) {
18985                Slog.w(TAG, "Failed to find settings for " + packageName);
18986                return false;
18987            }
18988        }
18989
18990        final String[] packageNames = { packageName };
18991        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18992        final String[] codePaths = { ps.codePathString };
18993
18994        try {
18995            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18996                    ps.appId, ceDataInodes, codePaths, stats);
18997
18998            // For now, ignore code size of packages on system partition
18999            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19000                stats.codeSize = 0;
19001            }
19002
19003            // External clients expect these to be tracked separately
19004            stats.dataSize -= stats.cacheSize;
19005
19006        } catch (InstallerException e) {
19007            Slog.w(TAG, String.valueOf(e));
19008            return false;
19009        }
19010
19011        return true;
19012    }
19013
19014    private int getUidTargetSdkVersionLockedLPr(int uid) {
19015        Object obj = mSettings.getUserIdLPr(uid);
19016        if (obj instanceof SharedUserSetting) {
19017            final SharedUserSetting sus = (SharedUserSetting) obj;
19018            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19019            final Iterator<PackageSetting> it = sus.packages.iterator();
19020            while (it.hasNext()) {
19021                final PackageSetting ps = it.next();
19022                if (ps.pkg != null) {
19023                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19024                    if (v < vers) vers = v;
19025                }
19026            }
19027            return vers;
19028        } else if (obj instanceof PackageSetting) {
19029            final PackageSetting ps = (PackageSetting) obj;
19030            if (ps.pkg != null) {
19031                return ps.pkg.applicationInfo.targetSdkVersion;
19032            }
19033        }
19034        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19035    }
19036
19037    @Override
19038    public void addPreferredActivity(IntentFilter filter, int match,
19039            ComponentName[] set, ComponentName activity, int userId) {
19040        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19041                "Adding preferred");
19042    }
19043
19044    private void addPreferredActivityInternal(IntentFilter filter, int match,
19045            ComponentName[] set, ComponentName activity, boolean always, int userId,
19046            String opname) {
19047        // writer
19048        int callingUid = Binder.getCallingUid();
19049        enforceCrossUserPermission(callingUid, userId,
19050                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19051        if (filter.countActions() == 0) {
19052            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19053            return;
19054        }
19055        synchronized (mPackages) {
19056            if (mContext.checkCallingOrSelfPermission(
19057                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19058                    != PackageManager.PERMISSION_GRANTED) {
19059                if (getUidTargetSdkVersionLockedLPr(callingUid)
19060                        < Build.VERSION_CODES.FROYO) {
19061                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19062                            + callingUid);
19063                    return;
19064                }
19065                mContext.enforceCallingOrSelfPermission(
19066                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19067            }
19068
19069            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19070            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19071                    + userId + ":");
19072            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19073            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19074            scheduleWritePackageRestrictionsLocked(userId);
19075            postPreferredActivityChangedBroadcast(userId);
19076        }
19077    }
19078
19079    private void postPreferredActivityChangedBroadcast(int userId) {
19080        mHandler.post(() -> {
19081            final IActivityManager am = ActivityManager.getService();
19082            if (am == null) {
19083                return;
19084            }
19085
19086            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19087            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19088            try {
19089                am.broadcastIntent(null, intent, null, null,
19090                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19091                        null, false, false, userId);
19092            } catch (RemoteException e) {
19093            }
19094        });
19095    }
19096
19097    @Override
19098    public void replacePreferredActivity(IntentFilter filter, int match,
19099            ComponentName[] set, ComponentName activity, int userId) {
19100        if (filter.countActions() != 1) {
19101            throw new IllegalArgumentException(
19102                    "replacePreferredActivity expects filter to have only 1 action.");
19103        }
19104        if (filter.countDataAuthorities() != 0
19105                || filter.countDataPaths() != 0
19106                || filter.countDataSchemes() > 1
19107                || filter.countDataTypes() != 0) {
19108            throw new IllegalArgumentException(
19109                    "replacePreferredActivity expects filter to have no data authorities, " +
19110                    "paths, or types; and at most one scheme.");
19111        }
19112
19113        final int callingUid = Binder.getCallingUid();
19114        enforceCrossUserPermission(callingUid, userId,
19115                true /* requireFullPermission */, false /* checkShell */,
19116                "replace preferred activity");
19117        synchronized (mPackages) {
19118            if (mContext.checkCallingOrSelfPermission(
19119                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19120                    != PackageManager.PERMISSION_GRANTED) {
19121                if (getUidTargetSdkVersionLockedLPr(callingUid)
19122                        < Build.VERSION_CODES.FROYO) {
19123                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19124                            + Binder.getCallingUid());
19125                    return;
19126                }
19127                mContext.enforceCallingOrSelfPermission(
19128                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19129            }
19130
19131            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19132            if (pir != null) {
19133                // Get all of the existing entries that exactly match this filter.
19134                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19135                if (existing != null && existing.size() == 1) {
19136                    PreferredActivity cur = existing.get(0);
19137                    if (DEBUG_PREFERRED) {
19138                        Slog.i(TAG, "Checking replace of preferred:");
19139                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19140                        if (!cur.mPref.mAlways) {
19141                            Slog.i(TAG, "  -- CUR; not mAlways!");
19142                        } else {
19143                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19144                            Slog.i(TAG, "  -- CUR: mSet="
19145                                    + Arrays.toString(cur.mPref.mSetComponents));
19146                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19147                            Slog.i(TAG, "  -- NEW: mMatch="
19148                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19149                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19150                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19151                        }
19152                    }
19153                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19154                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19155                            && cur.mPref.sameSet(set)) {
19156                        // Setting the preferred activity to what it happens to be already
19157                        if (DEBUG_PREFERRED) {
19158                            Slog.i(TAG, "Replacing with same preferred activity "
19159                                    + cur.mPref.mShortComponent + " for user "
19160                                    + userId + ":");
19161                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19162                        }
19163                        return;
19164                    }
19165                }
19166
19167                if (existing != null) {
19168                    if (DEBUG_PREFERRED) {
19169                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19170                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19171                    }
19172                    for (int i = 0; i < existing.size(); i++) {
19173                        PreferredActivity pa = existing.get(i);
19174                        if (DEBUG_PREFERRED) {
19175                            Slog.i(TAG, "Removing existing preferred activity "
19176                                    + pa.mPref.mComponent + ":");
19177                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19178                        }
19179                        pir.removeFilter(pa);
19180                    }
19181                }
19182            }
19183            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19184                    "Replacing preferred");
19185        }
19186    }
19187
19188    @Override
19189    public void clearPackagePreferredActivities(String packageName) {
19190        final int uid = Binder.getCallingUid();
19191        // writer
19192        synchronized (mPackages) {
19193            PackageParser.Package pkg = mPackages.get(packageName);
19194            if (pkg == null || pkg.applicationInfo.uid != uid) {
19195                if (mContext.checkCallingOrSelfPermission(
19196                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19197                        != PackageManager.PERMISSION_GRANTED) {
19198                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
19199                            < Build.VERSION_CODES.FROYO) {
19200                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19201                                + Binder.getCallingUid());
19202                        return;
19203                    }
19204                    mContext.enforceCallingOrSelfPermission(
19205                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19206                }
19207            }
19208
19209            int user = UserHandle.getCallingUserId();
19210            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19211                scheduleWritePackageRestrictionsLocked(user);
19212            }
19213        }
19214    }
19215
19216    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19217    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19218        ArrayList<PreferredActivity> removed = null;
19219        boolean changed = false;
19220        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19221            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19222            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19223            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19224                continue;
19225            }
19226            Iterator<PreferredActivity> it = pir.filterIterator();
19227            while (it.hasNext()) {
19228                PreferredActivity pa = it.next();
19229                // Mark entry for removal only if it matches the package name
19230                // and the entry is of type "always".
19231                if (packageName == null ||
19232                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19233                                && pa.mPref.mAlways)) {
19234                    if (removed == null) {
19235                        removed = new ArrayList<PreferredActivity>();
19236                    }
19237                    removed.add(pa);
19238                }
19239            }
19240            if (removed != null) {
19241                for (int j=0; j<removed.size(); j++) {
19242                    PreferredActivity pa = removed.get(j);
19243                    pir.removeFilter(pa);
19244                }
19245                changed = true;
19246            }
19247        }
19248        if (changed) {
19249            postPreferredActivityChangedBroadcast(userId);
19250        }
19251        return changed;
19252    }
19253
19254    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19255    private void clearIntentFilterVerificationsLPw(int userId) {
19256        final int packageCount = mPackages.size();
19257        for (int i = 0; i < packageCount; i++) {
19258            PackageParser.Package pkg = mPackages.valueAt(i);
19259            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19260        }
19261    }
19262
19263    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19264    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19265        if (userId == UserHandle.USER_ALL) {
19266            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19267                    sUserManager.getUserIds())) {
19268                for (int oneUserId : sUserManager.getUserIds()) {
19269                    scheduleWritePackageRestrictionsLocked(oneUserId);
19270                }
19271            }
19272        } else {
19273            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19274                scheduleWritePackageRestrictionsLocked(userId);
19275            }
19276        }
19277    }
19278
19279    void clearDefaultBrowserIfNeeded(String packageName) {
19280        for (int oneUserId : sUserManager.getUserIds()) {
19281            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19282            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19283            if (packageName.equals(defaultBrowserPackageName)) {
19284                setDefaultBrowserPackageName(null, oneUserId);
19285            }
19286        }
19287    }
19288
19289    @Override
19290    public void resetApplicationPreferences(int userId) {
19291        mContext.enforceCallingOrSelfPermission(
19292                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19293        final long identity = Binder.clearCallingIdentity();
19294        // writer
19295        try {
19296            synchronized (mPackages) {
19297                clearPackagePreferredActivitiesLPw(null, userId);
19298                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19299                // TODO: We have to reset the default SMS and Phone. This requires
19300                // significant refactoring to keep all default apps in the package
19301                // manager (cleaner but more work) or have the services provide
19302                // callbacks to the package manager to request a default app reset.
19303                applyFactoryDefaultBrowserLPw(userId);
19304                clearIntentFilterVerificationsLPw(userId);
19305                primeDomainVerificationsLPw(userId);
19306                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19307                scheduleWritePackageRestrictionsLocked(userId);
19308            }
19309            resetNetworkPolicies(userId);
19310        } finally {
19311            Binder.restoreCallingIdentity(identity);
19312        }
19313    }
19314
19315    @Override
19316    public int getPreferredActivities(List<IntentFilter> outFilters,
19317            List<ComponentName> outActivities, String packageName) {
19318
19319        int num = 0;
19320        final int userId = UserHandle.getCallingUserId();
19321        // reader
19322        synchronized (mPackages) {
19323            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19324            if (pir != null) {
19325                final Iterator<PreferredActivity> it = pir.filterIterator();
19326                while (it.hasNext()) {
19327                    final PreferredActivity pa = it.next();
19328                    if (packageName == null
19329                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19330                                    && pa.mPref.mAlways)) {
19331                        if (outFilters != null) {
19332                            outFilters.add(new IntentFilter(pa));
19333                        }
19334                        if (outActivities != null) {
19335                            outActivities.add(pa.mPref.mComponent);
19336                        }
19337                    }
19338                }
19339            }
19340        }
19341
19342        return num;
19343    }
19344
19345    @Override
19346    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19347            int userId) {
19348        int callingUid = Binder.getCallingUid();
19349        if (callingUid != Process.SYSTEM_UID) {
19350            throw new SecurityException(
19351                    "addPersistentPreferredActivity can only be run by the system");
19352        }
19353        if (filter.countActions() == 0) {
19354            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19355            return;
19356        }
19357        synchronized (mPackages) {
19358            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19359                    ":");
19360            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19361            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19362                    new PersistentPreferredActivity(filter, activity));
19363            scheduleWritePackageRestrictionsLocked(userId);
19364            postPreferredActivityChangedBroadcast(userId);
19365        }
19366    }
19367
19368    @Override
19369    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19370        int callingUid = Binder.getCallingUid();
19371        if (callingUid != Process.SYSTEM_UID) {
19372            throw new SecurityException(
19373                    "clearPackagePersistentPreferredActivities can only be run by the system");
19374        }
19375        ArrayList<PersistentPreferredActivity> removed = null;
19376        boolean changed = false;
19377        synchronized (mPackages) {
19378            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19379                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19380                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19381                        .valueAt(i);
19382                if (userId != thisUserId) {
19383                    continue;
19384                }
19385                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19386                while (it.hasNext()) {
19387                    PersistentPreferredActivity ppa = it.next();
19388                    // Mark entry for removal only if it matches the package name.
19389                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19390                        if (removed == null) {
19391                            removed = new ArrayList<PersistentPreferredActivity>();
19392                        }
19393                        removed.add(ppa);
19394                    }
19395                }
19396                if (removed != null) {
19397                    for (int j=0; j<removed.size(); j++) {
19398                        PersistentPreferredActivity ppa = removed.get(j);
19399                        ppir.removeFilter(ppa);
19400                    }
19401                    changed = true;
19402                }
19403            }
19404
19405            if (changed) {
19406                scheduleWritePackageRestrictionsLocked(userId);
19407                postPreferredActivityChangedBroadcast(userId);
19408            }
19409        }
19410    }
19411
19412    /**
19413     * Common machinery for picking apart a restored XML blob and passing
19414     * it to a caller-supplied functor to be applied to the running system.
19415     */
19416    private void restoreFromXml(XmlPullParser parser, int userId,
19417            String expectedStartTag, BlobXmlRestorer functor)
19418            throws IOException, XmlPullParserException {
19419        int type;
19420        while ((type = parser.next()) != XmlPullParser.START_TAG
19421                && type != XmlPullParser.END_DOCUMENT) {
19422        }
19423        if (type != XmlPullParser.START_TAG) {
19424            // oops didn't find a start tag?!
19425            if (DEBUG_BACKUP) {
19426                Slog.e(TAG, "Didn't find start tag during restore");
19427            }
19428            return;
19429        }
19430Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19431        // this is supposed to be TAG_PREFERRED_BACKUP
19432        if (!expectedStartTag.equals(parser.getName())) {
19433            if (DEBUG_BACKUP) {
19434                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19435            }
19436            return;
19437        }
19438
19439        // skip interfering stuff, then we're aligned with the backing implementation
19440        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19441Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19442        functor.apply(parser, userId);
19443    }
19444
19445    private interface BlobXmlRestorer {
19446        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19447    }
19448
19449    /**
19450     * Non-Binder method, support for the backup/restore mechanism: write the
19451     * full set of preferred activities in its canonical XML format.  Returns the
19452     * XML output as a byte array, or null if there is none.
19453     */
19454    @Override
19455    public byte[] getPreferredActivityBackup(int userId) {
19456        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19457            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19458        }
19459
19460        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19461        try {
19462            final XmlSerializer serializer = new FastXmlSerializer();
19463            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19464            serializer.startDocument(null, true);
19465            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19466
19467            synchronized (mPackages) {
19468                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19469            }
19470
19471            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19472            serializer.endDocument();
19473            serializer.flush();
19474        } catch (Exception e) {
19475            if (DEBUG_BACKUP) {
19476                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19477            }
19478            return null;
19479        }
19480
19481        return dataStream.toByteArray();
19482    }
19483
19484    @Override
19485    public void restorePreferredActivities(byte[] backup, int userId) {
19486        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19487            throw new SecurityException("Only the system may call restorePreferredActivities()");
19488        }
19489
19490        try {
19491            final XmlPullParser parser = Xml.newPullParser();
19492            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19493            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19494                    new BlobXmlRestorer() {
19495                        @Override
19496                        public void apply(XmlPullParser parser, int userId)
19497                                throws XmlPullParserException, IOException {
19498                            synchronized (mPackages) {
19499                                mSettings.readPreferredActivitiesLPw(parser, userId);
19500                            }
19501                        }
19502                    } );
19503        } catch (Exception e) {
19504            if (DEBUG_BACKUP) {
19505                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19506            }
19507        }
19508    }
19509
19510    /**
19511     * Non-Binder method, support for the backup/restore mechanism: write the
19512     * default browser (etc) settings in its canonical XML format.  Returns the default
19513     * browser XML representation as a byte array, or null if there is none.
19514     */
19515    @Override
19516    public byte[] getDefaultAppsBackup(int userId) {
19517        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19518            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19519        }
19520
19521        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19522        try {
19523            final XmlSerializer serializer = new FastXmlSerializer();
19524            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19525            serializer.startDocument(null, true);
19526            serializer.startTag(null, TAG_DEFAULT_APPS);
19527
19528            synchronized (mPackages) {
19529                mSettings.writeDefaultAppsLPr(serializer, userId);
19530            }
19531
19532            serializer.endTag(null, TAG_DEFAULT_APPS);
19533            serializer.endDocument();
19534            serializer.flush();
19535        } catch (Exception e) {
19536            if (DEBUG_BACKUP) {
19537                Slog.e(TAG, "Unable to write default apps for backup", e);
19538            }
19539            return null;
19540        }
19541
19542        return dataStream.toByteArray();
19543    }
19544
19545    @Override
19546    public void restoreDefaultApps(byte[] backup, int userId) {
19547        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19548            throw new SecurityException("Only the system may call restoreDefaultApps()");
19549        }
19550
19551        try {
19552            final XmlPullParser parser = Xml.newPullParser();
19553            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19554            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19555                    new BlobXmlRestorer() {
19556                        @Override
19557                        public void apply(XmlPullParser parser, int userId)
19558                                throws XmlPullParserException, IOException {
19559                            synchronized (mPackages) {
19560                                mSettings.readDefaultAppsLPw(parser, userId);
19561                            }
19562                        }
19563                    } );
19564        } catch (Exception e) {
19565            if (DEBUG_BACKUP) {
19566                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19567            }
19568        }
19569    }
19570
19571    @Override
19572    public byte[] getIntentFilterVerificationBackup(int userId) {
19573        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19574            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19575        }
19576
19577        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19578        try {
19579            final XmlSerializer serializer = new FastXmlSerializer();
19580            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19581            serializer.startDocument(null, true);
19582            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19583
19584            synchronized (mPackages) {
19585                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19586            }
19587
19588            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19589            serializer.endDocument();
19590            serializer.flush();
19591        } catch (Exception e) {
19592            if (DEBUG_BACKUP) {
19593                Slog.e(TAG, "Unable to write default apps for backup", e);
19594            }
19595            return null;
19596        }
19597
19598        return dataStream.toByteArray();
19599    }
19600
19601    @Override
19602    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19603        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19604            throw new SecurityException("Only the system may call restorePreferredActivities()");
19605        }
19606
19607        try {
19608            final XmlPullParser parser = Xml.newPullParser();
19609            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19610            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19611                    new BlobXmlRestorer() {
19612                        @Override
19613                        public void apply(XmlPullParser parser, int userId)
19614                                throws XmlPullParserException, IOException {
19615                            synchronized (mPackages) {
19616                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19617                                mSettings.writeLPr();
19618                            }
19619                        }
19620                    } );
19621        } catch (Exception e) {
19622            if (DEBUG_BACKUP) {
19623                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19624            }
19625        }
19626    }
19627
19628    @Override
19629    public byte[] getPermissionGrantBackup(int userId) {
19630        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19631            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19632        }
19633
19634        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19635        try {
19636            final XmlSerializer serializer = new FastXmlSerializer();
19637            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19638            serializer.startDocument(null, true);
19639            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19640
19641            synchronized (mPackages) {
19642                serializeRuntimePermissionGrantsLPr(serializer, userId);
19643            }
19644
19645            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19646            serializer.endDocument();
19647            serializer.flush();
19648        } catch (Exception e) {
19649            if (DEBUG_BACKUP) {
19650                Slog.e(TAG, "Unable to write default apps for backup", e);
19651            }
19652            return null;
19653        }
19654
19655        return dataStream.toByteArray();
19656    }
19657
19658    @Override
19659    public void restorePermissionGrants(byte[] backup, int userId) {
19660        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19661            throw new SecurityException("Only the system may call restorePermissionGrants()");
19662        }
19663
19664        try {
19665            final XmlPullParser parser = Xml.newPullParser();
19666            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19667            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19668                    new BlobXmlRestorer() {
19669                        @Override
19670                        public void apply(XmlPullParser parser, int userId)
19671                                throws XmlPullParserException, IOException {
19672                            synchronized (mPackages) {
19673                                processRestoredPermissionGrantsLPr(parser, userId);
19674                            }
19675                        }
19676                    } );
19677        } catch (Exception e) {
19678            if (DEBUG_BACKUP) {
19679                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19680            }
19681        }
19682    }
19683
19684    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19685            throws IOException {
19686        serializer.startTag(null, TAG_ALL_GRANTS);
19687
19688        final int N = mSettings.mPackages.size();
19689        for (int i = 0; i < N; i++) {
19690            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19691            boolean pkgGrantsKnown = false;
19692
19693            PermissionsState packagePerms = ps.getPermissionsState();
19694
19695            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19696                final int grantFlags = state.getFlags();
19697                // only look at grants that are not system/policy fixed
19698                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19699                    final boolean isGranted = state.isGranted();
19700                    // And only back up the user-twiddled state bits
19701                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19702                        final String packageName = mSettings.mPackages.keyAt(i);
19703                        if (!pkgGrantsKnown) {
19704                            serializer.startTag(null, TAG_GRANT);
19705                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19706                            pkgGrantsKnown = true;
19707                        }
19708
19709                        final boolean userSet =
19710                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19711                        final boolean userFixed =
19712                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19713                        final boolean revoke =
19714                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19715
19716                        serializer.startTag(null, TAG_PERMISSION);
19717                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19718                        if (isGranted) {
19719                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19720                        }
19721                        if (userSet) {
19722                            serializer.attribute(null, ATTR_USER_SET, "true");
19723                        }
19724                        if (userFixed) {
19725                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19726                        }
19727                        if (revoke) {
19728                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19729                        }
19730                        serializer.endTag(null, TAG_PERMISSION);
19731                    }
19732                }
19733            }
19734
19735            if (pkgGrantsKnown) {
19736                serializer.endTag(null, TAG_GRANT);
19737            }
19738        }
19739
19740        serializer.endTag(null, TAG_ALL_GRANTS);
19741    }
19742
19743    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19744            throws XmlPullParserException, IOException {
19745        String pkgName = null;
19746        int outerDepth = parser.getDepth();
19747        int type;
19748        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19749                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19750            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19751                continue;
19752            }
19753
19754            final String tagName = parser.getName();
19755            if (tagName.equals(TAG_GRANT)) {
19756                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19757                if (DEBUG_BACKUP) {
19758                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19759                }
19760            } else if (tagName.equals(TAG_PERMISSION)) {
19761
19762                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19763                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19764
19765                int newFlagSet = 0;
19766                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19767                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19768                }
19769                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19770                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19771                }
19772                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19773                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19774                }
19775                if (DEBUG_BACKUP) {
19776                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19777                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19778                }
19779                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19780                if (ps != null) {
19781                    // Already installed so we apply the grant immediately
19782                    if (DEBUG_BACKUP) {
19783                        Slog.v(TAG, "        + already installed; applying");
19784                    }
19785                    PermissionsState perms = ps.getPermissionsState();
19786                    BasePermission bp = mSettings.mPermissions.get(permName);
19787                    if (bp != null) {
19788                        if (isGranted) {
19789                            perms.grantRuntimePermission(bp, userId);
19790                        }
19791                        if (newFlagSet != 0) {
19792                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19793                        }
19794                    }
19795                } else {
19796                    // Need to wait for post-restore install to apply the grant
19797                    if (DEBUG_BACKUP) {
19798                        Slog.v(TAG, "        - not yet installed; saving for later");
19799                    }
19800                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19801                            isGranted, newFlagSet, userId);
19802                }
19803            } else {
19804                PackageManagerService.reportSettingsProblem(Log.WARN,
19805                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19806                XmlUtils.skipCurrentTag(parser);
19807            }
19808        }
19809
19810        scheduleWriteSettingsLocked();
19811        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19812    }
19813
19814    @Override
19815    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19816            int sourceUserId, int targetUserId, int flags) {
19817        mContext.enforceCallingOrSelfPermission(
19818                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19819        int callingUid = Binder.getCallingUid();
19820        enforceOwnerRights(ownerPackage, callingUid);
19821        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19822        if (intentFilter.countActions() == 0) {
19823            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19824            return;
19825        }
19826        synchronized (mPackages) {
19827            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19828                    ownerPackage, targetUserId, flags);
19829            CrossProfileIntentResolver resolver =
19830                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19831            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19832            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19833            if (existing != null) {
19834                int size = existing.size();
19835                for (int i = 0; i < size; i++) {
19836                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19837                        return;
19838                    }
19839                }
19840            }
19841            resolver.addFilter(newFilter);
19842            scheduleWritePackageRestrictionsLocked(sourceUserId);
19843        }
19844    }
19845
19846    @Override
19847    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19848        mContext.enforceCallingOrSelfPermission(
19849                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19850        int callingUid = Binder.getCallingUid();
19851        enforceOwnerRights(ownerPackage, callingUid);
19852        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19853        synchronized (mPackages) {
19854            CrossProfileIntentResolver resolver =
19855                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19856            ArraySet<CrossProfileIntentFilter> set =
19857                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19858            for (CrossProfileIntentFilter filter : set) {
19859                if (filter.getOwnerPackage().equals(ownerPackage)) {
19860                    resolver.removeFilter(filter);
19861                }
19862            }
19863            scheduleWritePackageRestrictionsLocked(sourceUserId);
19864        }
19865    }
19866
19867    // Enforcing that callingUid is owning pkg on userId
19868    private void enforceOwnerRights(String pkg, int callingUid) {
19869        // The system owns everything.
19870        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19871            return;
19872        }
19873        int callingUserId = UserHandle.getUserId(callingUid);
19874        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19875        if (pi == null) {
19876            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19877                    + callingUserId);
19878        }
19879        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19880            throw new SecurityException("Calling uid " + callingUid
19881                    + " does not own package " + pkg);
19882        }
19883    }
19884
19885    @Override
19886    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19887        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19888    }
19889
19890    /**
19891     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19892     * then reports the most likely home activity or null if there are more than one.
19893     */
19894    public ComponentName getDefaultHomeActivity(int userId) {
19895        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19896        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19897        if (cn != null) {
19898            return cn;
19899        }
19900
19901        // Find the launcher with the highest priority and return that component if there are no
19902        // other home activity with the same priority.
19903        int lastPriority = Integer.MIN_VALUE;
19904        ComponentName lastComponent = null;
19905        final int size = allHomeCandidates.size();
19906        for (int i = 0; i < size; i++) {
19907            final ResolveInfo ri = allHomeCandidates.get(i);
19908            if (ri.priority > lastPriority) {
19909                lastComponent = ri.activityInfo.getComponentName();
19910                lastPriority = ri.priority;
19911            } else if (ri.priority == lastPriority) {
19912                // Two components found with same priority.
19913                lastComponent = null;
19914            }
19915        }
19916        return lastComponent;
19917    }
19918
19919    private Intent getHomeIntent() {
19920        Intent intent = new Intent(Intent.ACTION_MAIN);
19921        intent.addCategory(Intent.CATEGORY_HOME);
19922        intent.addCategory(Intent.CATEGORY_DEFAULT);
19923        return intent;
19924    }
19925
19926    private IntentFilter getHomeFilter() {
19927        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19928        filter.addCategory(Intent.CATEGORY_HOME);
19929        filter.addCategory(Intent.CATEGORY_DEFAULT);
19930        return filter;
19931    }
19932
19933    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19934            int userId) {
19935        Intent intent  = getHomeIntent();
19936        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19937                PackageManager.GET_META_DATA, userId);
19938        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19939                true, false, false, userId);
19940
19941        allHomeCandidates.clear();
19942        if (list != null) {
19943            for (ResolveInfo ri : list) {
19944                allHomeCandidates.add(ri);
19945            }
19946        }
19947        return (preferred == null || preferred.activityInfo == null)
19948                ? null
19949                : new ComponentName(preferred.activityInfo.packageName,
19950                        preferred.activityInfo.name);
19951    }
19952
19953    @Override
19954    public void setHomeActivity(ComponentName comp, int userId) {
19955        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19956        getHomeActivitiesAsUser(homeActivities, userId);
19957
19958        boolean found = false;
19959
19960        final int size = homeActivities.size();
19961        final ComponentName[] set = new ComponentName[size];
19962        for (int i = 0; i < size; i++) {
19963            final ResolveInfo candidate = homeActivities.get(i);
19964            final ActivityInfo info = candidate.activityInfo;
19965            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19966            set[i] = activityName;
19967            if (!found && activityName.equals(comp)) {
19968                found = true;
19969            }
19970        }
19971        if (!found) {
19972            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19973                    + userId);
19974        }
19975        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19976                set, comp, userId);
19977    }
19978
19979    private @Nullable String getSetupWizardPackageName() {
19980        final Intent intent = new Intent(Intent.ACTION_MAIN);
19981        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19982
19983        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19984                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19985                        | MATCH_DISABLED_COMPONENTS,
19986                UserHandle.myUserId());
19987        if (matches.size() == 1) {
19988            return matches.get(0).getComponentInfo().packageName;
19989        } else {
19990            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19991                    + ": matches=" + matches);
19992            return null;
19993        }
19994    }
19995
19996    private @Nullable String getStorageManagerPackageName() {
19997        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19998
19999        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20000                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20001                        | MATCH_DISABLED_COMPONENTS,
20002                UserHandle.myUserId());
20003        if (matches.size() == 1) {
20004            return matches.get(0).getComponentInfo().packageName;
20005        } else {
20006            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20007                    + matches.size() + ": matches=" + matches);
20008            return null;
20009        }
20010    }
20011
20012    @Override
20013    public void setApplicationEnabledSetting(String appPackageName,
20014            int newState, int flags, int userId, String callingPackage) {
20015        if (!sUserManager.exists(userId)) return;
20016        if (callingPackage == null) {
20017            callingPackage = Integer.toString(Binder.getCallingUid());
20018        }
20019        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20020    }
20021
20022    @Override
20023    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20024        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20025        synchronized (mPackages) {
20026            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20027            if (pkgSetting != null) {
20028                pkgSetting.setUpdateAvailable(updateAvailable);
20029            }
20030        }
20031    }
20032
20033    @Override
20034    public void setComponentEnabledSetting(ComponentName componentName,
20035            int newState, int flags, int userId) {
20036        if (!sUserManager.exists(userId)) return;
20037        setEnabledSetting(componentName.getPackageName(),
20038                componentName.getClassName(), newState, flags, userId, null);
20039    }
20040
20041    private void setEnabledSetting(final String packageName, String className, int newState,
20042            final int flags, int userId, String callingPackage) {
20043        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20044              || newState == COMPONENT_ENABLED_STATE_ENABLED
20045              || newState == COMPONENT_ENABLED_STATE_DISABLED
20046              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20047              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20048            throw new IllegalArgumentException("Invalid new component state: "
20049                    + newState);
20050        }
20051        PackageSetting pkgSetting;
20052        final int uid = Binder.getCallingUid();
20053        final int permission;
20054        if (uid == Process.SYSTEM_UID) {
20055            permission = PackageManager.PERMISSION_GRANTED;
20056        } else {
20057            permission = mContext.checkCallingOrSelfPermission(
20058                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20059        }
20060        enforceCrossUserPermission(uid, userId,
20061                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20062        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20063        boolean sendNow = false;
20064        boolean isApp = (className == null);
20065        String componentName = isApp ? packageName : className;
20066        int packageUid = -1;
20067        ArrayList<String> components;
20068
20069        // writer
20070        synchronized (mPackages) {
20071            pkgSetting = mSettings.mPackages.get(packageName);
20072            if (pkgSetting == null) {
20073                if (className == null) {
20074                    throw new IllegalArgumentException("Unknown package: " + packageName);
20075                }
20076                throw new IllegalArgumentException(
20077                        "Unknown component: " + packageName + "/" + className);
20078            }
20079        }
20080
20081        // Limit who can change which apps
20082        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
20083            // Don't allow apps that don't have permission to modify other apps
20084            if (!allowedByPermission) {
20085                throw new SecurityException(
20086                        "Permission Denial: attempt to change component state from pid="
20087                        + Binder.getCallingPid()
20088                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
20089            }
20090            // Don't allow changing protected packages.
20091            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20092                throw new SecurityException("Cannot disable a protected package: " + packageName);
20093            }
20094        }
20095
20096        synchronized (mPackages) {
20097            if (uid == Process.SHELL_UID
20098                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20099                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20100                // unless it is a test package.
20101                int oldState = pkgSetting.getEnabled(userId);
20102                if (className == null
20103                    &&
20104                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20105                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20106                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20107                    &&
20108                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20109                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20110                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20111                    // ok
20112                } else {
20113                    throw new SecurityException(
20114                            "Shell cannot change component state for " + packageName + "/"
20115                            + className + " to " + newState);
20116                }
20117            }
20118            if (className == null) {
20119                // We're dealing with an application/package level state change
20120                if (pkgSetting.getEnabled(userId) == newState) {
20121                    // Nothing to do
20122                    return;
20123                }
20124                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20125                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20126                    // Don't care about who enables an app.
20127                    callingPackage = null;
20128                }
20129                pkgSetting.setEnabled(newState, userId, callingPackage);
20130                // pkgSetting.pkg.mSetEnabled = newState;
20131            } else {
20132                // We're dealing with a component level state change
20133                // First, verify that this is a valid class name.
20134                PackageParser.Package pkg = pkgSetting.pkg;
20135                if (pkg == null || !pkg.hasComponentClassName(className)) {
20136                    if (pkg != null &&
20137                            pkg.applicationInfo.targetSdkVersion >=
20138                                    Build.VERSION_CODES.JELLY_BEAN) {
20139                        throw new IllegalArgumentException("Component class " + className
20140                                + " does not exist in " + packageName);
20141                    } else {
20142                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20143                                + className + " does not exist in " + packageName);
20144                    }
20145                }
20146                switch (newState) {
20147                case COMPONENT_ENABLED_STATE_ENABLED:
20148                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20149                        return;
20150                    }
20151                    break;
20152                case COMPONENT_ENABLED_STATE_DISABLED:
20153                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20154                        return;
20155                    }
20156                    break;
20157                case COMPONENT_ENABLED_STATE_DEFAULT:
20158                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20159                        return;
20160                    }
20161                    break;
20162                default:
20163                    Slog.e(TAG, "Invalid new component state: " + newState);
20164                    return;
20165                }
20166            }
20167            scheduleWritePackageRestrictionsLocked(userId);
20168            updateSequenceNumberLP(packageName, new int[] { userId });
20169            final long callingId = Binder.clearCallingIdentity();
20170            try {
20171                updateInstantAppInstallerLocked(packageName);
20172            } finally {
20173                Binder.restoreCallingIdentity(callingId);
20174            }
20175            components = mPendingBroadcasts.get(userId, packageName);
20176            final boolean newPackage = components == null;
20177            if (newPackage) {
20178                components = new ArrayList<String>();
20179            }
20180            if (!components.contains(componentName)) {
20181                components.add(componentName);
20182            }
20183            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20184                sendNow = true;
20185                // Purge entry from pending broadcast list if another one exists already
20186                // since we are sending one right away.
20187                mPendingBroadcasts.remove(userId, packageName);
20188            } else {
20189                if (newPackage) {
20190                    mPendingBroadcasts.put(userId, packageName, components);
20191                }
20192                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20193                    // Schedule a message
20194                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20195                }
20196            }
20197        }
20198
20199        long callingId = Binder.clearCallingIdentity();
20200        try {
20201            if (sendNow) {
20202                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20203                sendPackageChangedBroadcast(packageName,
20204                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20205            }
20206        } finally {
20207            Binder.restoreCallingIdentity(callingId);
20208        }
20209    }
20210
20211    @Override
20212    public void flushPackageRestrictionsAsUser(int userId) {
20213        if (!sUserManager.exists(userId)) {
20214            return;
20215        }
20216        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20217                false /* checkShell */, "flushPackageRestrictions");
20218        synchronized (mPackages) {
20219            mSettings.writePackageRestrictionsLPr(userId);
20220            mDirtyUsers.remove(userId);
20221            if (mDirtyUsers.isEmpty()) {
20222                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20223            }
20224        }
20225    }
20226
20227    private void sendPackageChangedBroadcast(String packageName,
20228            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20229        if (DEBUG_INSTALL)
20230            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20231                    + componentNames);
20232        Bundle extras = new Bundle(4);
20233        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20234        String nameList[] = new String[componentNames.size()];
20235        componentNames.toArray(nameList);
20236        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20237        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20238        extras.putInt(Intent.EXTRA_UID, packageUid);
20239        // If this is not reporting a change of the overall package, then only send it
20240        // to registered receivers.  We don't want to launch a swath of apps for every
20241        // little component state change.
20242        final int flags = !componentNames.contains(packageName)
20243                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20244        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20245                new int[] {UserHandle.getUserId(packageUid)});
20246    }
20247
20248    @Override
20249    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20250        if (!sUserManager.exists(userId)) return;
20251        final int uid = Binder.getCallingUid();
20252        final int permission = mContext.checkCallingOrSelfPermission(
20253                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20254        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20255        enforceCrossUserPermission(uid, userId,
20256                true /* requireFullPermission */, true /* checkShell */, "stop package");
20257        // writer
20258        synchronized (mPackages) {
20259            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20260                    allowedByPermission, uid, userId)) {
20261                scheduleWritePackageRestrictionsLocked(userId);
20262            }
20263        }
20264    }
20265
20266    @Override
20267    public String getInstallerPackageName(String packageName) {
20268        // reader
20269        synchronized (mPackages) {
20270            return mSettings.getInstallerPackageNameLPr(packageName);
20271        }
20272    }
20273
20274    public boolean isOrphaned(String packageName) {
20275        // reader
20276        synchronized (mPackages) {
20277            return mSettings.isOrphaned(packageName);
20278        }
20279    }
20280
20281    @Override
20282    public int getApplicationEnabledSetting(String packageName, int userId) {
20283        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20284        int uid = Binder.getCallingUid();
20285        enforceCrossUserPermission(uid, userId,
20286                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20287        // reader
20288        synchronized (mPackages) {
20289            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20290        }
20291    }
20292
20293    @Override
20294    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20295        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20296        int uid = Binder.getCallingUid();
20297        enforceCrossUserPermission(uid, userId,
20298                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20299        // reader
20300        synchronized (mPackages) {
20301            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20302        }
20303    }
20304
20305    @Override
20306    public void enterSafeMode() {
20307        enforceSystemOrRoot("Only the system can request entering safe mode");
20308
20309        if (!mSystemReady) {
20310            mSafeMode = true;
20311        }
20312    }
20313
20314    @Override
20315    public void systemReady() {
20316        mSystemReady = true;
20317        final ContentResolver resolver = mContext.getContentResolver();
20318        ContentObserver co = new ContentObserver(mHandler) {
20319            @Override
20320            public void onChange(boolean selfChange) {
20321                mEphemeralAppsDisabled =
20322                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20323                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20324            }
20325        };
20326        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20327                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20328                false, co, UserHandle.USER_SYSTEM);
20329        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20330                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20331        co.onChange(true);
20332
20333        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20334        // disabled after already being started.
20335        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20336                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20337
20338        // Read the compatibilty setting when the system is ready.
20339        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20340                mContext.getContentResolver(),
20341                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20342        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20343        if (DEBUG_SETTINGS) {
20344            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20345        }
20346
20347        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20348
20349        synchronized (mPackages) {
20350            // Verify that all of the preferred activity components actually
20351            // exist.  It is possible for applications to be updated and at
20352            // that point remove a previously declared activity component that
20353            // had been set as a preferred activity.  We try to clean this up
20354            // the next time we encounter that preferred activity, but it is
20355            // possible for the user flow to never be able to return to that
20356            // situation so here we do a sanity check to make sure we haven't
20357            // left any junk around.
20358            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20359            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20360                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20361                removed.clear();
20362                for (PreferredActivity pa : pir.filterSet()) {
20363                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20364                        removed.add(pa);
20365                    }
20366                }
20367                if (removed.size() > 0) {
20368                    for (int r=0; r<removed.size(); r++) {
20369                        PreferredActivity pa = removed.get(r);
20370                        Slog.w(TAG, "Removing dangling preferred activity: "
20371                                + pa.mPref.mComponent);
20372                        pir.removeFilter(pa);
20373                    }
20374                    mSettings.writePackageRestrictionsLPr(
20375                            mSettings.mPreferredActivities.keyAt(i));
20376                }
20377            }
20378
20379            for (int userId : UserManagerService.getInstance().getUserIds()) {
20380                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20381                    grantPermissionsUserIds = ArrayUtils.appendInt(
20382                            grantPermissionsUserIds, userId);
20383                }
20384            }
20385        }
20386        sUserManager.systemReady();
20387
20388        // If we upgraded grant all default permissions before kicking off.
20389        for (int userId : grantPermissionsUserIds) {
20390            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20391        }
20392
20393        // If we did not grant default permissions, we preload from this the
20394        // default permission exceptions lazily to ensure we don't hit the
20395        // disk on a new user creation.
20396        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20397            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20398        }
20399
20400        // Kick off any messages waiting for system ready
20401        if (mPostSystemReadyMessages != null) {
20402            for (Message msg : mPostSystemReadyMessages) {
20403                msg.sendToTarget();
20404            }
20405            mPostSystemReadyMessages = null;
20406        }
20407
20408        // Watch for external volumes that come and go over time
20409        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20410        storage.registerListener(mStorageListener);
20411
20412        mInstallerService.systemReady();
20413        mPackageDexOptimizer.systemReady();
20414
20415        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20416                StorageManagerInternal.class);
20417        StorageManagerInternal.addExternalStoragePolicy(
20418                new StorageManagerInternal.ExternalStorageMountPolicy() {
20419            @Override
20420            public int getMountMode(int uid, String packageName) {
20421                if (Process.isIsolated(uid)) {
20422                    return Zygote.MOUNT_EXTERNAL_NONE;
20423                }
20424                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20425                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20426                }
20427                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20428                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20429                }
20430                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20431                    return Zygote.MOUNT_EXTERNAL_READ;
20432                }
20433                return Zygote.MOUNT_EXTERNAL_WRITE;
20434            }
20435
20436            @Override
20437            public boolean hasExternalStorage(int uid, String packageName) {
20438                return true;
20439            }
20440        });
20441
20442        // Now that we're mostly running, clean up stale users and apps
20443        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20444        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20445
20446        if (mPrivappPermissionsViolations != null) {
20447            Slog.wtf(TAG,"Signature|privileged permissions not in "
20448                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20449            mPrivappPermissionsViolations = null;
20450        }
20451    }
20452
20453    public void waitForAppDataPrepared() {
20454        if (mPrepareAppDataFuture == null) {
20455            return;
20456        }
20457        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20458        mPrepareAppDataFuture = null;
20459    }
20460
20461    @Override
20462    public boolean isSafeMode() {
20463        return mSafeMode;
20464    }
20465
20466    @Override
20467    public boolean hasSystemUidErrors() {
20468        return mHasSystemUidErrors;
20469    }
20470
20471    static String arrayToString(int[] array) {
20472        StringBuffer buf = new StringBuffer(128);
20473        buf.append('[');
20474        if (array != null) {
20475            for (int i=0; i<array.length; i++) {
20476                if (i > 0) buf.append(", ");
20477                buf.append(array[i]);
20478            }
20479        }
20480        buf.append(']');
20481        return buf.toString();
20482    }
20483
20484    static class DumpState {
20485        public static final int DUMP_LIBS = 1 << 0;
20486        public static final int DUMP_FEATURES = 1 << 1;
20487        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20488        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20489        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20490        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20491        public static final int DUMP_PERMISSIONS = 1 << 6;
20492        public static final int DUMP_PACKAGES = 1 << 7;
20493        public static final int DUMP_SHARED_USERS = 1 << 8;
20494        public static final int DUMP_MESSAGES = 1 << 9;
20495        public static final int DUMP_PROVIDERS = 1 << 10;
20496        public static final int DUMP_VERIFIERS = 1 << 11;
20497        public static final int DUMP_PREFERRED = 1 << 12;
20498        public static final int DUMP_PREFERRED_XML = 1 << 13;
20499        public static final int DUMP_KEYSETS = 1 << 14;
20500        public static final int DUMP_VERSION = 1 << 15;
20501        public static final int DUMP_INSTALLS = 1 << 16;
20502        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20503        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20504        public static final int DUMP_FROZEN = 1 << 19;
20505        public static final int DUMP_DEXOPT = 1 << 20;
20506        public static final int DUMP_COMPILER_STATS = 1 << 21;
20507        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20508
20509        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20510
20511        private int mTypes;
20512
20513        private int mOptions;
20514
20515        private boolean mTitlePrinted;
20516
20517        private SharedUserSetting mSharedUser;
20518
20519        public boolean isDumping(int type) {
20520            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20521                return true;
20522            }
20523
20524            return (mTypes & type) != 0;
20525        }
20526
20527        public void setDump(int type) {
20528            mTypes |= type;
20529        }
20530
20531        public boolean isOptionEnabled(int option) {
20532            return (mOptions & option) != 0;
20533        }
20534
20535        public void setOptionEnabled(int option) {
20536            mOptions |= option;
20537        }
20538
20539        public boolean onTitlePrinted() {
20540            final boolean printed = mTitlePrinted;
20541            mTitlePrinted = true;
20542            return printed;
20543        }
20544
20545        public boolean getTitlePrinted() {
20546            return mTitlePrinted;
20547        }
20548
20549        public void setTitlePrinted(boolean enabled) {
20550            mTitlePrinted = enabled;
20551        }
20552
20553        public SharedUserSetting getSharedUser() {
20554            return mSharedUser;
20555        }
20556
20557        public void setSharedUser(SharedUserSetting user) {
20558            mSharedUser = user;
20559        }
20560    }
20561
20562    @Override
20563    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20564            FileDescriptor err, String[] args, ShellCallback callback,
20565            ResultReceiver resultReceiver) {
20566        (new PackageManagerShellCommand(this)).exec(
20567                this, in, out, err, args, callback, resultReceiver);
20568    }
20569
20570    @Override
20571    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20572        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20573
20574        DumpState dumpState = new DumpState();
20575        boolean fullPreferred = false;
20576        boolean checkin = false;
20577
20578        String packageName = null;
20579        ArraySet<String> permissionNames = null;
20580
20581        int opti = 0;
20582        while (opti < args.length) {
20583            String opt = args[opti];
20584            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20585                break;
20586            }
20587            opti++;
20588
20589            if ("-a".equals(opt)) {
20590                // Right now we only know how to print all.
20591            } else if ("-h".equals(opt)) {
20592                pw.println("Package manager dump options:");
20593                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20594                pw.println("    --checkin: dump for a checkin");
20595                pw.println("    -f: print details of intent filters");
20596                pw.println("    -h: print this help");
20597                pw.println("  cmd may be one of:");
20598                pw.println("    l[ibraries]: list known shared libraries");
20599                pw.println("    f[eatures]: list device features");
20600                pw.println("    k[eysets]: print known keysets");
20601                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20602                pw.println("    perm[issions]: dump permissions");
20603                pw.println("    permission [name ...]: dump declaration and use of given permission");
20604                pw.println("    pref[erred]: print preferred package settings");
20605                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20606                pw.println("    prov[iders]: dump content providers");
20607                pw.println("    p[ackages]: dump installed packages");
20608                pw.println("    s[hared-users]: dump shared user IDs");
20609                pw.println("    m[essages]: print collected runtime messages");
20610                pw.println("    v[erifiers]: print package verifier info");
20611                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20612                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20613                pw.println("    version: print database version info");
20614                pw.println("    write: write current settings now");
20615                pw.println("    installs: details about install sessions");
20616                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20617                pw.println("    dexopt: dump dexopt state");
20618                pw.println("    compiler-stats: dump compiler statistics");
20619                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20620                pw.println("    <package.name>: info about given package");
20621                return;
20622            } else if ("--checkin".equals(opt)) {
20623                checkin = true;
20624            } else if ("-f".equals(opt)) {
20625                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20626            } else if ("--proto".equals(opt)) {
20627                dumpProto(fd);
20628                return;
20629            } else {
20630                pw.println("Unknown argument: " + opt + "; use -h for help");
20631            }
20632        }
20633
20634        // Is the caller requesting to dump a particular piece of data?
20635        if (opti < args.length) {
20636            String cmd = args[opti];
20637            opti++;
20638            // Is this a package name?
20639            if ("android".equals(cmd) || cmd.contains(".")) {
20640                packageName = cmd;
20641                // When dumping a single package, we always dump all of its
20642                // filter information since the amount of data will be reasonable.
20643                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20644            } else if ("check-permission".equals(cmd)) {
20645                if (opti >= args.length) {
20646                    pw.println("Error: check-permission missing permission argument");
20647                    return;
20648                }
20649                String perm = args[opti];
20650                opti++;
20651                if (opti >= args.length) {
20652                    pw.println("Error: check-permission missing package argument");
20653                    return;
20654                }
20655
20656                String pkg = args[opti];
20657                opti++;
20658                int user = UserHandle.getUserId(Binder.getCallingUid());
20659                if (opti < args.length) {
20660                    try {
20661                        user = Integer.parseInt(args[opti]);
20662                    } catch (NumberFormatException e) {
20663                        pw.println("Error: check-permission user argument is not a number: "
20664                                + args[opti]);
20665                        return;
20666                    }
20667                }
20668
20669                // Normalize package name to handle renamed packages and static libs
20670                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20671
20672                pw.println(checkPermission(perm, pkg, user));
20673                return;
20674            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20675                dumpState.setDump(DumpState.DUMP_LIBS);
20676            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20677                dumpState.setDump(DumpState.DUMP_FEATURES);
20678            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20679                if (opti >= args.length) {
20680                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20681                            | DumpState.DUMP_SERVICE_RESOLVERS
20682                            | DumpState.DUMP_RECEIVER_RESOLVERS
20683                            | DumpState.DUMP_CONTENT_RESOLVERS);
20684                } else {
20685                    while (opti < args.length) {
20686                        String name = args[opti];
20687                        if ("a".equals(name) || "activity".equals(name)) {
20688                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20689                        } else if ("s".equals(name) || "service".equals(name)) {
20690                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20691                        } else if ("r".equals(name) || "receiver".equals(name)) {
20692                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20693                        } else if ("c".equals(name) || "content".equals(name)) {
20694                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20695                        } else {
20696                            pw.println("Error: unknown resolver table type: " + name);
20697                            return;
20698                        }
20699                        opti++;
20700                    }
20701                }
20702            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20703                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20704            } else if ("permission".equals(cmd)) {
20705                if (opti >= args.length) {
20706                    pw.println("Error: permission requires permission name");
20707                    return;
20708                }
20709                permissionNames = new ArraySet<>();
20710                while (opti < args.length) {
20711                    permissionNames.add(args[opti]);
20712                    opti++;
20713                }
20714                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20715                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20716            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20717                dumpState.setDump(DumpState.DUMP_PREFERRED);
20718            } else if ("preferred-xml".equals(cmd)) {
20719                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20720                if (opti < args.length && "--full".equals(args[opti])) {
20721                    fullPreferred = true;
20722                    opti++;
20723                }
20724            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20725                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20726            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20727                dumpState.setDump(DumpState.DUMP_PACKAGES);
20728            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20729                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20730            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20731                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20732            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20733                dumpState.setDump(DumpState.DUMP_MESSAGES);
20734            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20735                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20736            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20737                    || "intent-filter-verifiers".equals(cmd)) {
20738                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20739            } else if ("version".equals(cmd)) {
20740                dumpState.setDump(DumpState.DUMP_VERSION);
20741            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20742                dumpState.setDump(DumpState.DUMP_KEYSETS);
20743            } else if ("installs".equals(cmd)) {
20744                dumpState.setDump(DumpState.DUMP_INSTALLS);
20745            } else if ("frozen".equals(cmd)) {
20746                dumpState.setDump(DumpState.DUMP_FROZEN);
20747            } else if ("dexopt".equals(cmd)) {
20748                dumpState.setDump(DumpState.DUMP_DEXOPT);
20749            } else if ("compiler-stats".equals(cmd)) {
20750                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20751            } else if ("enabled-overlays".equals(cmd)) {
20752                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20753            } else if ("write".equals(cmd)) {
20754                synchronized (mPackages) {
20755                    mSettings.writeLPr();
20756                    pw.println("Settings written.");
20757                    return;
20758                }
20759            }
20760        }
20761
20762        if (checkin) {
20763            pw.println("vers,1");
20764        }
20765
20766        // reader
20767        synchronized (mPackages) {
20768            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20769                if (!checkin) {
20770                    if (dumpState.onTitlePrinted())
20771                        pw.println();
20772                    pw.println("Database versions:");
20773                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20774                }
20775            }
20776
20777            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20778                if (!checkin) {
20779                    if (dumpState.onTitlePrinted())
20780                        pw.println();
20781                    pw.println("Verifiers:");
20782                    pw.print("  Required: ");
20783                    pw.print(mRequiredVerifierPackage);
20784                    pw.print(" (uid=");
20785                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20786                            UserHandle.USER_SYSTEM));
20787                    pw.println(")");
20788                } else if (mRequiredVerifierPackage != null) {
20789                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20790                    pw.print(",");
20791                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20792                            UserHandle.USER_SYSTEM));
20793                }
20794            }
20795
20796            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20797                    packageName == null) {
20798                if (mIntentFilterVerifierComponent != null) {
20799                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20800                    if (!checkin) {
20801                        if (dumpState.onTitlePrinted())
20802                            pw.println();
20803                        pw.println("Intent Filter Verifier:");
20804                        pw.print("  Using: ");
20805                        pw.print(verifierPackageName);
20806                        pw.print(" (uid=");
20807                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20808                                UserHandle.USER_SYSTEM));
20809                        pw.println(")");
20810                    } else if (verifierPackageName != null) {
20811                        pw.print("ifv,"); pw.print(verifierPackageName);
20812                        pw.print(",");
20813                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20814                                UserHandle.USER_SYSTEM));
20815                    }
20816                } else {
20817                    pw.println();
20818                    pw.println("No Intent Filter Verifier available!");
20819                }
20820            }
20821
20822            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20823                boolean printedHeader = false;
20824                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20825                while (it.hasNext()) {
20826                    String libName = it.next();
20827                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20828                    if (versionedLib == null) {
20829                        continue;
20830                    }
20831                    final int versionCount = versionedLib.size();
20832                    for (int i = 0; i < versionCount; i++) {
20833                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20834                        if (!checkin) {
20835                            if (!printedHeader) {
20836                                if (dumpState.onTitlePrinted())
20837                                    pw.println();
20838                                pw.println("Libraries:");
20839                                printedHeader = true;
20840                            }
20841                            pw.print("  ");
20842                        } else {
20843                            pw.print("lib,");
20844                        }
20845                        pw.print(libEntry.info.getName());
20846                        if (libEntry.info.isStatic()) {
20847                            pw.print(" version=" + libEntry.info.getVersion());
20848                        }
20849                        if (!checkin) {
20850                            pw.print(" -> ");
20851                        }
20852                        if (libEntry.path != null) {
20853                            pw.print(" (jar) ");
20854                            pw.print(libEntry.path);
20855                        } else {
20856                            pw.print(" (apk) ");
20857                            pw.print(libEntry.apk);
20858                        }
20859                        pw.println();
20860                    }
20861                }
20862            }
20863
20864            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20865                if (dumpState.onTitlePrinted())
20866                    pw.println();
20867                if (!checkin) {
20868                    pw.println("Features:");
20869                }
20870
20871                synchronized (mAvailableFeatures) {
20872                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20873                        if (checkin) {
20874                            pw.print("feat,");
20875                            pw.print(feat.name);
20876                            pw.print(",");
20877                            pw.println(feat.version);
20878                        } else {
20879                            pw.print("  ");
20880                            pw.print(feat.name);
20881                            if (feat.version > 0) {
20882                                pw.print(" version=");
20883                                pw.print(feat.version);
20884                            }
20885                            pw.println();
20886                        }
20887                    }
20888                }
20889            }
20890
20891            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20892                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20893                        : "Activity Resolver Table:", "  ", packageName,
20894                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20895                    dumpState.setTitlePrinted(true);
20896                }
20897            }
20898            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20899                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20900                        : "Receiver Resolver Table:", "  ", packageName,
20901                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20902                    dumpState.setTitlePrinted(true);
20903                }
20904            }
20905            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20906                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20907                        : "Service Resolver Table:", "  ", packageName,
20908                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20909                    dumpState.setTitlePrinted(true);
20910                }
20911            }
20912            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20913                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20914                        : "Provider Resolver Table:", "  ", packageName,
20915                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20916                    dumpState.setTitlePrinted(true);
20917                }
20918            }
20919
20920            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20921                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20922                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20923                    int user = mSettings.mPreferredActivities.keyAt(i);
20924                    if (pir.dump(pw,
20925                            dumpState.getTitlePrinted()
20926                                ? "\nPreferred Activities User " + user + ":"
20927                                : "Preferred Activities User " + user + ":", "  ",
20928                            packageName, true, false)) {
20929                        dumpState.setTitlePrinted(true);
20930                    }
20931                }
20932            }
20933
20934            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20935                pw.flush();
20936                FileOutputStream fout = new FileOutputStream(fd);
20937                BufferedOutputStream str = new BufferedOutputStream(fout);
20938                XmlSerializer serializer = new FastXmlSerializer();
20939                try {
20940                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20941                    serializer.startDocument(null, true);
20942                    serializer.setFeature(
20943                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20944                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20945                    serializer.endDocument();
20946                    serializer.flush();
20947                } catch (IllegalArgumentException e) {
20948                    pw.println("Failed writing: " + e);
20949                } catch (IllegalStateException e) {
20950                    pw.println("Failed writing: " + e);
20951                } catch (IOException e) {
20952                    pw.println("Failed writing: " + e);
20953                }
20954            }
20955
20956            if (!checkin
20957                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20958                    && packageName == null) {
20959                pw.println();
20960                int count = mSettings.mPackages.size();
20961                if (count == 0) {
20962                    pw.println("No applications!");
20963                    pw.println();
20964                } else {
20965                    final String prefix = "  ";
20966                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20967                    if (allPackageSettings.size() == 0) {
20968                        pw.println("No domain preferred apps!");
20969                        pw.println();
20970                    } else {
20971                        pw.println("App verification status:");
20972                        pw.println();
20973                        count = 0;
20974                        for (PackageSetting ps : allPackageSettings) {
20975                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20976                            if (ivi == null || ivi.getPackageName() == null) continue;
20977                            pw.println(prefix + "Package: " + ivi.getPackageName());
20978                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20979                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20980                            pw.println();
20981                            count++;
20982                        }
20983                        if (count == 0) {
20984                            pw.println(prefix + "No app verification established.");
20985                            pw.println();
20986                        }
20987                        for (int userId : sUserManager.getUserIds()) {
20988                            pw.println("App linkages for user " + userId + ":");
20989                            pw.println();
20990                            count = 0;
20991                            for (PackageSetting ps : allPackageSettings) {
20992                                final long status = ps.getDomainVerificationStatusForUser(userId);
20993                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20994                                        && !DEBUG_DOMAIN_VERIFICATION) {
20995                                    continue;
20996                                }
20997                                pw.println(prefix + "Package: " + ps.name);
20998                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20999                                String statusStr = IntentFilterVerificationInfo.
21000                                        getStatusStringFromValue(status);
21001                                pw.println(prefix + "Status:  " + statusStr);
21002                                pw.println();
21003                                count++;
21004                            }
21005                            if (count == 0) {
21006                                pw.println(prefix + "No configured app linkages.");
21007                                pw.println();
21008                            }
21009                        }
21010                    }
21011                }
21012            }
21013
21014            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21015                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21016                if (packageName == null && permissionNames == null) {
21017                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21018                        if (iperm == 0) {
21019                            if (dumpState.onTitlePrinted())
21020                                pw.println();
21021                            pw.println("AppOp Permissions:");
21022                        }
21023                        pw.print("  AppOp Permission ");
21024                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21025                        pw.println(":");
21026                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21027                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21028                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21029                        }
21030                    }
21031                }
21032            }
21033
21034            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21035                boolean printedSomething = false;
21036                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21037                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21038                        continue;
21039                    }
21040                    if (!printedSomething) {
21041                        if (dumpState.onTitlePrinted())
21042                            pw.println();
21043                        pw.println("Registered ContentProviders:");
21044                        printedSomething = true;
21045                    }
21046                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21047                    pw.print("    "); pw.println(p.toString());
21048                }
21049                printedSomething = false;
21050                for (Map.Entry<String, PackageParser.Provider> entry :
21051                        mProvidersByAuthority.entrySet()) {
21052                    PackageParser.Provider p = entry.getValue();
21053                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21054                        continue;
21055                    }
21056                    if (!printedSomething) {
21057                        if (dumpState.onTitlePrinted())
21058                            pw.println();
21059                        pw.println("ContentProvider Authorities:");
21060                        printedSomething = true;
21061                    }
21062                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21063                    pw.print("    "); pw.println(p.toString());
21064                    if (p.info != null && p.info.applicationInfo != null) {
21065                        final String appInfo = p.info.applicationInfo.toString();
21066                        pw.print("      applicationInfo="); pw.println(appInfo);
21067                    }
21068                }
21069            }
21070
21071            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21072                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21073            }
21074
21075            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21076                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21077            }
21078
21079            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21080                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21081            }
21082
21083            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21084                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21085            }
21086
21087            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21088                // XXX should handle packageName != null by dumping only install data that
21089                // the given package is involved with.
21090                if (dumpState.onTitlePrinted()) pw.println();
21091
21092                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21093                ipw.println();
21094                ipw.println("Frozen packages:");
21095                ipw.increaseIndent();
21096                if (mFrozenPackages.size() == 0) {
21097                    ipw.println("(none)");
21098                } else {
21099                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21100                        ipw.println(mFrozenPackages.valueAt(i));
21101                    }
21102                }
21103                ipw.decreaseIndent();
21104            }
21105
21106            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21107                if (dumpState.onTitlePrinted()) pw.println();
21108                dumpDexoptStateLPr(pw, packageName);
21109            }
21110
21111            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21112                if (dumpState.onTitlePrinted()) pw.println();
21113                dumpCompilerStatsLPr(pw, packageName);
21114            }
21115
21116            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21117                if (dumpState.onTitlePrinted()) pw.println();
21118                dumpEnabledOverlaysLPr(pw);
21119            }
21120
21121            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21122                if (dumpState.onTitlePrinted()) pw.println();
21123                mSettings.dumpReadMessagesLPr(pw, dumpState);
21124
21125                pw.println();
21126                pw.println("Package warning messages:");
21127                BufferedReader in = null;
21128                String line = null;
21129                try {
21130                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21131                    while ((line = in.readLine()) != null) {
21132                        if (line.contains("ignored: updated version")) continue;
21133                        pw.println(line);
21134                    }
21135                } catch (IOException ignored) {
21136                } finally {
21137                    IoUtils.closeQuietly(in);
21138                }
21139            }
21140
21141            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21142                BufferedReader in = null;
21143                String line = null;
21144                try {
21145                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21146                    while ((line = in.readLine()) != null) {
21147                        if (line.contains("ignored: updated version")) continue;
21148                        pw.print("msg,");
21149                        pw.println(line);
21150                    }
21151                } catch (IOException ignored) {
21152                } finally {
21153                    IoUtils.closeQuietly(in);
21154                }
21155            }
21156        }
21157
21158        // PackageInstaller should be called outside of mPackages lock
21159        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21160            // XXX should handle packageName != null by dumping only install data that
21161            // the given package is involved with.
21162            if (dumpState.onTitlePrinted()) pw.println();
21163            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21164        }
21165    }
21166
21167    private void dumpProto(FileDescriptor fd) {
21168        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21169
21170        synchronized (mPackages) {
21171            final long requiredVerifierPackageToken =
21172                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21173            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21174            proto.write(
21175                    PackageServiceDumpProto.PackageShortProto.UID,
21176                    getPackageUid(
21177                            mRequiredVerifierPackage,
21178                            MATCH_DEBUG_TRIAGED_MISSING,
21179                            UserHandle.USER_SYSTEM));
21180            proto.end(requiredVerifierPackageToken);
21181
21182            if (mIntentFilterVerifierComponent != null) {
21183                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21184                final long verifierPackageToken =
21185                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21186                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21187                proto.write(
21188                        PackageServiceDumpProto.PackageShortProto.UID,
21189                        getPackageUid(
21190                                verifierPackageName,
21191                                MATCH_DEBUG_TRIAGED_MISSING,
21192                                UserHandle.USER_SYSTEM));
21193                proto.end(verifierPackageToken);
21194            }
21195
21196            dumpSharedLibrariesProto(proto);
21197            dumpFeaturesProto(proto);
21198            mSettings.dumpPackagesProto(proto);
21199            mSettings.dumpSharedUsersProto(proto);
21200            dumpMessagesProto(proto);
21201        }
21202        proto.flush();
21203    }
21204
21205    private void dumpMessagesProto(ProtoOutputStream proto) {
21206        BufferedReader in = null;
21207        String line = null;
21208        try {
21209            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21210            while ((line = in.readLine()) != null) {
21211                if (line.contains("ignored: updated version")) continue;
21212                proto.write(PackageServiceDumpProto.MESSAGES, line);
21213            }
21214        } catch (IOException ignored) {
21215        } finally {
21216            IoUtils.closeQuietly(in);
21217        }
21218    }
21219
21220    private void dumpFeaturesProto(ProtoOutputStream proto) {
21221        synchronized (mAvailableFeatures) {
21222            final int count = mAvailableFeatures.size();
21223            for (int i = 0; i < count; i++) {
21224                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21225                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21226                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21227                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21228                proto.end(featureToken);
21229            }
21230        }
21231    }
21232
21233    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21234        final int count = mSharedLibraries.size();
21235        for (int i = 0; i < count; i++) {
21236            final String libName = mSharedLibraries.keyAt(i);
21237            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21238            if (versionedLib == null) {
21239                continue;
21240            }
21241            final int versionCount = versionedLib.size();
21242            for (int j = 0; j < versionCount; j++) {
21243                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21244                final long sharedLibraryToken =
21245                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21246                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21247                final boolean isJar = (libEntry.path != null);
21248                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21249                if (isJar) {
21250                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21251                } else {
21252                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21253                }
21254                proto.end(sharedLibraryToken);
21255            }
21256        }
21257    }
21258
21259    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21260        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21261        ipw.println();
21262        ipw.println("Dexopt state:");
21263        ipw.increaseIndent();
21264        Collection<PackageParser.Package> packages = null;
21265        if (packageName != null) {
21266            PackageParser.Package targetPackage = mPackages.get(packageName);
21267            if (targetPackage != null) {
21268                packages = Collections.singletonList(targetPackage);
21269            } else {
21270                ipw.println("Unable to find package: " + packageName);
21271                return;
21272            }
21273        } else {
21274            packages = mPackages.values();
21275        }
21276
21277        for (PackageParser.Package pkg : packages) {
21278            ipw.println("[" + pkg.packageName + "]");
21279            ipw.increaseIndent();
21280            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21281            ipw.decreaseIndent();
21282        }
21283    }
21284
21285    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21286        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21287        ipw.println();
21288        ipw.println("Compiler stats:");
21289        ipw.increaseIndent();
21290        Collection<PackageParser.Package> packages = null;
21291        if (packageName != null) {
21292            PackageParser.Package targetPackage = mPackages.get(packageName);
21293            if (targetPackage != null) {
21294                packages = Collections.singletonList(targetPackage);
21295            } else {
21296                ipw.println("Unable to find package: " + packageName);
21297                return;
21298            }
21299        } else {
21300            packages = mPackages.values();
21301        }
21302
21303        for (PackageParser.Package pkg : packages) {
21304            ipw.println("[" + pkg.packageName + "]");
21305            ipw.increaseIndent();
21306
21307            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21308            if (stats == null) {
21309                ipw.println("(No recorded stats)");
21310            } else {
21311                stats.dump(ipw);
21312            }
21313            ipw.decreaseIndent();
21314        }
21315    }
21316
21317    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21318        pw.println("Enabled overlay paths:");
21319        final int N = mEnabledOverlayPaths.size();
21320        for (int i = 0; i < N; i++) {
21321            final int userId = mEnabledOverlayPaths.keyAt(i);
21322            pw.println(String.format("    User %d:", userId));
21323            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21324                mEnabledOverlayPaths.valueAt(i);
21325            final int M = userSpecificOverlays.size();
21326            for (int j = 0; j < M; j++) {
21327                final String targetPackageName = userSpecificOverlays.keyAt(j);
21328                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21329                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21330            }
21331        }
21332    }
21333
21334    private String dumpDomainString(String packageName) {
21335        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21336                .getList();
21337        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21338
21339        ArraySet<String> result = new ArraySet<>();
21340        if (iviList.size() > 0) {
21341            for (IntentFilterVerificationInfo ivi : iviList) {
21342                for (String host : ivi.getDomains()) {
21343                    result.add(host);
21344                }
21345            }
21346        }
21347        if (filters != null && filters.size() > 0) {
21348            for (IntentFilter filter : filters) {
21349                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21350                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21351                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21352                    result.addAll(filter.getHostsList());
21353                }
21354            }
21355        }
21356
21357        StringBuilder sb = new StringBuilder(result.size() * 16);
21358        for (String domain : result) {
21359            if (sb.length() > 0) sb.append(" ");
21360            sb.append(domain);
21361        }
21362        return sb.toString();
21363    }
21364
21365    // ------- apps on sdcard specific code -------
21366    static final boolean DEBUG_SD_INSTALL = false;
21367
21368    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21369
21370    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21371
21372    private boolean mMediaMounted = false;
21373
21374    static String getEncryptKey() {
21375        try {
21376            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21377                    SD_ENCRYPTION_KEYSTORE_NAME);
21378            if (sdEncKey == null) {
21379                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21380                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21381                if (sdEncKey == null) {
21382                    Slog.e(TAG, "Failed to create encryption keys");
21383                    return null;
21384                }
21385            }
21386            return sdEncKey;
21387        } catch (NoSuchAlgorithmException nsae) {
21388            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21389            return null;
21390        } catch (IOException ioe) {
21391            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21392            return null;
21393        }
21394    }
21395
21396    /*
21397     * Update media status on PackageManager.
21398     */
21399    @Override
21400    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21401        int callingUid = Binder.getCallingUid();
21402        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21403            throw new SecurityException("Media status can only be updated by the system");
21404        }
21405        // reader; this apparently protects mMediaMounted, but should probably
21406        // be a different lock in that case.
21407        synchronized (mPackages) {
21408            Log.i(TAG, "Updating external media status from "
21409                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21410                    + (mediaStatus ? "mounted" : "unmounted"));
21411            if (DEBUG_SD_INSTALL)
21412                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21413                        + ", mMediaMounted=" + mMediaMounted);
21414            if (mediaStatus == mMediaMounted) {
21415                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21416                        : 0, -1);
21417                mHandler.sendMessage(msg);
21418                return;
21419            }
21420            mMediaMounted = mediaStatus;
21421        }
21422        // Queue up an async operation since the package installation may take a
21423        // little while.
21424        mHandler.post(new Runnable() {
21425            public void run() {
21426                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21427            }
21428        });
21429    }
21430
21431    /**
21432     * Called by StorageManagerService when the initial ASECs to scan are available.
21433     * Should block until all the ASEC containers are finished being scanned.
21434     */
21435    public void scanAvailableAsecs() {
21436        updateExternalMediaStatusInner(true, false, false);
21437    }
21438
21439    /*
21440     * Collect information of applications on external media, map them against
21441     * existing containers and update information based on current mount status.
21442     * Please note that we always have to report status if reportStatus has been
21443     * set to true especially when unloading packages.
21444     */
21445    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21446            boolean externalStorage) {
21447        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21448        int[] uidArr = EmptyArray.INT;
21449
21450        final String[] list = PackageHelper.getSecureContainerList();
21451        if (ArrayUtils.isEmpty(list)) {
21452            Log.i(TAG, "No secure containers found");
21453        } else {
21454            // Process list of secure containers and categorize them
21455            // as active or stale based on their package internal state.
21456
21457            // reader
21458            synchronized (mPackages) {
21459                for (String cid : list) {
21460                    // Leave stages untouched for now; installer service owns them
21461                    if (PackageInstallerService.isStageName(cid)) continue;
21462
21463                    if (DEBUG_SD_INSTALL)
21464                        Log.i(TAG, "Processing container " + cid);
21465                    String pkgName = getAsecPackageName(cid);
21466                    if (pkgName == null) {
21467                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21468                        continue;
21469                    }
21470                    if (DEBUG_SD_INSTALL)
21471                        Log.i(TAG, "Looking for pkg : " + pkgName);
21472
21473                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21474                    if (ps == null) {
21475                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21476                        continue;
21477                    }
21478
21479                    /*
21480                     * Skip packages that are not external if we're unmounting
21481                     * external storage.
21482                     */
21483                    if (externalStorage && !isMounted && !isExternal(ps)) {
21484                        continue;
21485                    }
21486
21487                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21488                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21489                    // The package status is changed only if the code path
21490                    // matches between settings and the container id.
21491                    if (ps.codePathString != null
21492                            && ps.codePathString.startsWith(args.getCodePath())) {
21493                        if (DEBUG_SD_INSTALL) {
21494                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21495                                    + " at code path: " + ps.codePathString);
21496                        }
21497
21498                        // We do have a valid package installed on sdcard
21499                        processCids.put(args, ps.codePathString);
21500                        final int uid = ps.appId;
21501                        if (uid != -1) {
21502                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21503                        }
21504                    } else {
21505                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21506                                + ps.codePathString);
21507                    }
21508                }
21509            }
21510
21511            Arrays.sort(uidArr);
21512        }
21513
21514        // Process packages with valid entries.
21515        if (isMounted) {
21516            if (DEBUG_SD_INSTALL)
21517                Log.i(TAG, "Loading packages");
21518            loadMediaPackages(processCids, uidArr, externalStorage);
21519            startCleaningPackages();
21520            mInstallerService.onSecureContainersAvailable();
21521        } else {
21522            if (DEBUG_SD_INSTALL)
21523                Log.i(TAG, "Unloading packages");
21524            unloadMediaPackages(processCids, uidArr, reportStatus);
21525        }
21526    }
21527
21528    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21529            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21530        final int size = infos.size();
21531        final String[] packageNames = new String[size];
21532        final int[] packageUids = new int[size];
21533        for (int i = 0; i < size; i++) {
21534            final ApplicationInfo info = infos.get(i);
21535            packageNames[i] = info.packageName;
21536            packageUids[i] = info.uid;
21537        }
21538        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21539                finishedReceiver);
21540    }
21541
21542    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21543            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21544        sendResourcesChangedBroadcast(mediaStatus, replacing,
21545                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21546    }
21547
21548    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21549            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21550        int size = pkgList.length;
21551        if (size > 0) {
21552            // Send broadcasts here
21553            Bundle extras = new Bundle();
21554            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21555            if (uidArr != null) {
21556                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21557            }
21558            if (replacing) {
21559                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21560            }
21561            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21562                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21563            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21564        }
21565    }
21566
21567   /*
21568     * Look at potentially valid container ids from processCids If package
21569     * information doesn't match the one on record or package scanning fails,
21570     * the cid is added to list of removeCids. We currently don't delete stale
21571     * containers.
21572     */
21573    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21574            boolean externalStorage) {
21575        ArrayList<String> pkgList = new ArrayList<String>();
21576        Set<AsecInstallArgs> keys = processCids.keySet();
21577
21578        for (AsecInstallArgs args : keys) {
21579            String codePath = processCids.get(args);
21580            if (DEBUG_SD_INSTALL)
21581                Log.i(TAG, "Loading container : " + args.cid);
21582            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21583            try {
21584                // Make sure there are no container errors first.
21585                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21586                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21587                            + " when installing from sdcard");
21588                    continue;
21589                }
21590                // Check code path here.
21591                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21592                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21593                            + " does not match one in settings " + codePath);
21594                    continue;
21595                }
21596                // Parse package
21597                int parseFlags = mDefParseFlags;
21598                if (args.isExternalAsec()) {
21599                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21600                }
21601                if (args.isFwdLocked()) {
21602                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21603                }
21604
21605                synchronized (mInstallLock) {
21606                    PackageParser.Package pkg = null;
21607                    try {
21608                        // Sadly we don't know the package name yet to freeze it
21609                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21610                                SCAN_IGNORE_FROZEN, 0, null);
21611                    } catch (PackageManagerException e) {
21612                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21613                    }
21614                    // Scan the package
21615                    if (pkg != null) {
21616                        /*
21617                         * TODO why is the lock being held? doPostInstall is
21618                         * called in other places without the lock. This needs
21619                         * to be straightened out.
21620                         */
21621                        // writer
21622                        synchronized (mPackages) {
21623                            retCode = PackageManager.INSTALL_SUCCEEDED;
21624                            pkgList.add(pkg.packageName);
21625                            // Post process args
21626                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21627                                    pkg.applicationInfo.uid);
21628                        }
21629                    } else {
21630                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21631                    }
21632                }
21633
21634            } finally {
21635                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21636                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21637                }
21638            }
21639        }
21640        // writer
21641        synchronized (mPackages) {
21642            // If the platform SDK has changed since the last time we booted,
21643            // we need to re-grant app permission to catch any new ones that
21644            // appear. This is really a hack, and means that apps can in some
21645            // cases get permissions that the user didn't initially explicitly
21646            // allow... it would be nice to have some better way to handle
21647            // this situation.
21648            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21649                    : mSettings.getInternalVersion();
21650            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21651                    : StorageManager.UUID_PRIVATE_INTERNAL;
21652
21653            int updateFlags = UPDATE_PERMISSIONS_ALL;
21654            if (ver.sdkVersion != mSdkVersion) {
21655                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21656                        + mSdkVersion + "; regranting permissions for external");
21657                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21658            }
21659            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21660
21661            // Yay, everything is now upgraded
21662            ver.forceCurrent();
21663
21664            // can downgrade to reader
21665            // Persist settings
21666            mSettings.writeLPr();
21667        }
21668        // Send a broadcast to let everyone know we are done processing
21669        if (pkgList.size() > 0) {
21670            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21671        }
21672    }
21673
21674   /*
21675     * Utility method to unload a list of specified containers
21676     */
21677    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21678        // Just unmount all valid containers.
21679        for (AsecInstallArgs arg : cidArgs) {
21680            synchronized (mInstallLock) {
21681                arg.doPostDeleteLI(false);
21682           }
21683       }
21684   }
21685
21686    /*
21687     * Unload packages mounted on external media. This involves deleting package
21688     * data from internal structures, sending broadcasts about disabled packages,
21689     * gc'ing to free up references, unmounting all secure containers
21690     * corresponding to packages on external media, and posting a
21691     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21692     * that we always have to post this message if status has been requested no
21693     * matter what.
21694     */
21695    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21696            final boolean reportStatus) {
21697        if (DEBUG_SD_INSTALL)
21698            Log.i(TAG, "unloading media packages");
21699        ArrayList<String> pkgList = new ArrayList<String>();
21700        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21701        final Set<AsecInstallArgs> keys = processCids.keySet();
21702        for (AsecInstallArgs args : keys) {
21703            String pkgName = args.getPackageName();
21704            if (DEBUG_SD_INSTALL)
21705                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21706            // Delete package internally
21707            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21708            synchronized (mInstallLock) {
21709                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21710                final boolean res;
21711                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21712                        "unloadMediaPackages")) {
21713                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21714                            null);
21715                }
21716                if (res) {
21717                    pkgList.add(pkgName);
21718                } else {
21719                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21720                    failedList.add(args);
21721                }
21722            }
21723        }
21724
21725        // reader
21726        synchronized (mPackages) {
21727            // We didn't update the settings after removing each package;
21728            // write them now for all packages.
21729            mSettings.writeLPr();
21730        }
21731
21732        // We have to absolutely send UPDATED_MEDIA_STATUS only
21733        // after confirming that all the receivers processed the ordered
21734        // broadcast when packages get disabled, force a gc to clean things up.
21735        // and unload all the containers.
21736        if (pkgList.size() > 0) {
21737            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21738                    new IIntentReceiver.Stub() {
21739                public void performReceive(Intent intent, int resultCode, String data,
21740                        Bundle extras, boolean ordered, boolean sticky,
21741                        int sendingUser) throws RemoteException {
21742                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21743                            reportStatus ? 1 : 0, 1, keys);
21744                    mHandler.sendMessage(msg);
21745                }
21746            });
21747        } else {
21748            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21749                    keys);
21750            mHandler.sendMessage(msg);
21751        }
21752    }
21753
21754    private void loadPrivatePackages(final VolumeInfo vol) {
21755        mHandler.post(new Runnable() {
21756            @Override
21757            public void run() {
21758                loadPrivatePackagesInner(vol);
21759            }
21760        });
21761    }
21762
21763    private void loadPrivatePackagesInner(VolumeInfo vol) {
21764        final String volumeUuid = vol.fsUuid;
21765        if (TextUtils.isEmpty(volumeUuid)) {
21766            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21767            return;
21768        }
21769
21770        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21771        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21772        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21773
21774        final VersionInfo ver;
21775        final List<PackageSetting> packages;
21776        synchronized (mPackages) {
21777            ver = mSettings.findOrCreateVersion(volumeUuid);
21778            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21779        }
21780
21781        for (PackageSetting ps : packages) {
21782            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21783            synchronized (mInstallLock) {
21784                final PackageParser.Package pkg;
21785                try {
21786                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21787                    loaded.add(pkg.applicationInfo);
21788
21789                } catch (PackageManagerException e) {
21790                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21791                }
21792
21793                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21794                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21795                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21796                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21797                }
21798            }
21799        }
21800
21801        // Reconcile app data for all started/unlocked users
21802        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21803        final UserManager um = mContext.getSystemService(UserManager.class);
21804        UserManagerInternal umInternal = getUserManagerInternal();
21805        for (UserInfo user : um.getUsers()) {
21806            final int flags;
21807            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21808                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21809            } else if (umInternal.isUserRunning(user.id)) {
21810                flags = StorageManager.FLAG_STORAGE_DE;
21811            } else {
21812                continue;
21813            }
21814
21815            try {
21816                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21817                synchronized (mInstallLock) {
21818                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21819                }
21820            } catch (IllegalStateException e) {
21821                // Device was probably ejected, and we'll process that event momentarily
21822                Slog.w(TAG, "Failed to prepare storage: " + e);
21823            }
21824        }
21825
21826        synchronized (mPackages) {
21827            int updateFlags = UPDATE_PERMISSIONS_ALL;
21828            if (ver.sdkVersion != mSdkVersion) {
21829                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21830                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21831                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21832            }
21833            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21834
21835            // Yay, everything is now upgraded
21836            ver.forceCurrent();
21837
21838            mSettings.writeLPr();
21839        }
21840
21841        for (PackageFreezer freezer : freezers) {
21842            freezer.close();
21843        }
21844
21845        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21846        sendResourcesChangedBroadcast(true, false, loaded, null);
21847    }
21848
21849    private void unloadPrivatePackages(final VolumeInfo vol) {
21850        mHandler.post(new Runnable() {
21851            @Override
21852            public void run() {
21853                unloadPrivatePackagesInner(vol);
21854            }
21855        });
21856    }
21857
21858    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21859        final String volumeUuid = vol.fsUuid;
21860        if (TextUtils.isEmpty(volumeUuid)) {
21861            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21862            return;
21863        }
21864
21865        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21866        synchronized (mInstallLock) {
21867        synchronized (mPackages) {
21868            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21869            for (PackageSetting ps : packages) {
21870                if (ps.pkg == null) continue;
21871
21872                final ApplicationInfo info = ps.pkg.applicationInfo;
21873                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21874                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21875
21876                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21877                        "unloadPrivatePackagesInner")) {
21878                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21879                            false, null)) {
21880                        unloaded.add(info);
21881                    } else {
21882                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21883                    }
21884                }
21885
21886                // Try very hard to release any references to this package
21887                // so we don't risk the system server being killed due to
21888                // open FDs
21889                AttributeCache.instance().removePackage(ps.name);
21890            }
21891
21892            mSettings.writeLPr();
21893        }
21894        }
21895
21896        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21897        sendResourcesChangedBroadcast(false, false, unloaded, null);
21898
21899        // Try very hard to release any references to this path so we don't risk
21900        // the system server being killed due to open FDs
21901        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21902
21903        for (int i = 0; i < 3; i++) {
21904            System.gc();
21905            System.runFinalization();
21906        }
21907    }
21908
21909    private void assertPackageKnown(String volumeUuid, String packageName)
21910            throws PackageManagerException {
21911        synchronized (mPackages) {
21912            // Normalize package name to handle renamed packages
21913            packageName = normalizePackageNameLPr(packageName);
21914
21915            final PackageSetting ps = mSettings.mPackages.get(packageName);
21916            if (ps == null) {
21917                throw new PackageManagerException("Package " + packageName + " is unknown");
21918            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21919                throw new PackageManagerException(
21920                        "Package " + packageName + " found on unknown volume " + volumeUuid
21921                                + "; expected volume " + ps.volumeUuid);
21922            }
21923        }
21924    }
21925
21926    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21927            throws PackageManagerException {
21928        synchronized (mPackages) {
21929            // Normalize package name to handle renamed packages
21930            packageName = normalizePackageNameLPr(packageName);
21931
21932            final PackageSetting ps = mSettings.mPackages.get(packageName);
21933            if (ps == null) {
21934                throw new PackageManagerException("Package " + packageName + " is unknown");
21935            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21936                throw new PackageManagerException(
21937                        "Package " + packageName + " found on unknown volume " + volumeUuid
21938                                + "; expected volume " + ps.volumeUuid);
21939            } else if (!ps.getInstalled(userId)) {
21940                throw new PackageManagerException(
21941                        "Package " + packageName + " not installed for user " + userId);
21942            }
21943        }
21944    }
21945
21946    private List<String> collectAbsoluteCodePaths() {
21947        synchronized (mPackages) {
21948            List<String> codePaths = new ArrayList<>();
21949            final int packageCount = mSettings.mPackages.size();
21950            for (int i = 0; i < packageCount; i++) {
21951                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21952                codePaths.add(ps.codePath.getAbsolutePath());
21953            }
21954            return codePaths;
21955        }
21956    }
21957
21958    /**
21959     * Examine all apps present on given mounted volume, and destroy apps that
21960     * aren't expected, either due to uninstallation or reinstallation on
21961     * another volume.
21962     */
21963    private void reconcileApps(String volumeUuid) {
21964        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21965        List<File> filesToDelete = null;
21966
21967        final File[] files = FileUtils.listFilesOrEmpty(
21968                Environment.getDataAppDirectory(volumeUuid));
21969        for (File file : files) {
21970            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21971                    && !PackageInstallerService.isStageName(file.getName());
21972            if (!isPackage) {
21973                // Ignore entries which are not packages
21974                continue;
21975            }
21976
21977            String absolutePath = file.getAbsolutePath();
21978
21979            boolean pathValid = false;
21980            final int absoluteCodePathCount = absoluteCodePaths.size();
21981            for (int i = 0; i < absoluteCodePathCount; i++) {
21982                String absoluteCodePath = absoluteCodePaths.get(i);
21983                if (absolutePath.startsWith(absoluteCodePath)) {
21984                    pathValid = true;
21985                    break;
21986                }
21987            }
21988
21989            if (!pathValid) {
21990                if (filesToDelete == null) {
21991                    filesToDelete = new ArrayList<>();
21992                }
21993                filesToDelete.add(file);
21994            }
21995        }
21996
21997        if (filesToDelete != null) {
21998            final int fileToDeleteCount = filesToDelete.size();
21999            for (int i = 0; i < fileToDeleteCount; i++) {
22000                File fileToDelete = filesToDelete.get(i);
22001                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22002                synchronized (mInstallLock) {
22003                    removeCodePathLI(fileToDelete);
22004                }
22005            }
22006        }
22007    }
22008
22009    /**
22010     * Reconcile all app data for the given user.
22011     * <p>
22012     * Verifies that directories exist and that ownership and labeling is
22013     * correct for all installed apps on all mounted volumes.
22014     */
22015    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22016        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22017        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22018            final String volumeUuid = vol.getFsUuid();
22019            synchronized (mInstallLock) {
22020                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22021            }
22022        }
22023    }
22024
22025    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22026            boolean migrateAppData) {
22027        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22028    }
22029
22030    /**
22031     * Reconcile all app data on given mounted volume.
22032     * <p>
22033     * Destroys app data that isn't expected, either due to uninstallation or
22034     * reinstallation on another volume.
22035     * <p>
22036     * Verifies that directories exist and that ownership and labeling is
22037     * correct for all installed apps.
22038     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22039     */
22040    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22041            boolean migrateAppData, boolean onlyCoreApps) {
22042        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22043                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22044        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22045
22046        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22047        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22048
22049        // First look for stale data that doesn't belong, and check if things
22050        // have changed since we did our last restorecon
22051        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22052            if (StorageManager.isFileEncryptedNativeOrEmulated()
22053                    && !StorageManager.isUserKeyUnlocked(userId)) {
22054                throw new RuntimeException(
22055                        "Yikes, someone asked us to reconcile CE storage while " + userId
22056                                + " was still locked; this would have caused massive data loss!");
22057            }
22058
22059            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22060            for (File file : files) {
22061                final String packageName = file.getName();
22062                try {
22063                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22064                } catch (PackageManagerException e) {
22065                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22066                    try {
22067                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22068                                StorageManager.FLAG_STORAGE_CE, 0);
22069                    } catch (InstallerException e2) {
22070                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22071                    }
22072                }
22073            }
22074        }
22075        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22076            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22077            for (File file : files) {
22078                final String packageName = file.getName();
22079                try {
22080                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22081                } catch (PackageManagerException e) {
22082                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22083                    try {
22084                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22085                                StorageManager.FLAG_STORAGE_DE, 0);
22086                    } catch (InstallerException e2) {
22087                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22088                    }
22089                }
22090            }
22091        }
22092
22093        // Ensure that data directories are ready to roll for all packages
22094        // installed for this volume and user
22095        final List<PackageSetting> packages;
22096        synchronized (mPackages) {
22097            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22098        }
22099        int preparedCount = 0;
22100        for (PackageSetting ps : packages) {
22101            final String packageName = ps.name;
22102            if (ps.pkg == null) {
22103                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22104                // TODO: might be due to legacy ASEC apps; we should circle back
22105                // and reconcile again once they're scanned
22106                continue;
22107            }
22108            // Skip non-core apps if requested
22109            if (onlyCoreApps && !ps.pkg.coreApp) {
22110                result.add(packageName);
22111                continue;
22112            }
22113
22114            if (ps.getInstalled(userId)) {
22115                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22116                preparedCount++;
22117            }
22118        }
22119
22120        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22121        return result;
22122    }
22123
22124    /**
22125     * Prepare app data for the given app just after it was installed or
22126     * upgraded. This method carefully only touches users that it's installed
22127     * for, and it forces a restorecon to handle any seinfo changes.
22128     * <p>
22129     * Verifies that directories exist and that ownership and labeling is
22130     * correct for all installed apps. If there is an ownership mismatch, it
22131     * will try recovering system apps by wiping data; third-party app data is
22132     * left intact.
22133     * <p>
22134     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22135     */
22136    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22137        final PackageSetting ps;
22138        synchronized (mPackages) {
22139            ps = mSettings.mPackages.get(pkg.packageName);
22140            mSettings.writeKernelMappingLPr(ps);
22141        }
22142
22143        final UserManager um = mContext.getSystemService(UserManager.class);
22144        UserManagerInternal umInternal = getUserManagerInternal();
22145        for (UserInfo user : um.getUsers()) {
22146            final int flags;
22147            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22148                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22149            } else if (umInternal.isUserRunning(user.id)) {
22150                flags = StorageManager.FLAG_STORAGE_DE;
22151            } else {
22152                continue;
22153            }
22154
22155            if (ps.getInstalled(user.id)) {
22156                // TODO: when user data is locked, mark that we're still dirty
22157                prepareAppDataLIF(pkg, user.id, flags);
22158            }
22159        }
22160    }
22161
22162    /**
22163     * Prepare app data for the given app.
22164     * <p>
22165     * Verifies that directories exist and that ownership and labeling is
22166     * correct for all installed apps. If there is an ownership mismatch, this
22167     * will try recovering system apps by wiping data; third-party app data is
22168     * left intact.
22169     */
22170    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22171        if (pkg == null) {
22172            Slog.wtf(TAG, "Package was null!", new Throwable());
22173            return;
22174        }
22175        prepareAppDataLeafLIF(pkg, userId, flags);
22176        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22177        for (int i = 0; i < childCount; i++) {
22178            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22179        }
22180    }
22181
22182    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22183            boolean maybeMigrateAppData) {
22184        prepareAppDataLIF(pkg, userId, flags);
22185
22186        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22187            // We may have just shuffled around app data directories, so
22188            // prepare them one more time
22189            prepareAppDataLIF(pkg, userId, flags);
22190        }
22191    }
22192
22193    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22194        if (DEBUG_APP_DATA) {
22195            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22196                    + Integer.toHexString(flags));
22197        }
22198
22199        final String volumeUuid = pkg.volumeUuid;
22200        final String packageName = pkg.packageName;
22201        final ApplicationInfo app = pkg.applicationInfo;
22202        final int appId = UserHandle.getAppId(app.uid);
22203
22204        Preconditions.checkNotNull(app.seInfo);
22205
22206        long ceDataInode = -1;
22207        try {
22208            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22209                    appId, app.seInfo, app.targetSdkVersion);
22210        } catch (InstallerException e) {
22211            if (app.isSystemApp()) {
22212                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22213                        + ", but trying to recover: " + e);
22214                destroyAppDataLeafLIF(pkg, userId, flags);
22215                try {
22216                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22217                            appId, app.seInfo, app.targetSdkVersion);
22218                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22219                } catch (InstallerException e2) {
22220                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22221                }
22222            } else {
22223                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22224            }
22225        }
22226
22227        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22228            // TODO: mark this structure as dirty so we persist it!
22229            synchronized (mPackages) {
22230                final PackageSetting ps = mSettings.mPackages.get(packageName);
22231                if (ps != null) {
22232                    ps.setCeDataInode(ceDataInode, userId);
22233                }
22234            }
22235        }
22236
22237        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22238    }
22239
22240    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22241        if (pkg == null) {
22242            Slog.wtf(TAG, "Package was null!", new Throwable());
22243            return;
22244        }
22245        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22246        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22247        for (int i = 0; i < childCount; i++) {
22248            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22249        }
22250    }
22251
22252    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22253        final String volumeUuid = pkg.volumeUuid;
22254        final String packageName = pkg.packageName;
22255        final ApplicationInfo app = pkg.applicationInfo;
22256
22257        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22258            // Create a native library symlink only if we have native libraries
22259            // and if the native libraries are 32 bit libraries. We do not provide
22260            // this symlink for 64 bit libraries.
22261            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22262                final String nativeLibPath = app.nativeLibraryDir;
22263                try {
22264                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22265                            nativeLibPath, userId);
22266                } catch (InstallerException e) {
22267                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22268                }
22269            }
22270        }
22271    }
22272
22273    /**
22274     * For system apps on non-FBE devices, this method migrates any existing
22275     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22276     * requested by the app.
22277     */
22278    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22279        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22280                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22281            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22282                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22283            try {
22284                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22285                        storageTarget);
22286            } catch (InstallerException e) {
22287                logCriticalInfo(Log.WARN,
22288                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22289            }
22290            return true;
22291        } else {
22292            return false;
22293        }
22294    }
22295
22296    public PackageFreezer freezePackage(String packageName, String killReason) {
22297        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22298    }
22299
22300    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22301        return new PackageFreezer(packageName, userId, killReason);
22302    }
22303
22304    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22305            String killReason) {
22306        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22307    }
22308
22309    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22310            String killReason) {
22311        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22312            return new PackageFreezer();
22313        } else {
22314            return freezePackage(packageName, userId, killReason);
22315        }
22316    }
22317
22318    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22319            String killReason) {
22320        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22321    }
22322
22323    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22324            String killReason) {
22325        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22326            return new PackageFreezer();
22327        } else {
22328            return freezePackage(packageName, userId, killReason);
22329        }
22330    }
22331
22332    /**
22333     * Class that freezes and kills the given package upon creation, and
22334     * unfreezes it upon closing. This is typically used when doing surgery on
22335     * app code/data to prevent the app from running while you're working.
22336     */
22337    private class PackageFreezer implements AutoCloseable {
22338        private final String mPackageName;
22339        private final PackageFreezer[] mChildren;
22340
22341        private final boolean mWeFroze;
22342
22343        private final AtomicBoolean mClosed = new AtomicBoolean();
22344        private final CloseGuard mCloseGuard = CloseGuard.get();
22345
22346        /**
22347         * Create and return a stub freezer that doesn't actually do anything,
22348         * typically used when someone requested
22349         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22350         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22351         */
22352        public PackageFreezer() {
22353            mPackageName = null;
22354            mChildren = null;
22355            mWeFroze = false;
22356            mCloseGuard.open("close");
22357        }
22358
22359        public PackageFreezer(String packageName, int userId, String killReason) {
22360            synchronized (mPackages) {
22361                mPackageName = packageName;
22362                mWeFroze = mFrozenPackages.add(mPackageName);
22363
22364                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22365                if (ps != null) {
22366                    killApplication(ps.name, ps.appId, userId, killReason);
22367                }
22368
22369                final PackageParser.Package p = mPackages.get(packageName);
22370                if (p != null && p.childPackages != null) {
22371                    final int N = p.childPackages.size();
22372                    mChildren = new PackageFreezer[N];
22373                    for (int i = 0; i < N; i++) {
22374                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22375                                userId, killReason);
22376                    }
22377                } else {
22378                    mChildren = null;
22379                }
22380            }
22381            mCloseGuard.open("close");
22382        }
22383
22384        @Override
22385        protected void finalize() throws Throwable {
22386            try {
22387                mCloseGuard.warnIfOpen();
22388                close();
22389            } finally {
22390                super.finalize();
22391            }
22392        }
22393
22394        @Override
22395        public void close() {
22396            mCloseGuard.close();
22397            if (mClosed.compareAndSet(false, true)) {
22398                synchronized (mPackages) {
22399                    if (mWeFroze) {
22400                        mFrozenPackages.remove(mPackageName);
22401                    }
22402
22403                    if (mChildren != null) {
22404                        for (PackageFreezer freezer : mChildren) {
22405                            freezer.close();
22406                        }
22407                    }
22408                }
22409            }
22410        }
22411    }
22412
22413    /**
22414     * Verify that given package is currently frozen.
22415     */
22416    private void checkPackageFrozen(String packageName) {
22417        synchronized (mPackages) {
22418            if (!mFrozenPackages.contains(packageName)) {
22419                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22420            }
22421        }
22422    }
22423
22424    @Override
22425    public int movePackage(final String packageName, final String volumeUuid) {
22426        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22427
22428        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22429        final int moveId = mNextMoveId.getAndIncrement();
22430        mHandler.post(new Runnable() {
22431            @Override
22432            public void run() {
22433                try {
22434                    movePackageInternal(packageName, volumeUuid, moveId, user);
22435                } catch (PackageManagerException e) {
22436                    Slog.w(TAG, "Failed to move " + packageName, e);
22437                    mMoveCallbacks.notifyStatusChanged(moveId,
22438                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22439                }
22440            }
22441        });
22442        return moveId;
22443    }
22444
22445    private void movePackageInternal(final String packageName, final String volumeUuid,
22446            final int moveId, UserHandle user) throws PackageManagerException {
22447        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22448        final PackageManager pm = mContext.getPackageManager();
22449
22450        final boolean currentAsec;
22451        final String currentVolumeUuid;
22452        final File codeFile;
22453        final String installerPackageName;
22454        final String packageAbiOverride;
22455        final int appId;
22456        final String seinfo;
22457        final String label;
22458        final int targetSdkVersion;
22459        final PackageFreezer freezer;
22460        final int[] installedUserIds;
22461
22462        // reader
22463        synchronized (mPackages) {
22464            final PackageParser.Package pkg = mPackages.get(packageName);
22465            final PackageSetting ps = mSettings.mPackages.get(packageName);
22466            if (pkg == null || ps == null) {
22467                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22468            }
22469
22470            if (pkg.applicationInfo.isSystemApp()) {
22471                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22472                        "Cannot move system application");
22473            }
22474
22475            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22476            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22477                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22478            if (isInternalStorage && !allow3rdPartyOnInternal) {
22479                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22480                        "3rd party apps are not allowed on internal storage");
22481            }
22482
22483            if (pkg.applicationInfo.isExternalAsec()) {
22484                currentAsec = true;
22485                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22486            } else if (pkg.applicationInfo.isForwardLocked()) {
22487                currentAsec = true;
22488                currentVolumeUuid = "forward_locked";
22489            } else {
22490                currentAsec = false;
22491                currentVolumeUuid = ps.volumeUuid;
22492
22493                final File probe = new File(pkg.codePath);
22494                final File probeOat = new File(probe, "oat");
22495                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22496                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22497                            "Move only supported for modern cluster style installs");
22498                }
22499            }
22500
22501            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22502                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22503                        "Package already moved to " + volumeUuid);
22504            }
22505            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22506                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22507                        "Device admin cannot be moved");
22508            }
22509
22510            if (mFrozenPackages.contains(packageName)) {
22511                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22512                        "Failed to move already frozen package");
22513            }
22514
22515            codeFile = new File(pkg.codePath);
22516            installerPackageName = ps.installerPackageName;
22517            packageAbiOverride = ps.cpuAbiOverrideString;
22518            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22519            seinfo = pkg.applicationInfo.seInfo;
22520            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22521            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22522            freezer = freezePackage(packageName, "movePackageInternal");
22523            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22524        }
22525
22526        final Bundle extras = new Bundle();
22527        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22528        extras.putString(Intent.EXTRA_TITLE, label);
22529        mMoveCallbacks.notifyCreated(moveId, extras);
22530
22531        int installFlags;
22532        final boolean moveCompleteApp;
22533        final File measurePath;
22534
22535        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22536            installFlags = INSTALL_INTERNAL;
22537            moveCompleteApp = !currentAsec;
22538            measurePath = Environment.getDataAppDirectory(volumeUuid);
22539        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22540            installFlags = INSTALL_EXTERNAL;
22541            moveCompleteApp = false;
22542            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22543        } else {
22544            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22545            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22546                    || !volume.isMountedWritable()) {
22547                freezer.close();
22548                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22549                        "Move location not mounted private volume");
22550            }
22551
22552            Preconditions.checkState(!currentAsec);
22553
22554            installFlags = INSTALL_INTERNAL;
22555            moveCompleteApp = true;
22556            measurePath = Environment.getDataAppDirectory(volumeUuid);
22557        }
22558
22559        final PackageStats stats = new PackageStats(null, -1);
22560        synchronized (mInstaller) {
22561            for (int userId : installedUserIds) {
22562                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22563                    freezer.close();
22564                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22565                            "Failed to measure package size");
22566                }
22567            }
22568        }
22569
22570        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22571                + stats.dataSize);
22572
22573        final long startFreeBytes = measurePath.getUsableSpace();
22574        final long sizeBytes;
22575        if (moveCompleteApp) {
22576            sizeBytes = stats.codeSize + stats.dataSize;
22577        } else {
22578            sizeBytes = stats.codeSize;
22579        }
22580
22581        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22582            freezer.close();
22583            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22584                    "Not enough free space to move");
22585        }
22586
22587        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22588
22589        final CountDownLatch installedLatch = new CountDownLatch(1);
22590        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22591            @Override
22592            public void onUserActionRequired(Intent intent) throws RemoteException {
22593                throw new IllegalStateException();
22594            }
22595
22596            @Override
22597            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22598                    Bundle extras) throws RemoteException {
22599                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22600                        + PackageManager.installStatusToString(returnCode, msg));
22601
22602                installedLatch.countDown();
22603                freezer.close();
22604
22605                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22606                switch (status) {
22607                    case PackageInstaller.STATUS_SUCCESS:
22608                        mMoveCallbacks.notifyStatusChanged(moveId,
22609                                PackageManager.MOVE_SUCCEEDED);
22610                        break;
22611                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22612                        mMoveCallbacks.notifyStatusChanged(moveId,
22613                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22614                        break;
22615                    default:
22616                        mMoveCallbacks.notifyStatusChanged(moveId,
22617                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22618                        break;
22619                }
22620            }
22621        };
22622
22623        final MoveInfo move;
22624        if (moveCompleteApp) {
22625            // Kick off a thread to report progress estimates
22626            new Thread() {
22627                @Override
22628                public void run() {
22629                    while (true) {
22630                        try {
22631                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22632                                break;
22633                            }
22634                        } catch (InterruptedException ignored) {
22635                        }
22636
22637                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22638                        final int progress = 10 + (int) MathUtils.constrain(
22639                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22640                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22641                    }
22642                }
22643            }.start();
22644
22645            final String dataAppName = codeFile.getName();
22646            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22647                    dataAppName, appId, seinfo, targetSdkVersion);
22648        } else {
22649            move = null;
22650        }
22651
22652        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22653
22654        final Message msg = mHandler.obtainMessage(INIT_COPY);
22655        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22656        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22657                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22658                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22659                PackageManager.INSTALL_REASON_UNKNOWN);
22660        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22661        msg.obj = params;
22662
22663        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22664                System.identityHashCode(msg.obj));
22665        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22666                System.identityHashCode(msg.obj));
22667
22668        mHandler.sendMessage(msg);
22669    }
22670
22671    @Override
22672    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22673        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22674
22675        final int realMoveId = mNextMoveId.getAndIncrement();
22676        final Bundle extras = new Bundle();
22677        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22678        mMoveCallbacks.notifyCreated(realMoveId, extras);
22679
22680        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22681            @Override
22682            public void onCreated(int moveId, Bundle extras) {
22683                // Ignored
22684            }
22685
22686            @Override
22687            public void onStatusChanged(int moveId, int status, long estMillis) {
22688                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22689            }
22690        };
22691
22692        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22693        storage.setPrimaryStorageUuid(volumeUuid, callback);
22694        return realMoveId;
22695    }
22696
22697    @Override
22698    public int getMoveStatus(int moveId) {
22699        mContext.enforceCallingOrSelfPermission(
22700                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22701        return mMoveCallbacks.mLastStatus.get(moveId);
22702    }
22703
22704    @Override
22705    public void registerMoveCallback(IPackageMoveObserver callback) {
22706        mContext.enforceCallingOrSelfPermission(
22707                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22708        mMoveCallbacks.register(callback);
22709    }
22710
22711    @Override
22712    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22713        mContext.enforceCallingOrSelfPermission(
22714                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22715        mMoveCallbacks.unregister(callback);
22716    }
22717
22718    @Override
22719    public boolean setInstallLocation(int loc) {
22720        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22721                null);
22722        if (getInstallLocation() == loc) {
22723            return true;
22724        }
22725        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22726                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22727            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22728                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22729            return true;
22730        }
22731        return false;
22732   }
22733
22734    @Override
22735    public int getInstallLocation() {
22736        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22737                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22738                PackageHelper.APP_INSTALL_AUTO);
22739    }
22740
22741    /** Called by UserManagerService */
22742    void cleanUpUser(UserManagerService userManager, int userHandle) {
22743        synchronized (mPackages) {
22744            mDirtyUsers.remove(userHandle);
22745            mUserNeedsBadging.delete(userHandle);
22746            mSettings.removeUserLPw(userHandle);
22747            mPendingBroadcasts.remove(userHandle);
22748            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22749            removeUnusedPackagesLPw(userManager, userHandle);
22750        }
22751    }
22752
22753    /**
22754     * We're removing userHandle and would like to remove any downloaded packages
22755     * that are no longer in use by any other user.
22756     * @param userHandle the user being removed
22757     */
22758    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22759        final boolean DEBUG_CLEAN_APKS = false;
22760        int [] users = userManager.getUserIds();
22761        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22762        while (psit.hasNext()) {
22763            PackageSetting ps = psit.next();
22764            if (ps.pkg == null) {
22765                continue;
22766            }
22767            final String packageName = ps.pkg.packageName;
22768            // Skip over if system app
22769            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22770                continue;
22771            }
22772            if (DEBUG_CLEAN_APKS) {
22773                Slog.i(TAG, "Checking package " + packageName);
22774            }
22775            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22776            if (keep) {
22777                if (DEBUG_CLEAN_APKS) {
22778                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22779                }
22780            } else {
22781                for (int i = 0; i < users.length; i++) {
22782                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22783                        keep = true;
22784                        if (DEBUG_CLEAN_APKS) {
22785                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22786                                    + users[i]);
22787                        }
22788                        break;
22789                    }
22790                }
22791            }
22792            if (!keep) {
22793                if (DEBUG_CLEAN_APKS) {
22794                    Slog.i(TAG, "  Removing package " + packageName);
22795                }
22796                mHandler.post(new Runnable() {
22797                    public void run() {
22798                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22799                                userHandle, 0);
22800                    } //end run
22801                });
22802            }
22803        }
22804    }
22805
22806    /** Called by UserManagerService */
22807    void createNewUser(int userId, String[] disallowedPackages) {
22808        synchronized (mInstallLock) {
22809            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22810        }
22811        synchronized (mPackages) {
22812            scheduleWritePackageRestrictionsLocked(userId);
22813            scheduleWritePackageListLocked(userId);
22814            applyFactoryDefaultBrowserLPw(userId);
22815            primeDomainVerificationsLPw(userId);
22816        }
22817    }
22818
22819    void onNewUserCreated(final int userId) {
22820        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22821        // If permission review for legacy apps is required, we represent
22822        // dagerous permissions for such apps as always granted runtime
22823        // permissions to keep per user flag state whether review is needed.
22824        // Hence, if a new user is added we have to propagate dangerous
22825        // permission grants for these legacy apps.
22826        if (mPermissionReviewRequired) {
22827            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22828                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22829        }
22830    }
22831
22832    @Override
22833    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22834        mContext.enforceCallingOrSelfPermission(
22835                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22836                "Only package verification agents can read the verifier device identity");
22837
22838        synchronized (mPackages) {
22839            return mSettings.getVerifierDeviceIdentityLPw();
22840        }
22841    }
22842
22843    @Override
22844    public void setPermissionEnforced(String permission, boolean enforced) {
22845        // TODO: Now that we no longer change GID for storage, this should to away.
22846        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22847                "setPermissionEnforced");
22848        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22849            synchronized (mPackages) {
22850                if (mSettings.mReadExternalStorageEnforced == null
22851                        || mSettings.mReadExternalStorageEnforced != enforced) {
22852                    mSettings.mReadExternalStorageEnforced = enforced;
22853                    mSettings.writeLPr();
22854                }
22855            }
22856            // kill any non-foreground processes so we restart them and
22857            // grant/revoke the GID.
22858            final IActivityManager am = ActivityManager.getService();
22859            if (am != null) {
22860                final long token = Binder.clearCallingIdentity();
22861                try {
22862                    am.killProcessesBelowForeground("setPermissionEnforcement");
22863                } catch (RemoteException e) {
22864                } finally {
22865                    Binder.restoreCallingIdentity(token);
22866                }
22867            }
22868        } else {
22869            throw new IllegalArgumentException("No selective enforcement for " + permission);
22870        }
22871    }
22872
22873    @Override
22874    @Deprecated
22875    public boolean isPermissionEnforced(String permission) {
22876        return true;
22877    }
22878
22879    @Override
22880    public boolean isStorageLow() {
22881        final long token = Binder.clearCallingIdentity();
22882        try {
22883            final DeviceStorageMonitorInternal
22884                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22885            if (dsm != null) {
22886                return dsm.isMemoryLow();
22887            } else {
22888                return false;
22889            }
22890        } finally {
22891            Binder.restoreCallingIdentity(token);
22892        }
22893    }
22894
22895    @Override
22896    public IPackageInstaller getPackageInstaller() {
22897        return mInstallerService;
22898    }
22899
22900    private boolean userNeedsBadging(int userId) {
22901        int index = mUserNeedsBadging.indexOfKey(userId);
22902        if (index < 0) {
22903            final UserInfo userInfo;
22904            final long token = Binder.clearCallingIdentity();
22905            try {
22906                userInfo = sUserManager.getUserInfo(userId);
22907            } finally {
22908                Binder.restoreCallingIdentity(token);
22909            }
22910            final boolean b;
22911            if (userInfo != null && userInfo.isManagedProfile()) {
22912                b = true;
22913            } else {
22914                b = false;
22915            }
22916            mUserNeedsBadging.put(userId, b);
22917            return b;
22918        }
22919        return mUserNeedsBadging.valueAt(index);
22920    }
22921
22922    @Override
22923    public KeySet getKeySetByAlias(String packageName, String alias) {
22924        if (packageName == null || alias == null) {
22925            return null;
22926        }
22927        synchronized(mPackages) {
22928            final PackageParser.Package pkg = mPackages.get(packageName);
22929            if (pkg == null) {
22930                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22931                throw new IllegalArgumentException("Unknown package: " + packageName);
22932            }
22933            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22934            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22935        }
22936    }
22937
22938    @Override
22939    public KeySet getSigningKeySet(String packageName) {
22940        if (packageName == null) {
22941            return null;
22942        }
22943        synchronized(mPackages) {
22944            final PackageParser.Package pkg = mPackages.get(packageName);
22945            if (pkg == null) {
22946                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22947                throw new IllegalArgumentException("Unknown package: " + packageName);
22948            }
22949            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22950                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22951                throw new SecurityException("May not access signing KeySet of other apps.");
22952            }
22953            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22954            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22955        }
22956    }
22957
22958    @Override
22959    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22960        if (packageName == null || ks == null) {
22961            return false;
22962        }
22963        synchronized(mPackages) {
22964            final PackageParser.Package pkg = mPackages.get(packageName);
22965            if (pkg == null) {
22966                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22967                throw new IllegalArgumentException("Unknown package: " + packageName);
22968            }
22969            IBinder ksh = ks.getToken();
22970            if (ksh instanceof KeySetHandle) {
22971                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22972                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22973            }
22974            return false;
22975        }
22976    }
22977
22978    @Override
22979    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22980        if (packageName == null || ks == null) {
22981            return false;
22982        }
22983        synchronized(mPackages) {
22984            final PackageParser.Package pkg = mPackages.get(packageName);
22985            if (pkg == null) {
22986                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22987                throw new IllegalArgumentException("Unknown package: " + packageName);
22988            }
22989            IBinder ksh = ks.getToken();
22990            if (ksh instanceof KeySetHandle) {
22991                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22992                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22993            }
22994            return false;
22995        }
22996    }
22997
22998    private void deletePackageIfUnusedLPr(final String packageName) {
22999        PackageSetting ps = mSettings.mPackages.get(packageName);
23000        if (ps == null) {
23001            return;
23002        }
23003        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23004            // TODO Implement atomic delete if package is unused
23005            // It is currently possible that the package will be deleted even if it is installed
23006            // after this method returns.
23007            mHandler.post(new Runnable() {
23008                public void run() {
23009                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23010                            0, PackageManager.DELETE_ALL_USERS);
23011                }
23012            });
23013        }
23014    }
23015
23016    /**
23017     * Check and throw if the given before/after packages would be considered a
23018     * downgrade.
23019     */
23020    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23021            throws PackageManagerException {
23022        if (after.versionCode < before.mVersionCode) {
23023            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23024                    "Update version code " + after.versionCode + " is older than current "
23025                    + before.mVersionCode);
23026        } else if (after.versionCode == before.mVersionCode) {
23027            if (after.baseRevisionCode < before.baseRevisionCode) {
23028                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23029                        "Update base revision code " + after.baseRevisionCode
23030                        + " is older than current " + before.baseRevisionCode);
23031            }
23032
23033            if (!ArrayUtils.isEmpty(after.splitNames)) {
23034                for (int i = 0; i < after.splitNames.length; i++) {
23035                    final String splitName = after.splitNames[i];
23036                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23037                    if (j != -1) {
23038                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23039                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23040                                    "Update split " + splitName + " revision code "
23041                                    + after.splitRevisionCodes[i] + " is older than current "
23042                                    + before.splitRevisionCodes[j]);
23043                        }
23044                    }
23045                }
23046            }
23047        }
23048    }
23049
23050    private static class MoveCallbacks extends Handler {
23051        private static final int MSG_CREATED = 1;
23052        private static final int MSG_STATUS_CHANGED = 2;
23053
23054        private final RemoteCallbackList<IPackageMoveObserver>
23055                mCallbacks = new RemoteCallbackList<>();
23056
23057        private final SparseIntArray mLastStatus = new SparseIntArray();
23058
23059        public MoveCallbacks(Looper looper) {
23060            super(looper);
23061        }
23062
23063        public void register(IPackageMoveObserver callback) {
23064            mCallbacks.register(callback);
23065        }
23066
23067        public void unregister(IPackageMoveObserver callback) {
23068            mCallbacks.unregister(callback);
23069        }
23070
23071        @Override
23072        public void handleMessage(Message msg) {
23073            final SomeArgs args = (SomeArgs) msg.obj;
23074            final int n = mCallbacks.beginBroadcast();
23075            for (int i = 0; i < n; i++) {
23076                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23077                try {
23078                    invokeCallback(callback, msg.what, args);
23079                } catch (RemoteException ignored) {
23080                }
23081            }
23082            mCallbacks.finishBroadcast();
23083            args.recycle();
23084        }
23085
23086        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23087                throws RemoteException {
23088            switch (what) {
23089                case MSG_CREATED: {
23090                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23091                    break;
23092                }
23093                case MSG_STATUS_CHANGED: {
23094                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23095                    break;
23096                }
23097            }
23098        }
23099
23100        private void notifyCreated(int moveId, Bundle extras) {
23101            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23102
23103            final SomeArgs args = SomeArgs.obtain();
23104            args.argi1 = moveId;
23105            args.arg2 = extras;
23106            obtainMessage(MSG_CREATED, args).sendToTarget();
23107        }
23108
23109        private void notifyStatusChanged(int moveId, int status) {
23110            notifyStatusChanged(moveId, status, -1);
23111        }
23112
23113        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23114            Slog.v(TAG, "Move " + moveId + " status " + status);
23115
23116            final SomeArgs args = SomeArgs.obtain();
23117            args.argi1 = moveId;
23118            args.argi2 = status;
23119            args.arg3 = estMillis;
23120            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23121
23122            synchronized (mLastStatus) {
23123                mLastStatus.put(moveId, status);
23124            }
23125        }
23126    }
23127
23128    private final static class OnPermissionChangeListeners extends Handler {
23129        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23130
23131        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23132                new RemoteCallbackList<>();
23133
23134        public OnPermissionChangeListeners(Looper looper) {
23135            super(looper);
23136        }
23137
23138        @Override
23139        public void handleMessage(Message msg) {
23140            switch (msg.what) {
23141                case MSG_ON_PERMISSIONS_CHANGED: {
23142                    final int uid = msg.arg1;
23143                    handleOnPermissionsChanged(uid);
23144                } break;
23145            }
23146        }
23147
23148        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23149            mPermissionListeners.register(listener);
23150
23151        }
23152
23153        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23154            mPermissionListeners.unregister(listener);
23155        }
23156
23157        public void onPermissionsChanged(int uid) {
23158            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23159                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23160            }
23161        }
23162
23163        private void handleOnPermissionsChanged(int uid) {
23164            final int count = mPermissionListeners.beginBroadcast();
23165            try {
23166                for (int i = 0; i < count; i++) {
23167                    IOnPermissionsChangeListener callback = mPermissionListeners
23168                            .getBroadcastItem(i);
23169                    try {
23170                        callback.onPermissionsChanged(uid);
23171                    } catch (RemoteException e) {
23172                        Log.e(TAG, "Permission listener is dead", e);
23173                    }
23174                }
23175            } finally {
23176                mPermissionListeners.finishBroadcast();
23177            }
23178        }
23179    }
23180
23181    private class PackageManagerInternalImpl extends PackageManagerInternal {
23182        @Override
23183        public void setLocationPackagesProvider(PackagesProvider provider) {
23184            synchronized (mPackages) {
23185                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23186            }
23187        }
23188
23189        @Override
23190        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23191            synchronized (mPackages) {
23192                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23193            }
23194        }
23195
23196        @Override
23197        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23198            synchronized (mPackages) {
23199                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23200            }
23201        }
23202
23203        @Override
23204        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23205            synchronized (mPackages) {
23206                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23207            }
23208        }
23209
23210        @Override
23211        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23212            synchronized (mPackages) {
23213                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23214            }
23215        }
23216
23217        @Override
23218        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23219            synchronized (mPackages) {
23220                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23221            }
23222        }
23223
23224        @Override
23225        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23226            synchronized (mPackages) {
23227                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23228                        packageName, userId);
23229            }
23230        }
23231
23232        @Override
23233        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23234            synchronized (mPackages) {
23235                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23236                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23237                        packageName, userId);
23238            }
23239        }
23240
23241        @Override
23242        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23243            synchronized (mPackages) {
23244                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23245                        packageName, userId);
23246            }
23247        }
23248
23249        @Override
23250        public void setKeepUninstalledPackages(final List<String> packageList) {
23251            Preconditions.checkNotNull(packageList);
23252            List<String> removedFromList = null;
23253            synchronized (mPackages) {
23254                if (mKeepUninstalledPackages != null) {
23255                    final int packagesCount = mKeepUninstalledPackages.size();
23256                    for (int i = 0; i < packagesCount; i++) {
23257                        String oldPackage = mKeepUninstalledPackages.get(i);
23258                        if (packageList != null && packageList.contains(oldPackage)) {
23259                            continue;
23260                        }
23261                        if (removedFromList == null) {
23262                            removedFromList = new ArrayList<>();
23263                        }
23264                        removedFromList.add(oldPackage);
23265                    }
23266                }
23267                mKeepUninstalledPackages = new ArrayList<>(packageList);
23268                if (removedFromList != null) {
23269                    final int removedCount = removedFromList.size();
23270                    for (int i = 0; i < removedCount; i++) {
23271                        deletePackageIfUnusedLPr(removedFromList.get(i));
23272                    }
23273                }
23274            }
23275        }
23276
23277        @Override
23278        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23279            synchronized (mPackages) {
23280                // If we do not support permission review, done.
23281                if (!mPermissionReviewRequired) {
23282                    return false;
23283                }
23284
23285                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23286                if (packageSetting == null) {
23287                    return false;
23288                }
23289
23290                // Permission review applies only to apps not supporting the new permission model.
23291                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23292                    return false;
23293                }
23294
23295                // Legacy apps have the permission and get user consent on launch.
23296                PermissionsState permissionsState = packageSetting.getPermissionsState();
23297                return permissionsState.isPermissionReviewRequired(userId);
23298            }
23299        }
23300
23301        @Override
23302        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23303            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23304        }
23305
23306        @Override
23307        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23308                int userId) {
23309            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23310        }
23311
23312        @Override
23313        public void setDeviceAndProfileOwnerPackages(
23314                int deviceOwnerUserId, String deviceOwnerPackage,
23315                SparseArray<String> profileOwnerPackages) {
23316            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23317                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23318        }
23319
23320        @Override
23321        public boolean isPackageDataProtected(int userId, String packageName) {
23322            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23323        }
23324
23325        @Override
23326        public boolean isPackageEphemeral(int userId, String packageName) {
23327            synchronized (mPackages) {
23328                final PackageSetting ps = mSettings.mPackages.get(packageName);
23329                return ps != null ? ps.getInstantApp(userId) : false;
23330            }
23331        }
23332
23333        @Override
23334        public boolean wasPackageEverLaunched(String packageName, int userId) {
23335            synchronized (mPackages) {
23336                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23337            }
23338        }
23339
23340        @Override
23341        public void grantRuntimePermission(String packageName, String name, int userId,
23342                boolean overridePolicy) {
23343            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23344                    overridePolicy);
23345        }
23346
23347        @Override
23348        public void revokeRuntimePermission(String packageName, String name, int userId,
23349                boolean overridePolicy) {
23350            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23351                    overridePolicy);
23352        }
23353
23354        @Override
23355        public String getNameForUid(int uid) {
23356            return PackageManagerService.this.getNameForUid(uid);
23357        }
23358
23359        @Override
23360        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23361                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23362            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23363                    responseObj, origIntent, resolvedType, callingPackage, userId);
23364        }
23365
23366        @Override
23367        public void grantEphemeralAccess(int userId, Intent intent,
23368                int targetAppId, int ephemeralAppId) {
23369            synchronized (mPackages) {
23370                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23371                        targetAppId, ephemeralAppId);
23372            }
23373        }
23374
23375        @Override
23376        public boolean isInstantAppInstallerComponent(ComponentName component) {
23377            synchronized (mPackages) {
23378                return mInstantAppInstallerActivity != null
23379                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23380            }
23381        }
23382
23383        @Override
23384        public void pruneInstantApps() {
23385            synchronized (mPackages) {
23386                mInstantAppRegistry.pruneInstantAppsLPw();
23387            }
23388        }
23389
23390        @Override
23391        public String getSetupWizardPackageName() {
23392            return mSetupWizardPackage;
23393        }
23394
23395        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23396            if (policy != null) {
23397                mExternalSourcesPolicy = policy;
23398            }
23399        }
23400
23401        @Override
23402        public boolean isPackagePersistent(String packageName) {
23403            synchronized (mPackages) {
23404                PackageParser.Package pkg = mPackages.get(packageName);
23405                return pkg != null
23406                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23407                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23408                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23409                        : false;
23410            }
23411        }
23412
23413        @Override
23414        public List<PackageInfo> getOverlayPackages(int userId) {
23415            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23416            synchronized (mPackages) {
23417                for (PackageParser.Package p : mPackages.values()) {
23418                    if (p.mOverlayTarget != null) {
23419                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23420                        if (pkg != null) {
23421                            overlayPackages.add(pkg);
23422                        }
23423                    }
23424                }
23425            }
23426            return overlayPackages;
23427        }
23428
23429        @Override
23430        public List<String> getTargetPackageNames(int userId) {
23431            List<String> targetPackages = new ArrayList<>();
23432            synchronized (mPackages) {
23433                for (PackageParser.Package p : mPackages.values()) {
23434                    if (p.mOverlayTarget == null) {
23435                        targetPackages.add(p.packageName);
23436                    }
23437                }
23438            }
23439            return targetPackages;
23440        }
23441
23442        @Override
23443        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23444                @Nullable List<String> overlayPackageNames) {
23445            synchronized (mPackages) {
23446                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23447                    Slog.e(TAG, "failed to find package " + targetPackageName);
23448                    return false;
23449                }
23450
23451                ArrayList<String> paths = null;
23452                if (overlayPackageNames != null) {
23453                    final int N = overlayPackageNames.size();
23454                    paths = new ArrayList<>(N);
23455                    for (int i = 0; i < N; i++) {
23456                        final String packageName = overlayPackageNames.get(i);
23457                        final PackageParser.Package pkg = mPackages.get(packageName);
23458                        if (pkg == null) {
23459                            Slog.e(TAG, "failed to find package " + packageName);
23460                            return false;
23461                        }
23462                        paths.add(pkg.baseCodePath);
23463                    }
23464                }
23465
23466                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23467                    mEnabledOverlayPaths.get(userId);
23468                if (userSpecificOverlays == null) {
23469                    userSpecificOverlays = new ArrayMap<>();
23470                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23471                }
23472
23473                if (paths != null && paths.size() > 0) {
23474                    userSpecificOverlays.put(targetPackageName, paths);
23475                } else {
23476                    userSpecificOverlays.remove(targetPackageName);
23477                }
23478                return true;
23479            }
23480        }
23481
23482        @Override
23483        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23484                int flags, int userId) {
23485            return resolveIntentInternal(
23486                    intent, resolvedType, flags, userId, true /*includeInstantApps*/);
23487        }
23488
23489        @Override
23490        public ResolveInfo resolveService(Intent intent, String resolvedType,
23491                int flags, int userId, int callingUid) {
23492            return resolveServiceInternal(
23493                    intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/);
23494        }
23495
23496        @Override
23497        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23498            synchronized (mPackages) {
23499                mIsolatedOwners.put(isolatedUid, ownerUid);
23500            }
23501        }
23502
23503        @Override
23504        public void removeIsolatedUid(int isolatedUid) {
23505            synchronized (mPackages) {
23506                mIsolatedOwners.delete(isolatedUid);
23507            }
23508        }
23509    }
23510
23511    @Override
23512    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23513        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23514        synchronized (mPackages) {
23515            final long identity = Binder.clearCallingIdentity();
23516            try {
23517                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23518                        packageNames, userId);
23519            } finally {
23520                Binder.restoreCallingIdentity(identity);
23521            }
23522        }
23523    }
23524
23525    @Override
23526    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23527        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23528        synchronized (mPackages) {
23529            final long identity = Binder.clearCallingIdentity();
23530            try {
23531                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23532                        packageNames, userId);
23533            } finally {
23534                Binder.restoreCallingIdentity(identity);
23535            }
23536        }
23537    }
23538
23539    private static void enforceSystemOrPhoneCaller(String tag) {
23540        int callingUid = Binder.getCallingUid();
23541        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23542            throw new SecurityException(
23543                    "Cannot call " + tag + " from UID " + callingUid);
23544        }
23545    }
23546
23547    boolean isHistoricalPackageUsageAvailable() {
23548        return mPackageUsage.isHistoricalPackageUsageAvailable();
23549    }
23550
23551    /**
23552     * Return a <b>copy</b> of the collection of packages known to the package manager.
23553     * @return A copy of the values of mPackages.
23554     */
23555    Collection<PackageParser.Package> getPackages() {
23556        synchronized (mPackages) {
23557            return new ArrayList<>(mPackages.values());
23558        }
23559    }
23560
23561    /**
23562     * Logs process start information (including base APK hash) to the security log.
23563     * @hide
23564     */
23565    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23566            String apkFile, int pid) {
23567        if (!SecurityLog.isLoggingEnabled()) {
23568            return;
23569        }
23570        Bundle data = new Bundle();
23571        data.putLong("startTimestamp", System.currentTimeMillis());
23572        data.putString("processName", processName);
23573        data.putInt("uid", uid);
23574        data.putString("seinfo", seinfo);
23575        data.putString("apkFile", apkFile);
23576        data.putInt("pid", pid);
23577        Message msg = mProcessLoggingHandler.obtainMessage(
23578                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23579        msg.setData(data);
23580        mProcessLoggingHandler.sendMessage(msg);
23581    }
23582
23583    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23584        return mCompilerStats.getPackageStats(pkgName);
23585    }
23586
23587    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23588        return getOrCreateCompilerPackageStats(pkg.packageName);
23589    }
23590
23591    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23592        return mCompilerStats.getOrCreatePackageStats(pkgName);
23593    }
23594
23595    public void deleteCompilerPackageStats(String pkgName) {
23596        mCompilerStats.deletePackageStats(pkgName);
23597    }
23598
23599    @Override
23600    public int getInstallReason(String packageName, int userId) {
23601        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23602                true /* requireFullPermission */, false /* checkShell */,
23603                "get install reason");
23604        synchronized (mPackages) {
23605            final PackageSetting ps = mSettings.mPackages.get(packageName);
23606            if (ps != null) {
23607                return ps.getInstallReason(userId);
23608            }
23609        }
23610        return PackageManager.INSTALL_REASON_UNKNOWN;
23611    }
23612
23613    @Override
23614    public boolean canRequestPackageInstalls(String packageName, int userId) {
23615        int callingUid = Binder.getCallingUid();
23616        int uid = getPackageUid(packageName, 0, userId);
23617        if (callingUid != uid && callingUid != Process.ROOT_UID
23618                && callingUid != Process.SYSTEM_UID) {
23619            throw new SecurityException(
23620                    "Caller uid " + callingUid + " does not own package " + packageName);
23621        }
23622        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23623        if (info == null) {
23624            return false;
23625        }
23626        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23627            throw new UnsupportedOperationException(
23628                    "Operation only supported on apps targeting Android O or higher");
23629        }
23630        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23631        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23632        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23633            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23634        }
23635        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23636            return false;
23637        }
23638        if (mExternalSourcesPolicy != null) {
23639            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23640            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23641                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23642            }
23643        }
23644        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23645    }
23646
23647    @Override
23648    public ComponentName getInstantAppResolverSettingsComponent() {
23649        return mInstantAppResolverSettingsComponent;
23650    }
23651
23652    @Override
23653    public ComponentName getInstantAppInstallerComponent() {
23654        return mInstantAppInstallerActivity == null
23655                ? null : mInstantAppInstallerActivity.getComponentName();
23656    }
23657
23658    @Override
23659    public String getInstantAppAndroidId(String packageName, int userId) {
23660        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23661                "getInstantAppAndroidId");
23662        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23663                true /* requireFullPermission */, false /* checkShell */,
23664                "getInstantAppAndroidId");
23665        // Make sure the target is an Instant App.
23666        if (!isInstantApp(packageName, userId)) {
23667            return null;
23668        }
23669        synchronized (mPackages) {
23670            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23671        }
23672    }
23673}
23674
23675interface PackageSender {
23676    void sendPackageBroadcast(final String action, final String pkg,
23677        final Bundle extras, final int flags, final String targetPkg,
23678        final IIntentReceiver finishedReceiver, final int[] userIds);
23679    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
23680        int appId, int... userIds);
23681}
23682