PackageManagerService.java revision e61b60115f3b08535ebc94e57b62ddd8a3f7de0f
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    static final String TAG = "PackageManager";
369    static final boolean DEBUG_SETTINGS = false;
370    static final boolean DEBUG_PREFERRED = false;
371    static final boolean DEBUG_UPGRADE = false;
372    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
373    private static final boolean DEBUG_BACKUP = false;
374    private static final boolean DEBUG_INSTALL = false;
375    private static final boolean DEBUG_REMOVE = false;
376    private static final boolean DEBUG_BROADCASTS = false;
377    private static final boolean DEBUG_SHOW_INFO = false;
378    private static final boolean DEBUG_PACKAGE_INFO = false;
379    private static final boolean DEBUG_INTENT_MATCHING = false;
380    private static final boolean DEBUG_PACKAGE_SCANNING = false;
381    private static final boolean DEBUG_VERIFY = false;
382    private static final boolean DEBUG_FILTERS = false;
383
384    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
385    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
386    // user, but by default initialize to this.
387    public static final boolean DEBUG_DEXOPT = false;
388
389    private static final boolean DEBUG_ABI_SELECTION = false;
390    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
391    private static final boolean DEBUG_TRIAGED_MISSING = false;
392    private static final boolean DEBUG_APP_DATA = false;
393
394    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
395    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
396
397    private static final boolean HIDE_EPHEMERAL_APIS = false;
398
399    private static final boolean ENABLE_FREE_CACHE_V2 =
400            SystemProperties.getBoolean("fw.free_cache_v2", true);
401
402    private static final int RADIO_UID = Process.PHONE_UID;
403    private static final int LOG_UID = Process.LOG_UID;
404    private static final int NFC_UID = Process.NFC_UID;
405    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
406    private static final int SHELL_UID = Process.SHELL_UID;
407
408    // Cap the size of permission trees that 3rd party apps can define
409    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
410
411    // Suffix used during package installation when copying/moving
412    // package apks to install directory.
413    private static final String INSTALL_PACKAGE_SUFFIX = "-";
414
415    static final int SCAN_NO_DEX = 1<<1;
416    static final int SCAN_FORCE_DEX = 1<<2;
417    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
418    static final int SCAN_NEW_INSTALL = 1<<4;
419    static final int SCAN_UPDATE_TIME = 1<<5;
420    static final int SCAN_BOOTING = 1<<6;
421    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
422    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
423    static final int SCAN_REPLACING = 1<<9;
424    static final int SCAN_REQUIRE_KNOWN = 1<<10;
425    static final int SCAN_MOVE = 1<<11;
426    static final int SCAN_INITIAL = 1<<12;
427    static final int SCAN_CHECK_ONLY = 1<<13;
428    static final int SCAN_DONT_KILL_APP = 1<<14;
429    static final int SCAN_IGNORE_FROZEN = 1<<15;
430    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
431    static final int SCAN_AS_INSTANT_APP = 1<<17;
432    static final int SCAN_AS_FULL_APP = 1<<18;
433    /** Should not be with the scan flags */
434    static final int FLAGS_REMOVE_CHATTY = 1<<31;
435
436    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
437
438    private static final int[] EMPTY_INT_ARRAY = new int[0];
439
440    /**
441     * Timeout (in milliseconds) after which the watchdog should declare that
442     * our handler thread is wedged.  The usual default for such things is one
443     * minute but we sometimes do very lengthy I/O operations on this thread,
444     * such as installing multi-gigabyte applications, so ours needs to be longer.
445     */
446    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
447
448    /**
449     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
450     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
451     * settings entry if available, otherwise we use the hardcoded default.  If it's been
452     * more than this long since the last fstrim, we force one during the boot sequence.
453     *
454     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
455     * one gets run at the next available charging+idle time.  This final mandatory
456     * no-fstrim check kicks in only of the other scheduling criteria is never met.
457     */
458    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
459
460    /**
461     * Whether verification is enabled by default.
462     */
463    private static final boolean DEFAULT_VERIFY_ENABLE = true;
464
465    /**
466     * The default maximum time to wait for the verification agent to return in
467     * milliseconds.
468     */
469    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
470
471    /**
472     * The default response for package verification timeout.
473     *
474     * This can be either PackageManager.VERIFICATION_ALLOW or
475     * PackageManager.VERIFICATION_REJECT.
476     */
477    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
478
479    static final String PLATFORM_PACKAGE_NAME = "android";
480
481    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
482
483    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
484            DEFAULT_CONTAINER_PACKAGE,
485            "com.android.defcontainer.DefaultContainerService");
486
487    private static final String KILL_APP_REASON_GIDS_CHANGED =
488            "permission grant or revoke changed gids";
489
490    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
491            "permissions revoked";
492
493    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
494
495    private static final String PACKAGE_SCHEME = "package";
496
497    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
498
499    /** Permission grant: not grant the permission. */
500    private static final int GRANT_DENIED = 1;
501
502    /** Permission grant: grant the permission as an install permission. */
503    private static final int GRANT_INSTALL = 2;
504
505    /** Permission grant: grant the permission as a runtime one. */
506    private static final int GRANT_RUNTIME = 3;
507
508    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
509    private static final int GRANT_UPGRADE = 4;
510
511    /** Canonical intent used to identify what counts as a "web browser" app */
512    private static final Intent sBrowserIntent;
513    static {
514        sBrowserIntent = new Intent();
515        sBrowserIntent.setAction(Intent.ACTION_VIEW);
516        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
517        sBrowserIntent.setData(Uri.parse("http:"));
518    }
519
520    /**
521     * The set of all protected actions [i.e. those actions for which a high priority
522     * intent filter is disallowed].
523     */
524    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
525    static {
526        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
527        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
528        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
529        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
530    }
531
532    // Compilation reasons.
533    public static final int REASON_FIRST_BOOT = 0;
534    public static final int REASON_BOOT = 1;
535    public static final int REASON_INSTALL = 2;
536    public static final int REASON_BACKGROUND_DEXOPT = 3;
537    public static final int REASON_AB_OTA = 4;
538    public static final int REASON_FORCED_DEXOPT = 5;
539
540    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
541
542    /** All dangerous permission names in the same order as the events in MetricsEvent */
543    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
544            Manifest.permission.READ_CALENDAR,
545            Manifest.permission.WRITE_CALENDAR,
546            Manifest.permission.CAMERA,
547            Manifest.permission.READ_CONTACTS,
548            Manifest.permission.WRITE_CONTACTS,
549            Manifest.permission.GET_ACCOUNTS,
550            Manifest.permission.ACCESS_FINE_LOCATION,
551            Manifest.permission.ACCESS_COARSE_LOCATION,
552            Manifest.permission.RECORD_AUDIO,
553            Manifest.permission.READ_PHONE_STATE,
554            Manifest.permission.CALL_PHONE,
555            Manifest.permission.READ_CALL_LOG,
556            Manifest.permission.WRITE_CALL_LOG,
557            Manifest.permission.ADD_VOICEMAIL,
558            Manifest.permission.USE_SIP,
559            Manifest.permission.PROCESS_OUTGOING_CALLS,
560            Manifest.permission.READ_CELL_BROADCASTS,
561            Manifest.permission.BODY_SENSORS,
562            Manifest.permission.SEND_SMS,
563            Manifest.permission.RECEIVE_SMS,
564            Manifest.permission.READ_SMS,
565            Manifest.permission.RECEIVE_WAP_PUSH,
566            Manifest.permission.RECEIVE_MMS,
567            Manifest.permission.READ_EXTERNAL_STORAGE,
568            Manifest.permission.WRITE_EXTERNAL_STORAGE,
569            Manifest.permission.READ_PHONE_NUMBERS,
570            Manifest.permission.ANSWER_PHONE_CALLS);
571
572
573    /**
574     * Version number for the package parser cache. Increment this whenever the format or
575     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
576     */
577    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
578
579    /**
580     * Whether the package parser cache is enabled.
581     */
582    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
583
584    final ServiceThread mHandlerThread;
585
586    final PackageHandler mHandler;
587
588    private final ProcessLoggingHandler mProcessLoggingHandler;
589
590    /**
591     * Messages for {@link #mHandler} that need to wait for system ready before
592     * being dispatched.
593     */
594    private ArrayList<Message> mPostSystemReadyMessages;
595
596    final int mSdkVersion = Build.VERSION.SDK_INT;
597
598    final Context mContext;
599    final boolean mFactoryTest;
600    final boolean mOnlyCore;
601    final DisplayMetrics mMetrics;
602    final int mDefParseFlags;
603    final String[] mSeparateProcesses;
604    final boolean mIsUpgrade;
605    final boolean mIsPreNUpgrade;
606    final boolean mIsPreNMR1Upgrade;
607
608    // Have we told the Activity Manager to whitelist the default container service by uid yet?
609    @GuardedBy("mPackages")
610    boolean mDefaultContainerWhitelisted = false;
611
612    @GuardedBy("mPackages")
613    private boolean mDexOptDialogShown;
614
615    /** The location for ASEC container files on internal storage. */
616    final String mAsecInternalPath;
617
618    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
619    // LOCK HELD.  Can be called with mInstallLock held.
620    @GuardedBy("mInstallLock")
621    final Installer mInstaller;
622
623    /** Directory where installed third-party apps stored */
624    final File mAppInstallDir;
625
626    /**
627     * Directory to which applications installed internally have their
628     * 32 bit native libraries copied.
629     */
630    private File mAppLib32InstallDir;
631
632    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
633    // apps.
634    final File mDrmAppPrivateInstallDir;
635
636    // ----------------------------------------------------------------
637
638    // Lock for state used when installing and doing other long running
639    // operations.  Methods that must be called with this lock held have
640    // the suffix "LI".
641    final Object mInstallLock = new Object();
642
643    // ----------------------------------------------------------------
644
645    // Keys are String (package name), values are Package.  This also serves
646    // as the lock for the global state.  Methods that must be called with
647    // this lock held have the prefix "LP".
648    @GuardedBy("mPackages")
649    final ArrayMap<String, PackageParser.Package> mPackages =
650            new ArrayMap<String, PackageParser.Package>();
651
652    final ArrayMap<String, Set<String>> mKnownCodebase =
653            new ArrayMap<String, Set<String>>();
654
655    // Keys are isolated uids and values are the uid of the application
656    // that created the isolated proccess.
657    @GuardedBy("mPackages")
658    final SparseIntArray mIsolatedOwners = new SparseIntArray();
659
660    // List of APK paths to load for each user and package. This data is never
661    // persisted by the package manager. Instead, the overlay manager will
662    // ensure the data is up-to-date in runtime.
663    @GuardedBy("mPackages")
664    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
665        new SparseArray<ArrayMap<String, ArrayList<String>>>();
666
667    /**
668     * Tracks new system packages [received in an OTA] that we expect to
669     * find updated user-installed versions. Keys are package name, values
670     * are package location.
671     */
672    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
673    /**
674     * Tracks high priority intent filters for protected actions. During boot, certain
675     * filter actions are protected and should never be allowed to have a high priority
676     * intent filter for them. However, there is one, and only one exception -- the
677     * setup wizard. It must be able to define a high priority intent filter for these
678     * actions to ensure there are no escapes from the wizard. We need to delay processing
679     * of these during boot as we need to look at all of the system packages in order
680     * to know which component is the setup wizard.
681     */
682    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
683    /**
684     * Whether or not processing protected filters should be deferred.
685     */
686    private boolean mDeferProtectedFilters = true;
687
688    /**
689     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
690     */
691    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
692    /**
693     * Whether or not system app permissions should be promoted from install to runtime.
694     */
695    boolean mPromoteSystemApps;
696
697    @GuardedBy("mPackages")
698    final Settings mSettings;
699
700    /**
701     * Set of package names that are currently "frozen", which means active
702     * surgery is being done on the code/data for that package. The platform
703     * will refuse to launch frozen packages to avoid race conditions.
704     *
705     * @see PackageFreezer
706     */
707    @GuardedBy("mPackages")
708    final ArraySet<String> mFrozenPackages = new ArraySet<>();
709
710    final ProtectedPackages mProtectedPackages;
711
712    boolean mFirstBoot;
713
714    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
715
716    // System configuration read by SystemConfig.
717    final int[] mGlobalGids;
718    final SparseArray<ArraySet<String>> mSystemPermissions;
719    @GuardedBy("mAvailableFeatures")
720    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
721
722    // If mac_permissions.xml was found for seinfo labeling.
723    boolean mFoundPolicyFile;
724
725    private final InstantAppRegistry mInstantAppRegistry;
726
727    @GuardedBy("mPackages")
728    int mChangedPackagesSequenceNumber;
729    /**
730     * List of changed [installed, removed or updated] packages.
731     * mapping from user id -> sequence number -> package name
732     */
733    @GuardedBy("mPackages")
734    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
735    /**
736     * The sequence number of the last change to a package.
737     * mapping from user id -> package name -> sequence number
738     */
739    @GuardedBy("mPackages")
740    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
741
742    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
743        @Override public boolean hasFeature(String feature) {
744            return PackageManagerService.this.hasSystemFeature(feature, 0);
745        }
746    };
747
748    public static final class SharedLibraryEntry {
749        public final String path;
750        public final String apk;
751        public final SharedLibraryInfo info;
752
753        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
754                String declaringPackageName, int declaringPackageVersionCode) {
755            path = _path;
756            apk = _apk;
757            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
758                    declaringPackageName, declaringPackageVersionCode), null);
759        }
760    }
761
762    // Currently known shared libraries.
763    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
764    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
765            new ArrayMap<>();
766
767    // All available activities, for your resolving pleasure.
768    final ActivityIntentResolver mActivities =
769            new ActivityIntentResolver();
770
771    // All available receivers, for your resolving pleasure.
772    final ActivityIntentResolver mReceivers =
773            new ActivityIntentResolver();
774
775    // All available services, for your resolving pleasure.
776    final ServiceIntentResolver mServices = new ServiceIntentResolver();
777
778    // All available providers, for your resolving pleasure.
779    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
780
781    // Mapping from provider base names (first directory in content URI codePath)
782    // to the provider information.
783    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
784            new ArrayMap<String, PackageParser.Provider>();
785
786    // Mapping from instrumentation class names to info about them.
787    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
788            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
789
790    // Mapping from permission names to info about them.
791    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
792            new ArrayMap<String, PackageParser.PermissionGroup>();
793
794    // Packages whose data we have transfered into another package, thus
795    // should no longer exist.
796    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
797
798    // Broadcast actions that are only available to the system.
799    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
800
801    /** List of packages waiting for verification. */
802    final SparseArray<PackageVerificationState> mPendingVerification
803            = new SparseArray<PackageVerificationState>();
804
805    /** Set of packages associated with each app op permission. */
806    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
807
808    final PackageInstallerService mInstallerService;
809
810    private final PackageDexOptimizer mPackageDexOptimizer;
811    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
812    // is used by other apps).
813    private final DexManager mDexManager;
814
815    private AtomicInteger mNextMoveId = new AtomicInteger();
816    private final MoveCallbacks mMoveCallbacks;
817
818    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
819
820    // Cache of users who need badging.
821    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
822
823    /** Token for keys in mPendingVerification. */
824    private int mPendingVerificationToken = 0;
825
826    volatile boolean mSystemReady;
827    volatile boolean mSafeMode;
828    volatile boolean mHasSystemUidErrors;
829    private volatile boolean mEphemeralAppsDisabled;
830
831    ApplicationInfo mAndroidApplication;
832    final ActivityInfo mResolveActivity = new ActivityInfo();
833    final ResolveInfo mResolveInfo = new ResolveInfo();
834    ComponentName mResolveComponentName;
835    PackageParser.Package mPlatformPackage;
836    ComponentName mCustomResolverComponentName;
837
838    boolean mResolverReplaced = false;
839
840    private final @Nullable ComponentName mIntentFilterVerifierComponent;
841    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
842
843    private int mIntentFilterVerificationToken = 0;
844
845    /** The service connection to the ephemeral resolver */
846    final EphemeralResolverConnection mInstantAppResolverConnection;
847    /** Component used to show resolver settings for Instant Apps */
848    final ComponentName mInstantAppResolverSettingsComponent;
849
850    /** Activity used to install instant applications */
851    ActivityInfo mInstantAppInstallerActivity;
852    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
853
854    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
855            = new SparseArray<IntentFilterVerificationState>();
856
857    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
858
859    // List of packages names to keep cached, even if they are uninstalled for all users
860    private List<String> mKeepUninstalledPackages;
861
862    private UserManagerInternal mUserManagerInternal;
863
864    private DeviceIdleController.LocalService mDeviceIdleController;
865
866    private File mCacheDir;
867
868    private ArraySet<String> mPrivappPermissionsViolations;
869
870    private Future<?> mPrepareAppDataFuture;
871
872    private static class IFVerificationParams {
873        PackageParser.Package pkg;
874        boolean replacing;
875        int userId;
876        int verifierUid;
877
878        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
879                int _userId, int _verifierUid) {
880            pkg = _pkg;
881            replacing = _replacing;
882            userId = _userId;
883            replacing = _replacing;
884            verifierUid = _verifierUid;
885        }
886    }
887
888    private interface IntentFilterVerifier<T extends IntentFilter> {
889        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
890                                               T filter, String packageName);
891        void startVerifications(int userId);
892        void receiveVerificationResponse(int verificationId);
893    }
894
895    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
896        private Context mContext;
897        private ComponentName mIntentFilterVerifierComponent;
898        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
899
900        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
901            mContext = context;
902            mIntentFilterVerifierComponent = verifierComponent;
903        }
904
905        private String getDefaultScheme() {
906            return IntentFilter.SCHEME_HTTPS;
907        }
908
909        @Override
910        public void startVerifications(int userId) {
911            // Launch verifications requests
912            int count = mCurrentIntentFilterVerifications.size();
913            for (int n=0; n<count; n++) {
914                int verificationId = mCurrentIntentFilterVerifications.get(n);
915                final IntentFilterVerificationState ivs =
916                        mIntentFilterVerificationStates.get(verificationId);
917
918                String packageName = ivs.getPackageName();
919
920                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
921                final int filterCount = filters.size();
922                ArraySet<String> domainsSet = new ArraySet<>();
923                for (int m=0; m<filterCount; m++) {
924                    PackageParser.ActivityIntentInfo filter = filters.get(m);
925                    domainsSet.addAll(filter.getHostsList());
926                }
927                synchronized (mPackages) {
928                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
929                            packageName, domainsSet) != null) {
930                        scheduleWriteSettingsLocked();
931                    }
932                }
933                sendVerificationRequest(userId, verificationId, ivs);
934            }
935            mCurrentIntentFilterVerifications.clear();
936        }
937
938        private void sendVerificationRequest(int userId, int verificationId,
939                IntentFilterVerificationState ivs) {
940
941            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
942            verificationIntent.putExtra(
943                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
944                    verificationId);
945            verificationIntent.putExtra(
946                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
947                    getDefaultScheme());
948            verificationIntent.putExtra(
949                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
950                    ivs.getHostsString());
951            verificationIntent.putExtra(
952                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
953                    ivs.getPackageName());
954            verificationIntent.setComponent(mIntentFilterVerifierComponent);
955            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
956
957            UserHandle user = new UserHandle(userId);
958            mContext.sendBroadcastAsUser(verificationIntent, user);
959            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
960                    "Sending IntentFilter verification broadcast");
961        }
962
963        public void receiveVerificationResponse(int verificationId) {
964            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
965
966            final boolean verified = ivs.isVerified();
967
968            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
969            final int count = filters.size();
970            if (DEBUG_DOMAIN_VERIFICATION) {
971                Slog.i(TAG, "Received verification response " + verificationId
972                        + " for " + count + " filters, verified=" + verified);
973            }
974            for (int n=0; n<count; n++) {
975                PackageParser.ActivityIntentInfo filter = filters.get(n);
976                filter.setVerified(verified);
977
978                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
979                        + " verified with result:" + verified + " and hosts:"
980                        + ivs.getHostsString());
981            }
982
983            mIntentFilterVerificationStates.remove(verificationId);
984
985            final String packageName = ivs.getPackageName();
986            IntentFilterVerificationInfo ivi = null;
987
988            synchronized (mPackages) {
989                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
990            }
991            if (ivi == null) {
992                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
993                        + verificationId + " packageName:" + packageName);
994                return;
995            }
996            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
997                    "Updating IntentFilterVerificationInfo for package " + packageName
998                            +" verificationId:" + verificationId);
999
1000            synchronized (mPackages) {
1001                if (verified) {
1002                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1003                } else {
1004                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1005                }
1006                scheduleWriteSettingsLocked();
1007
1008                final int userId = ivs.getUserId();
1009                if (userId != UserHandle.USER_ALL) {
1010                    final int userStatus =
1011                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1012
1013                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1014                    boolean needUpdate = false;
1015
1016                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1017                    // already been set by the User thru the Disambiguation dialog
1018                    switch (userStatus) {
1019                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1020                            if (verified) {
1021                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1022                            } else {
1023                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1024                            }
1025                            needUpdate = true;
1026                            break;
1027
1028                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1029                            if (verified) {
1030                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1031                                needUpdate = true;
1032                            }
1033                            break;
1034
1035                        default:
1036                            // Nothing to do
1037                    }
1038
1039                    if (needUpdate) {
1040                        mSettings.updateIntentFilterVerificationStatusLPw(
1041                                packageName, updatedStatus, userId);
1042                        scheduleWritePackageRestrictionsLocked(userId);
1043                    }
1044                }
1045            }
1046        }
1047
1048        @Override
1049        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1050                    ActivityIntentInfo filter, String packageName) {
1051            if (!hasValidDomains(filter)) {
1052                return false;
1053            }
1054            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1055            if (ivs == null) {
1056                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1057                        packageName);
1058            }
1059            if (DEBUG_DOMAIN_VERIFICATION) {
1060                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1061            }
1062            ivs.addFilter(filter);
1063            return true;
1064        }
1065
1066        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1067                int userId, int verificationId, String packageName) {
1068            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1069                    verifierUid, userId, packageName);
1070            ivs.setPendingState();
1071            synchronized (mPackages) {
1072                mIntentFilterVerificationStates.append(verificationId, ivs);
1073                mCurrentIntentFilterVerifications.add(verificationId);
1074            }
1075            return ivs;
1076        }
1077    }
1078
1079    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1080        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1081                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1082                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1083    }
1084
1085    // Set of pending broadcasts for aggregating enable/disable of components.
1086    static class PendingPackageBroadcasts {
1087        // for each user id, a map of <package name -> components within that package>
1088        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1089
1090        public PendingPackageBroadcasts() {
1091            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1092        }
1093
1094        public ArrayList<String> get(int userId, String packageName) {
1095            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1096            return packages.get(packageName);
1097        }
1098
1099        public void put(int userId, String packageName, ArrayList<String> components) {
1100            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1101            packages.put(packageName, components);
1102        }
1103
1104        public void remove(int userId, String packageName) {
1105            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1106            if (packages != null) {
1107                packages.remove(packageName);
1108            }
1109        }
1110
1111        public void remove(int userId) {
1112            mUidMap.remove(userId);
1113        }
1114
1115        public int userIdCount() {
1116            return mUidMap.size();
1117        }
1118
1119        public int userIdAt(int n) {
1120            return mUidMap.keyAt(n);
1121        }
1122
1123        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1124            return mUidMap.get(userId);
1125        }
1126
1127        public int size() {
1128            // total number of pending broadcast entries across all userIds
1129            int num = 0;
1130            for (int i = 0; i< mUidMap.size(); i++) {
1131                num += mUidMap.valueAt(i).size();
1132            }
1133            return num;
1134        }
1135
1136        public void clear() {
1137            mUidMap.clear();
1138        }
1139
1140        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1141            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1142            if (map == null) {
1143                map = new ArrayMap<String, ArrayList<String>>();
1144                mUidMap.put(userId, map);
1145            }
1146            return map;
1147        }
1148    }
1149    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1150
1151    // Service Connection to remote media container service to copy
1152    // package uri's from external media onto secure containers
1153    // or internal storage.
1154    private IMediaContainerService mContainerService = null;
1155
1156    static final int SEND_PENDING_BROADCAST = 1;
1157    static final int MCS_BOUND = 3;
1158    static final int END_COPY = 4;
1159    static final int INIT_COPY = 5;
1160    static final int MCS_UNBIND = 6;
1161    static final int START_CLEANING_PACKAGE = 7;
1162    static final int FIND_INSTALL_LOC = 8;
1163    static final int POST_INSTALL = 9;
1164    static final int MCS_RECONNECT = 10;
1165    static final int MCS_GIVE_UP = 11;
1166    static final int UPDATED_MEDIA_STATUS = 12;
1167    static final int WRITE_SETTINGS = 13;
1168    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1169    static final int PACKAGE_VERIFIED = 15;
1170    static final int CHECK_PENDING_VERIFICATION = 16;
1171    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1172    static final int INTENT_FILTER_VERIFIED = 18;
1173    static final int WRITE_PACKAGE_LIST = 19;
1174    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1175
1176    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1177
1178    // Delay time in millisecs
1179    static final int BROADCAST_DELAY = 10 * 1000;
1180
1181    static UserManagerService sUserManager;
1182
1183    // Stores a list of users whose package restrictions file needs to be updated
1184    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1185
1186    final private DefaultContainerConnection mDefContainerConn =
1187            new DefaultContainerConnection();
1188    class DefaultContainerConnection implements ServiceConnection {
1189        public void onServiceConnected(ComponentName name, IBinder service) {
1190            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1191            final IMediaContainerService imcs = IMediaContainerService.Stub
1192                    .asInterface(Binder.allowBlocking(service));
1193            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1194        }
1195
1196        public void onServiceDisconnected(ComponentName name) {
1197            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1198        }
1199    }
1200
1201    // Recordkeeping of restore-after-install operations that are currently in flight
1202    // between the Package Manager and the Backup Manager
1203    static class PostInstallData {
1204        public InstallArgs args;
1205        public PackageInstalledInfo res;
1206
1207        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1208            args = _a;
1209            res = _r;
1210        }
1211    }
1212
1213    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1214    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1215
1216    // XML tags for backup/restore of various bits of state
1217    private static final String TAG_PREFERRED_BACKUP = "pa";
1218    private static final String TAG_DEFAULT_APPS = "da";
1219    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1220
1221    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1222    private static final String TAG_ALL_GRANTS = "rt-grants";
1223    private static final String TAG_GRANT = "grant";
1224    private static final String ATTR_PACKAGE_NAME = "pkg";
1225
1226    private static final String TAG_PERMISSION = "perm";
1227    private static final String ATTR_PERMISSION_NAME = "name";
1228    private static final String ATTR_IS_GRANTED = "g";
1229    private static final String ATTR_USER_SET = "set";
1230    private static final String ATTR_USER_FIXED = "fixed";
1231    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1232
1233    // System/policy permission grants are not backed up
1234    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1235            FLAG_PERMISSION_POLICY_FIXED
1236            | FLAG_PERMISSION_SYSTEM_FIXED
1237            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1238
1239    // And we back up these user-adjusted states
1240    private static final int USER_RUNTIME_GRANT_MASK =
1241            FLAG_PERMISSION_USER_SET
1242            | FLAG_PERMISSION_USER_FIXED
1243            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1244
1245    final @Nullable String mRequiredVerifierPackage;
1246    final @NonNull String mRequiredInstallerPackage;
1247    final @NonNull String mRequiredUninstallerPackage;
1248    final @Nullable String mSetupWizardPackage;
1249    final @Nullable String mStorageManagerPackage;
1250    final @NonNull String mServicesSystemSharedLibraryPackageName;
1251    final @NonNull String mSharedSystemSharedLibraryPackageName;
1252
1253    final boolean mPermissionReviewRequired;
1254
1255    private final PackageUsage mPackageUsage = new PackageUsage();
1256    private final CompilerStats mCompilerStats = new CompilerStats();
1257
1258    class PackageHandler extends Handler {
1259        private boolean mBound = false;
1260        final ArrayList<HandlerParams> mPendingInstalls =
1261            new ArrayList<HandlerParams>();
1262
1263        private boolean connectToService() {
1264            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1265                    " DefaultContainerService");
1266            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1267            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1268            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1269                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1270                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1271                mBound = true;
1272                return true;
1273            }
1274            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1275            return false;
1276        }
1277
1278        private void disconnectService() {
1279            mContainerService = null;
1280            mBound = false;
1281            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1282            mContext.unbindService(mDefContainerConn);
1283            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1284        }
1285
1286        PackageHandler(Looper looper) {
1287            super(looper);
1288        }
1289
1290        public void handleMessage(Message msg) {
1291            try {
1292                doHandleMessage(msg);
1293            } finally {
1294                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1295            }
1296        }
1297
1298        void doHandleMessage(Message msg) {
1299            switch (msg.what) {
1300                case INIT_COPY: {
1301                    HandlerParams params = (HandlerParams) msg.obj;
1302                    int idx = mPendingInstalls.size();
1303                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1304                    // If a bind was already initiated we dont really
1305                    // need to do anything. The pending install
1306                    // will be processed later on.
1307                    if (!mBound) {
1308                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1309                                System.identityHashCode(mHandler));
1310                        // If this is the only one pending we might
1311                        // have to bind to the service again.
1312                        if (!connectToService()) {
1313                            Slog.e(TAG, "Failed to bind to media container service");
1314                            params.serviceError();
1315                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1316                                    System.identityHashCode(mHandler));
1317                            if (params.traceMethod != null) {
1318                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1319                                        params.traceCookie);
1320                            }
1321                            return;
1322                        } else {
1323                            // Once we bind to the service, the first
1324                            // pending request will be processed.
1325                            mPendingInstalls.add(idx, params);
1326                        }
1327                    } else {
1328                        mPendingInstalls.add(idx, params);
1329                        // Already bound to the service. Just make
1330                        // sure we trigger off processing the first request.
1331                        if (idx == 0) {
1332                            mHandler.sendEmptyMessage(MCS_BOUND);
1333                        }
1334                    }
1335                    break;
1336                }
1337                case MCS_BOUND: {
1338                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1339                    if (msg.obj != null) {
1340                        mContainerService = (IMediaContainerService) msg.obj;
1341                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1342                                System.identityHashCode(mHandler));
1343                    }
1344                    if (mContainerService == null) {
1345                        if (!mBound) {
1346                            // Something seriously wrong since we are not bound and we are not
1347                            // waiting for connection. Bail out.
1348                            Slog.e(TAG, "Cannot bind to media container service");
1349                            for (HandlerParams params : mPendingInstalls) {
1350                                // Indicate service bind error
1351                                params.serviceError();
1352                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1353                                        System.identityHashCode(params));
1354                                if (params.traceMethod != null) {
1355                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1356                                            params.traceMethod, params.traceCookie);
1357                                }
1358                                return;
1359                            }
1360                            mPendingInstalls.clear();
1361                        } else {
1362                            Slog.w(TAG, "Waiting to connect to media container service");
1363                        }
1364                    } else if (mPendingInstalls.size() > 0) {
1365                        HandlerParams params = mPendingInstalls.get(0);
1366                        if (params != null) {
1367                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1368                                    System.identityHashCode(params));
1369                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1370                            if (params.startCopy()) {
1371                                // We are done...  look for more work or to
1372                                // go idle.
1373                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1374                                        "Checking for more work or unbind...");
1375                                // Delete pending install
1376                                if (mPendingInstalls.size() > 0) {
1377                                    mPendingInstalls.remove(0);
1378                                }
1379                                if (mPendingInstalls.size() == 0) {
1380                                    if (mBound) {
1381                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1382                                                "Posting delayed MCS_UNBIND");
1383                                        removeMessages(MCS_UNBIND);
1384                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1385                                        // Unbind after a little delay, to avoid
1386                                        // continual thrashing.
1387                                        sendMessageDelayed(ubmsg, 10000);
1388                                    }
1389                                } else {
1390                                    // There are more pending requests in queue.
1391                                    // Just post MCS_BOUND message to trigger processing
1392                                    // of next pending install.
1393                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1394                                            "Posting MCS_BOUND for next work");
1395                                    mHandler.sendEmptyMessage(MCS_BOUND);
1396                                }
1397                            }
1398                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1399                        }
1400                    } else {
1401                        // Should never happen ideally.
1402                        Slog.w(TAG, "Empty queue");
1403                    }
1404                    break;
1405                }
1406                case MCS_RECONNECT: {
1407                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1408                    if (mPendingInstalls.size() > 0) {
1409                        if (mBound) {
1410                            disconnectService();
1411                        }
1412                        if (!connectToService()) {
1413                            Slog.e(TAG, "Failed to bind to media container service");
1414                            for (HandlerParams params : mPendingInstalls) {
1415                                // Indicate service bind error
1416                                params.serviceError();
1417                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1418                                        System.identityHashCode(params));
1419                            }
1420                            mPendingInstalls.clear();
1421                        }
1422                    }
1423                    break;
1424                }
1425                case MCS_UNBIND: {
1426                    // If there is no actual work left, then time to unbind.
1427                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1428
1429                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1430                        if (mBound) {
1431                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1432
1433                            disconnectService();
1434                        }
1435                    } else if (mPendingInstalls.size() > 0) {
1436                        // There are more pending requests in queue.
1437                        // Just post MCS_BOUND message to trigger processing
1438                        // of next pending install.
1439                        mHandler.sendEmptyMessage(MCS_BOUND);
1440                    }
1441
1442                    break;
1443                }
1444                case MCS_GIVE_UP: {
1445                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1446                    HandlerParams params = mPendingInstalls.remove(0);
1447                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1448                            System.identityHashCode(params));
1449                    break;
1450                }
1451                case SEND_PENDING_BROADCAST: {
1452                    String packages[];
1453                    ArrayList<String> components[];
1454                    int size = 0;
1455                    int uids[];
1456                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1457                    synchronized (mPackages) {
1458                        if (mPendingBroadcasts == null) {
1459                            return;
1460                        }
1461                        size = mPendingBroadcasts.size();
1462                        if (size <= 0) {
1463                            // Nothing to be done. Just return
1464                            return;
1465                        }
1466                        packages = new String[size];
1467                        components = new ArrayList[size];
1468                        uids = new int[size];
1469                        int i = 0;  // filling out the above arrays
1470
1471                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1472                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1473                            Iterator<Map.Entry<String, ArrayList<String>>> it
1474                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1475                                            .entrySet().iterator();
1476                            while (it.hasNext() && i < size) {
1477                                Map.Entry<String, ArrayList<String>> ent = it.next();
1478                                packages[i] = ent.getKey();
1479                                components[i] = ent.getValue();
1480                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1481                                uids[i] = (ps != null)
1482                                        ? UserHandle.getUid(packageUserId, ps.appId)
1483                                        : -1;
1484                                i++;
1485                            }
1486                        }
1487                        size = i;
1488                        mPendingBroadcasts.clear();
1489                    }
1490                    // Send broadcasts
1491                    for (int i = 0; i < size; i++) {
1492                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1493                    }
1494                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1495                    break;
1496                }
1497                case START_CLEANING_PACKAGE: {
1498                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1499                    final String packageName = (String)msg.obj;
1500                    final int userId = msg.arg1;
1501                    final boolean andCode = msg.arg2 != 0;
1502                    synchronized (mPackages) {
1503                        if (userId == UserHandle.USER_ALL) {
1504                            int[] users = sUserManager.getUserIds();
1505                            for (int user : users) {
1506                                mSettings.addPackageToCleanLPw(
1507                                        new PackageCleanItem(user, packageName, andCode));
1508                            }
1509                        } else {
1510                            mSettings.addPackageToCleanLPw(
1511                                    new PackageCleanItem(userId, packageName, andCode));
1512                        }
1513                    }
1514                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1515                    startCleaningPackages();
1516                } break;
1517                case POST_INSTALL: {
1518                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1519
1520                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1521                    final boolean didRestore = (msg.arg2 != 0);
1522                    mRunningInstalls.delete(msg.arg1);
1523
1524                    if (data != null) {
1525                        InstallArgs args = data.args;
1526                        PackageInstalledInfo parentRes = data.res;
1527
1528                        final boolean grantPermissions = (args.installFlags
1529                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1530                        final boolean killApp = (args.installFlags
1531                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1532                        final String[] grantedPermissions = args.installGrantPermissions;
1533
1534                        // Handle the parent package
1535                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1536                                grantedPermissions, didRestore, args.installerPackageName,
1537                                args.observer);
1538
1539                        // Handle the child packages
1540                        final int childCount = (parentRes.addedChildPackages != null)
1541                                ? parentRes.addedChildPackages.size() : 0;
1542                        for (int i = 0; i < childCount; i++) {
1543                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1544                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1545                                    grantedPermissions, false, args.installerPackageName,
1546                                    args.observer);
1547                        }
1548
1549                        // Log tracing if needed
1550                        if (args.traceMethod != null) {
1551                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1552                                    args.traceCookie);
1553                        }
1554                    } else {
1555                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1556                    }
1557
1558                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1559                } break;
1560                case UPDATED_MEDIA_STATUS: {
1561                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1562                    boolean reportStatus = msg.arg1 == 1;
1563                    boolean doGc = msg.arg2 == 1;
1564                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1565                    if (doGc) {
1566                        // Force a gc to clear up stale containers.
1567                        Runtime.getRuntime().gc();
1568                    }
1569                    if (msg.obj != null) {
1570                        @SuppressWarnings("unchecked")
1571                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1572                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1573                        // Unload containers
1574                        unloadAllContainers(args);
1575                    }
1576                    if (reportStatus) {
1577                        try {
1578                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1579                                    "Invoking StorageManagerService call back");
1580                            PackageHelper.getStorageManager().finishMediaUpdate();
1581                        } catch (RemoteException e) {
1582                            Log.e(TAG, "StorageManagerService not running?");
1583                        }
1584                    }
1585                } break;
1586                case WRITE_SETTINGS: {
1587                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1588                    synchronized (mPackages) {
1589                        removeMessages(WRITE_SETTINGS);
1590                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1591                        mSettings.writeLPr();
1592                        mDirtyUsers.clear();
1593                    }
1594                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1595                } break;
1596                case WRITE_PACKAGE_RESTRICTIONS: {
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1598                    synchronized (mPackages) {
1599                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1600                        for (int userId : mDirtyUsers) {
1601                            mSettings.writePackageRestrictionsLPr(userId);
1602                        }
1603                        mDirtyUsers.clear();
1604                    }
1605                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1606                } break;
1607                case WRITE_PACKAGE_LIST: {
1608                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1609                    synchronized (mPackages) {
1610                        removeMessages(WRITE_PACKAGE_LIST);
1611                        mSettings.writePackageListLPr(msg.arg1);
1612                    }
1613                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1614                } break;
1615                case CHECK_PENDING_VERIFICATION: {
1616                    final int verificationId = msg.arg1;
1617                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1618
1619                    if ((state != null) && !state.timeoutExtended()) {
1620                        final InstallArgs args = state.getInstallArgs();
1621                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1622
1623                        Slog.i(TAG, "Verification timed out for " + originUri);
1624                        mPendingVerification.remove(verificationId);
1625
1626                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1627
1628                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1629                            Slog.i(TAG, "Continuing with installation of " + originUri);
1630                            state.setVerifierResponse(Binder.getCallingUid(),
1631                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1632                            broadcastPackageVerified(verificationId, originUri,
1633                                    PackageManager.VERIFICATION_ALLOW,
1634                                    state.getInstallArgs().getUser());
1635                            try {
1636                                ret = args.copyApk(mContainerService, true);
1637                            } catch (RemoteException e) {
1638                                Slog.e(TAG, "Could not contact the ContainerService");
1639                            }
1640                        } else {
1641                            broadcastPackageVerified(verificationId, originUri,
1642                                    PackageManager.VERIFICATION_REJECT,
1643                                    state.getInstallArgs().getUser());
1644                        }
1645
1646                        Trace.asyncTraceEnd(
1647                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1648
1649                        processPendingInstall(args, ret);
1650                        mHandler.sendEmptyMessage(MCS_UNBIND);
1651                    }
1652                    break;
1653                }
1654                case PACKAGE_VERIFIED: {
1655                    final int verificationId = msg.arg1;
1656
1657                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1658                    if (state == null) {
1659                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1660                        break;
1661                    }
1662
1663                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1664
1665                    state.setVerifierResponse(response.callerUid, response.code);
1666
1667                    if (state.isVerificationComplete()) {
1668                        mPendingVerification.remove(verificationId);
1669
1670                        final InstallArgs args = state.getInstallArgs();
1671                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1672
1673                        int ret;
1674                        if (state.isInstallAllowed()) {
1675                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1676                            broadcastPackageVerified(verificationId, originUri,
1677                                    response.code, state.getInstallArgs().getUser());
1678                            try {
1679                                ret = args.copyApk(mContainerService, true);
1680                            } catch (RemoteException e) {
1681                                Slog.e(TAG, "Could not contact the ContainerService");
1682                            }
1683                        } else {
1684                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1685                        }
1686
1687                        Trace.asyncTraceEnd(
1688                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1689
1690                        processPendingInstall(args, ret);
1691                        mHandler.sendEmptyMessage(MCS_UNBIND);
1692                    }
1693
1694                    break;
1695                }
1696                case START_INTENT_FILTER_VERIFICATIONS: {
1697                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1698                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1699                            params.replacing, params.pkg);
1700                    break;
1701                }
1702                case INTENT_FILTER_VERIFIED: {
1703                    final int verificationId = msg.arg1;
1704
1705                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1706                            verificationId);
1707                    if (state == null) {
1708                        Slog.w(TAG, "Invalid IntentFilter verification token "
1709                                + verificationId + " received");
1710                        break;
1711                    }
1712
1713                    final int userId = state.getUserId();
1714
1715                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1716                            "Processing IntentFilter verification with token:"
1717                            + verificationId + " and userId:" + userId);
1718
1719                    final IntentFilterVerificationResponse response =
1720                            (IntentFilterVerificationResponse) msg.obj;
1721
1722                    state.setVerifierResponse(response.callerUid, response.code);
1723
1724                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1725                            "IntentFilter verification with token:" + verificationId
1726                            + " and userId:" + userId
1727                            + " is settings verifier response with response code:"
1728                            + response.code);
1729
1730                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1731                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1732                                + response.getFailedDomainsString());
1733                    }
1734
1735                    if (state.isVerificationComplete()) {
1736                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1737                    } else {
1738                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1739                                "IntentFilter verification with token:" + verificationId
1740                                + " was not said to be complete");
1741                    }
1742
1743                    break;
1744                }
1745                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1746                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1747                            mInstantAppResolverConnection,
1748                            (InstantAppRequest) msg.obj,
1749                            mInstantAppInstallerActivity,
1750                            mHandler);
1751                }
1752            }
1753        }
1754    }
1755
1756    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1757            boolean killApp, String[] grantedPermissions,
1758            boolean launchedForRestore, String installerPackage,
1759            IPackageInstallObserver2 installObserver) {
1760        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1761            // Send the removed broadcasts
1762            if (res.removedInfo != null) {
1763                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1764            }
1765
1766            // Now that we successfully installed the package, grant runtime
1767            // permissions if requested before broadcasting the install. Also
1768            // for legacy apps in permission review mode we clear the permission
1769            // review flag which is used to emulate runtime permissions for
1770            // legacy apps.
1771            if (grantPermissions) {
1772                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1773            }
1774
1775            final boolean update = res.removedInfo != null
1776                    && res.removedInfo.removedPackage != null;
1777
1778            // If this is the first time we have child packages for a disabled privileged
1779            // app that had no children, we grant requested runtime permissions to the new
1780            // children if the parent on the system image had them already granted.
1781            if (res.pkg.parentPackage != null) {
1782                synchronized (mPackages) {
1783                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1784                }
1785            }
1786
1787            synchronized (mPackages) {
1788                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1789            }
1790
1791            final String packageName = res.pkg.applicationInfo.packageName;
1792
1793            // Determine the set of users who are adding this package for
1794            // the first time vs. those who are seeing an update.
1795            int[] firstUsers = EMPTY_INT_ARRAY;
1796            int[] updateUsers = EMPTY_INT_ARRAY;
1797            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1798            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1799            for (int newUser : res.newUsers) {
1800                if (ps.getInstantApp(newUser)) {
1801                    continue;
1802                }
1803                if (allNewUsers) {
1804                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1805                    continue;
1806                }
1807                boolean isNew = true;
1808                for (int origUser : res.origUsers) {
1809                    if (origUser == newUser) {
1810                        isNew = false;
1811                        break;
1812                    }
1813                }
1814                if (isNew) {
1815                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1816                } else {
1817                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1818                }
1819            }
1820
1821            // Send installed broadcasts if the package is not a static shared lib.
1822            if (res.pkg.staticSharedLibName == null) {
1823                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1824
1825                // Send added for users that see the package for the first time
1826                // sendPackageAddedForNewUsers also deals with system apps
1827                int appId = UserHandle.getAppId(res.uid);
1828                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1829                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1830
1831                // Send added for users that don't see the package for the first time
1832                Bundle extras = new Bundle(1);
1833                extras.putInt(Intent.EXTRA_UID, res.uid);
1834                if (update) {
1835                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1836                } else {
1837                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_ADDED, packageName,
1838                            extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
1839                            null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1840                }
1841                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1842                        extras, 0 /*flags*/, null /*targetPackage*/,
1843                        null /*finishedReceiver*/, updateUsers);
1844
1845                // Send replaced for users that don't see the package for the first time
1846                if (update) {
1847                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1848                            packageName, extras, 0 /*flags*/,
1849                            null /*targetPackage*/, null /*finishedReceiver*/,
1850                            updateUsers);
1851                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1852                            null /*package*/, null /*extras*/, 0 /*flags*/,
1853                            packageName /*targetPackage*/,
1854                            null /*finishedReceiver*/, updateUsers);
1855                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1856                    // First-install and we did a restore, so we're responsible for the
1857                    // first-launch broadcast.
1858                    if (DEBUG_BACKUP) {
1859                        Slog.i(TAG, "Post-restore of " + packageName
1860                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1861                    }
1862                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1863                }
1864
1865                // Send broadcast package appeared if forward locked/external for all users
1866                // treat asec-hosted packages like removable media on upgrade
1867                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1868                    if (DEBUG_INSTALL) {
1869                        Slog.i(TAG, "upgrading pkg " + res.pkg
1870                                + " is ASEC-hosted -> AVAILABLE");
1871                    }
1872                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1873                    ArrayList<String> pkgList = new ArrayList<>(1);
1874                    pkgList.add(packageName);
1875                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1876                }
1877            }
1878
1879            // Work that needs to happen on first install within each user
1880            if (firstUsers != null && firstUsers.length > 0) {
1881                synchronized (mPackages) {
1882                    for (int userId : firstUsers) {
1883                        // If this app is a browser and it's newly-installed for some
1884                        // users, clear any default-browser state in those users. The
1885                        // app's nature doesn't depend on the user, so we can just check
1886                        // its browser nature in any user and generalize.
1887                        if (packageIsBrowser(packageName, userId)) {
1888                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1889                        }
1890
1891                        // We may also need to apply pending (restored) runtime
1892                        // permission grants within these users.
1893                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1894                    }
1895                }
1896            }
1897
1898            // Log current value of "unknown sources" setting
1899            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1900                    getUnknownSourcesSettings());
1901
1902            // Force a gc to clear up things
1903            Runtime.getRuntime().gc();
1904
1905            // Remove the replaced package's older resources safely now
1906            // We delete after a gc for applications  on sdcard.
1907            if (res.removedInfo != null && res.removedInfo.args != null) {
1908                synchronized (mInstallLock) {
1909                    res.removedInfo.args.doPostDeleteLI(true);
1910                }
1911            }
1912
1913            // Notify DexManager that the package was installed for new users.
1914            // The updated users should already be indexed and the package code paths
1915            // should not change.
1916            // Don't notify the manager for ephemeral apps as they are not expected to
1917            // survive long enough to benefit of background optimizations.
1918            for (int userId : firstUsers) {
1919                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1920                // There's a race currently where some install events may interleave with an uninstall.
1921                // This can lead to package info being null (b/36642664).
1922                if (info != null) {
1923                    mDexManager.notifyPackageInstalled(info, userId);
1924                }
1925            }
1926        }
1927
1928        // If someone is watching installs - notify them
1929        if (installObserver != null) {
1930            try {
1931                Bundle extras = extrasForInstallResult(res);
1932                installObserver.onPackageInstalled(res.name, res.returnCode,
1933                        res.returnMsg, extras);
1934            } catch (RemoteException e) {
1935                Slog.i(TAG, "Observer no longer exists.");
1936            }
1937        }
1938    }
1939
1940    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1941            PackageParser.Package pkg) {
1942        if (pkg.parentPackage == null) {
1943            return;
1944        }
1945        if (pkg.requestedPermissions == null) {
1946            return;
1947        }
1948        final PackageSetting disabledSysParentPs = mSettings
1949                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1950        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1951                || !disabledSysParentPs.isPrivileged()
1952                || (disabledSysParentPs.childPackageNames != null
1953                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1954            return;
1955        }
1956        final int[] allUserIds = sUserManager.getUserIds();
1957        final int permCount = pkg.requestedPermissions.size();
1958        for (int i = 0; i < permCount; i++) {
1959            String permission = pkg.requestedPermissions.get(i);
1960            BasePermission bp = mSettings.mPermissions.get(permission);
1961            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1962                continue;
1963            }
1964            for (int userId : allUserIds) {
1965                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1966                        permission, userId)) {
1967                    grantRuntimePermission(pkg.packageName, permission, userId);
1968                }
1969            }
1970        }
1971    }
1972
1973    private StorageEventListener mStorageListener = new StorageEventListener() {
1974        @Override
1975        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1976            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1977                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1978                    final String volumeUuid = vol.getFsUuid();
1979
1980                    // Clean up any users or apps that were removed or recreated
1981                    // while this volume was missing
1982                    sUserManager.reconcileUsers(volumeUuid);
1983                    reconcileApps(volumeUuid);
1984
1985                    // Clean up any install sessions that expired or were
1986                    // cancelled while this volume was missing
1987                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1988
1989                    loadPrivatePackages(vol);
1990
1991                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1992                    unloadPrivatePackages(vol);
1993                }
1994            }
1995
1996            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1997                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1998                    updateExternalMediaStatus(true, false);
1999                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2000                    updateExternalMediaStatus(false, false);
2001                }
2002            }
2003        }
2004
2005        @Override
2006        public void onVolumeForgotten(String fsUuid) {
2007            if (TextUtils.isEmpty(fsUuid)) {
2008                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2009                return;
2010            }
2011
2012            // Remove any apps installed on the forgotten volume
2013            synchronized (mPackages) {
2014                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2015                for (PackageSetting ps : packages) {
2016                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2017                    deletePackageVersioned(new VersionedPackage(ps.name,
2018                            PackageManager.VERSION_CODE_HIGHEST),
2019                            new LegacyPackageDeleteObserver(null).getBinder(),
2020                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2021                    // Try very hard to release any references to this package
2022                    // so we don't risk the system server being killed due to
2023                    // open FDs
2024                    AttributeCache.instance().removePackage(ps.name);
2025                }
2026
2027                mSettings.onVolumeForgotten(fsUuid);
2028                mSettings.writeLPr();
2029            }
2030        }
2031    };
2032
2033    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2034            String[] grantedPermissions) {
2035        for (int userId : userIds) {
2036            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2037        }
2038    }
2039
2040    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2041            String[] grantedPermissions) {
2042        SettingBase sb = (SettingBase) pkg.mExtras;
2043        if (sb == null) {
2044            return;
2045        }
2046
2047        PermissionsState permissionsState = sb.getPermissionsState();
2048
2049        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2050                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2051
2052        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2053                >= Build.VERSION_CODES.M;
2054
2055        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2056
2057        for (String permission : pkg.requestedPermissions) {
2058            final BasePermission bp;
2059            synchronized (mPackages) {
2060                bp = mSettings.mPermissions.get(permission);
2061            }
2062            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2063                    && (!instantApp || bp.isInstant())
2064                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2065                    && (grantedPermissions == null
2066                           || ArrayUtils.contains(grantedPermissions, permission))) {
2067                final int flags = permissionsState.getPermissionFlags(permission, userId);
2068                if (supportsRuntimePermissions) {
2069                    // Installer cannot change immutable permissions.
2070                    if ((flags & immutableFlags) == 0) {
2071                        grantRuntimePermission(pkg.packageName, permission, userId);
2072                    }
2073                } else if (mPermissionReviewRequired) {
2074                    // In permission review mode we clear the review flag when we
2075                    // are asked to install the app with all permissions granted.
2076                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2077                        updatePermissionFlags(permission, pkg.packageName,
2078                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2079                    }
2080                }
2081            }
2082        }
2083    }
2084
2085    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2086        Bundle extras = null;
2087        switch (res.returnCode) {
2088            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2089                extras = new Bundle();
2090                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2091                        res.origPermission);
2092                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2093                        res.origPackage);
2094                break;
2095            }
2096            case PackageManager.INSTALL_SUCCEEDED: {
2097                extras = new Bundle();
2098                extras.putBoolean(Intent.EXTRA_REPLACING,
2099                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2100                break;
2101            }
2102        }
2103        return extras;
2104    }
2105
2106    void scheduleWriteSettingsLocked() {
2107        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2108            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2109        }
2110    }
2111
2112    void scheduleWritePackageListLocked(int userId) {
2113        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2114            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2115            msg.arg1 = userId;
2116            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2117        }
2118    }
2119
2120    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2121        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2122        scheduleWritePackageRestrictionsLocked(userId);
2123    }
2124
2125    void scheduleWritePackageRestrictionsLocked(int userId) {
2126        final int[] userIds = (userId == UserHandle.USER_ALL)
2127                ? sUserManager.getUserIds() : new int[]{userId};
2128        for (int nextUserId : userIds) {
2129            if (!sUserManager.exists(nextUserId)) return;
2130            mDirtyUsers.add(nextUserId);
2131            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2132                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2133            }
2134        }
2135    }
2136
2137    public static PackageManagerService main(Context context, Installer installer,
2138            boolean factoryTest, boolean onlyCore) {
2139        // Self-check for initial settings.
2140        PackageManagerServiceCompilerMapping.checkProperties();
2141
2142        PackageManagerService m = new PackageManagerService(context, installer,
2143                factoryTest, onlyCore);
2144        m.enableSystemUserPackages();
2145        ServiceManager.addService("package", m);
2146        return m;
2147    }
2148
2149    private void enableSystemUserPackages() {
2150        if (!UserManager.isSplitSystemUser()) {
2151            return;
2152        }
2153        // For system user, enable apps based on the following conditions:
2154        // - app is whitelisted or belong to one of these groups:
2155        //   -- system app which has no launcher icons
2156        //   -- system app which has INTERACT_ACROSS_USERS permission
2157        //   -- system IME app
2158        // - app is not in the blacklist
2159        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2160        Set<String> enableApps = new ArraySet<>();
2161        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2162                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2163                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2164        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2165        enableApps.addAll(wlApps);
2166        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2167                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2168        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2169        enableApps.removeAll(blApps);
2170        Log.i(TAG, "Applications installed for system user: " + enableApps);
2171        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2172                UserHandle.SYSTEM);
2173        final int allAppsSize = allAps.size();
2174        synchronized (mPackages) {
2175            for (int i = 0; i < allAppsSize; i++) {
2176                String pName = allAps.get(i);
2177                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2178                // Should not happen, but we shouldn't be failing if it does
2179                if (pkgSetting == null) {
2180                    continue;
2181                }
2182                boolean install = enableApps.contains(pName);
2183                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2184                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2185                            + " for system user");
2186                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2187                }
2188            }
2189            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2190        }
2191    }
2192
2193    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2194        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2195                Context.DISPLAY_SERVICE);
2196        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2197    }
2198
2199    /**
2200     * Requests that files preopted on a secondary system partition be copied to the data partition
2201     * if possible.  Note that the actual copying of the files is accomplished by init for security
2202     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2203     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2204     */
2205    private static void requestCopyPreoptedFiles() {
2206        final int WAIT_TIME_MS = 100;
2207        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2208        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2209            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2210            // We will wait for up to 100 seconds.
2211            final long timeStart = SystemClock.uptimeMillis();
2212            final long timeEnd = timeStart + 100 * 1000;
2213            long timeNow = timeStart;
2214            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2215                try {
2216                    Thread.sleep(WAIT_TIME_MS);
2217                } catch (InterruptedException e) {
2218                    // Do nothing
2219                }
2220                timeNow = SystemClock.uptimeMillis();
2221                if (timeNow > timeEnd) {
2222                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2223                    Slog.wtf(TAG, "cppreopt did not finish!");
2224                    break;
2225                }
2226            }
2227
2228            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2229        }
2230    }
2231
2232    public PackageManagerService(Context context, Installer installer,
2233            boolean factoryTest, boolean onlyCore) {
2234        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2235        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2236        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2237                SystemClock.uptimeMillis());
2238
2239        if (mSdkVersion <= 0) {
2240            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2241        }
2242
2243        mContext = context;
2244
2245        mPermissionReviewRequired = context.getResources().getBoolean(
2246                R.bool.config_permissionReviewRequired);
2247
2248        mFactoryTest = factoryTest;
2249        mOnlyCore = onlyCore;
2250        mMetrics = new DisplayMetrics();
2251        mSettings = new Settings(mPackages);
2252        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2253                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2254        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2255                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2256        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2257                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2258        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2259                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2260        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2261                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2262        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2263                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2264
2265        String separateProcesses = SystemProperties.get("debug.separate_processes");
2266        if (separateProcesses != null && separateProcesses.length() > 0) {
2267            if ("*".equals(separateProcesses)) {
2268                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2269                mSeparateProcesses = null;
2270                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2271            } else {
2272                mDefParseFlags = 0;
2273                mSeparateProcesses = separateProcesses.split(",");
2274                Slog.w(TAG, "Running with debug.separate_processes: "
2275                        + separateProcesses);
2276            }
2277        } else {
2278            mDefParseFlags = 0;
2279            mSeparateProcesses = null;
2280        }
2281
2282        mInstaller = installer;
2283        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2284                "*dexopt*");
2285        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2286        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2287
2288        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2289                FgThread.get().getLooper());
2290
2291        getDefaultDisplayMetrics(context, mMetrics);
2292
2293        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2294        SystemConfig systemConfig = SystemConfig.getInstance();
2295        mGlobalGids = systemConfig.getGlobalGids();
2296        mSystemPermissions = systemConfig.getSystemPermissions();
2297        mAvailableFeatures = systemConfig.getAvailableFeatures();
2298        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2299
2300        mProtectedPackages = new ProtectedPackages(mContext);
2301
2302        synchronized (mInstallLock) {
2303        // writer
2304        synchronized (mPackages) {
2305            mHandlerThread = new ServiceThread(TAG,
2306                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2307            mHandlerThread.start();
2308            mHandler = new PackageHandler(mHandlerThread.getLooper());
2309            mProcessLoggingHandler = new ProcessLoggingHandler();
2310            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2311
2312            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2313            mInstantAppRegistry = new InstantAppRegistry(this);
2314
2315            File dataDir = Environment.getDataDirectory();
2316            mAppInstallDir = new File(dataDir, "app");
2317            mAppLib32InstallDir = new File(dataDir, "app-lib");
2318            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2319            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2320            sUserManager = new UserManagerService(context, this,
2321                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2322
2323            // Propagate permission configuration in to package manager.
2324            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2325                    = systemConfig.getPermissions();
2326            for (int i=0; i<permConfig.size(); i++) {
2327                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2328                BasePermission bp = mSettings.mPermissions.get(perm.name);
2329                if (bp == null) {
2330                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2331                    mSettings.mPermissions.put(perm.name, bp);
2332                }
2333                if (perm.gids != null) {
2334                    bp.setGids(perm.gids, perm.perUser);
2335                }
2336            }
2337
2338            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2339            final int builtInLibCount = libConfig.size();
2340            for (int i = 0; i < builtInLibCount; i++) {
2341                String name = libConfig.keyAt(i);
2342                String path = libConfig.valueAt(i);
2343                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2344                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2345            }
2346
2347            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2348
2349            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2350            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2351            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2352
2353            // Clean up orphaned packages for which the code path doesn't exist
2354            // and they are an update to a system app - caused by bug/32321269
2355            final int packageSettingCount = mSettings.mPackages.size();
2356            for (int i = packageSettingCount - 1; i >= 0; i--) {
2357                PackageSetting ps = mSettings.mPackages.valueAt(i);
2358                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2359                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2360                    mSettings.mPackages.removeAt(i);
2361                    mSettings.enableSystemPackageLPw(ps.name);
2362                }
2363            }
2364
2365            if (mFirstBoot) {
2366                requestCopyPreoptedFiles();
2367            }
2368
2369            String customResolverActivity = Resources.getSystem().getString(
2370                    R.string.config_customResolverActivity);
2371            if (TextUtils.isEmpty(customResolverActivity)) {
2372                customResolverActivity = null;
2373            } else {
2374                mCustomResolverComponentName = ComponentName.unflattenFromString(
2375                        customResolverActivity);
2376            }
2377
2378            long startTime = SystemClock.uptimeMillis();
2379
2380            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2381                    startTime);
2382
2383            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2384            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2385
2386            if (bootClassPath == null) {
2387                Slog.w(TAG, "No BOOTCLASSPATH found!");
2388            }
2389
2390            if (systemServerClassPath == null) {
2391                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2392            }
2393
2394            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2395
2396            final VersionInfo ver = mSettings.getInternalVersion();
2397            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2398            if (mIsUpgrade) {
2399                logCriticalInfo(Log.INFO,
2400                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2401            }
2402
2403            // when upgrading from pre-M, promote system app permissions from install to runtime
2404            mPromoteSystemApps =
2405                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2406
2407            // When upgrading from pre-N, we need to handle package extraction like first boot,
2408            // as there is no profiling data available.
2409            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2410
2411            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2412
2413            // save off the names of pre-existing system packages prior to scanning; we don't
2414            // want to automatically grant runtime permissions for new system apps
2415            if (mPromoteSystemApps) {
2416                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2417                while (pkgSettingIter.hasNext()) {
2418                    PackageSetting ps = pkgSettingIter.next();
2419                    if (isSystemApp(ps)) {
2420                        mExistingSystemPackages.add(ps.name);
2421                    }
2422                }
2423            }
2424
2425            mCacheDir = preparePackageParserCache(mIsUpgrade);
2426
2427            // Set flag to monitor and not change apk file paths when
2428            // scanning install directories.
2429            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2430
2431            if (mIsUpgrade || mFirstBoot) {
2432                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2433            }
2434
2435            // Collect vendor overlay packages. (Do this before scanning any apps.)
2436            // For security and version matching reason, only consider
2437            // overlay packages if they reside in the right directory.
2438            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2439                    | PackageParser.PARSE_IS_SYSTEM
2440                    | PackageParser.PARSE_IS_SYSTEM_DIR
2441                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2442
2443            // Find base frameworks (resource packages without code).
2444            scanDirTracedLI(frameworkDir, mDefParseFlags
2445                    | PackageParser.PARSE_IS_SYSTEM
2446                    | PackageParser.PARSE_IS_SYSTEM_DIR
2447                    | PackageParser.PARSE_IS_PRIVILEGED,
2448                    scanFlags | SCAN_NO_DEX, 0);
2449
2450            // Collected privileged system packages.
2451            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2452            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2453                    | PackageParser.PARSE_IS_SYSTEM
2454                    | PackageParser.PARSE_IS_SYSTEM_DIR
2455                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2456
2457            // Collect ordinary system packages.
2458            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2459            scanDirTracedLI(systemAppDir, mDefParseFlags
2460                    | PackageParser.PARSE_IS_SYSTEM
2461                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2462
2463            // Collect all vendor packages.
2464            File vendorAppDir = new File("/vendor/app");
2465            try {
2466                vendorAppDir = vendorAppDir.getCanonicalFile();
2467            } catch (IOException e) {
2468                // failed to look up canonical path, continue with original one
2469            }
2470            scanDirTracedLI(vendorAppDir, mDefParseFlags
2471                    | PackageParser.PARSE_IS_SYSTEM
2472                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2473
2474            // Collect all OEM packages.
2475            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2476            scanDirTracedLI(oemAppDir, mDefParseFlags
2477                    | PackageParser.PARSE_IS_SYSTEM
2478                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2479
2480            // Prune any system packages that no longer exist.
2481            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2482            if (!mOnlyCore) {
2483                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2484                while (psit.hasNext()) {
2485                    PackageSetting ps = psit.next();
2486
2487                    /*
2488                     * If this is not a system app, it can't be a
2489                     * disable system app.
2490                     */
2491                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2492                        continue;
2493                    }
2494
2495                    /*
2496                     * If the package is scanned, it's not erased.
2497                     */
2498                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2499                    if (scannedPkg != null) {
2500                        /*
2501                         * If the system app is both scanned and in the
2502                         * disabled packages list, then it must have been
2503                         * added via OTA. Remove it from the currently
2504                         * scanned package so the previously user-installed
2505                         * application can be scanned.
2506                         */
2507                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2508                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2509                                    + ps.name + "; removing system app.  Last known codePath="
2510                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2511                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2512                                    + scannedPkg.mVersionCode);
2513                            removePackageLI(scannedPkg, true);
2514                            mExpectingBetter.put(ps.name, ps.codePath);
2515                        }
2516
2517                        continue;
2518                    }
2519
2520                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2521                        psit.remove();
2522                        logCriticalInfo(Log.WARN, "System package " + ps.name
2523                                + " no longer exists; it's data will be wiped");
2524                        // Actual deletion of code and data will be handled by later
2525                        // reconciliation step
2526                    } else {
2527                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2528                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2529                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2530                        }
2531                    }
2532                }
2533            }
2534
2535            //look for any incomplete package installations
2536            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2537            for (int i = 0; i < deletePkgsList.size(); i++) {
2538                // Actual deletion of code and data will be handled by later
2539                // reconciliation step
2540                final String packageName = deletePkgsList.get(i).name;
2541                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2542                synchronized (mPackages) {
2543                    mSettings.removePackageLPw(packageName);
2544                }
2545            }
2546
2547            //delete tmp files
2548            deleteTempPackageFiles();
2549
2550            // Remove any shared userIDs that have no associated packages
2551            mSettings.pruneSharedUsersLPw();
2552
2553            if (!mOnlyCore) {
2554                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2555                        SystemClock.uptimeMillis());
2556                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2557
2558                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2559                        | PackageParser.PARSE_FORWARD_LOCK,
2560                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2561
2562                /**
2563                 * Remove disable package settings for any updated system
2564                 * apps that were removed via an OTA. If they're not a
2565                 * previously-updated app, remove them completely.
2566                 * Otherwise, just revoke their system-level permissions.
2567                 */
2568                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2569                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2570                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2571
2572                    String msg;
2573                    if (deletedPkg == null) {
2574                        msg = "Updated system package " + deletedAppName
2575                                + " no longer exists; it's data will be wiped";
2576                        // Actual deletion of code and data will be handled by later
2577                        // reconciliation step
2578                    } else {
2579                        msg = "Updated system app + " + deletedAppName
2580                                + " no longer present; removing system privileges for "
2581                                + deletedAppName;
2582
2583                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2584
2585                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2586                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2587                    }
2588                    logCriticalInfo(Log.WARN, msg);
2589                }
2590
2591                /**
2592                 * Make sure all system apps that we expected to appear on
2593                 * the userdata partition actually showed up. If they never
2594                 * appeared, crawl back and revive the system version.
2595                 */
2596                for (int i = 0; i < mExpectingBetter.size(); i++) {
2597                    final String packageName = mExpectingBetter.keyAt(i);
2598                    if (!mPackages.containsKey(packageName)) {
2599                        final File scanFile = mExpectingBetter.valueAt(i);
2600
2601                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2602                                + " but never showed up; reverting to system");
2603
2604                        int reparseFlags = mDefParseFlags;
2605                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2606                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2607                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2608                                    | PackageParser.PARSE_IS_PRIVILEGED;
2609                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2610                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2611                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2612                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2613                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2614                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2615                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2616                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2617                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2618                        } else {
2619                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2620                            continue;
2621                        }
2622
2623                        mSettings.enableSystemPackageLPw(packageName);
2624
2625                        try {
2626                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2627                        } catch (PackageManagerException e) {
2628                            Slog.e(TAG, "Failed to parse original system package: "
2629                                    + e.getMessage());
2630                        }
2631                    }
2632                }
2633            }
2634            mExpectingBetter.clear();
2635
2636            // Resolve the storage manager.
2637            mStorageManagerPackage = getStorageManagerPackageName();
2638
2639            // Resolve protected action filters. Only the setup wizard is allowed to
2640            // have a high priority filter for these actions.
2641            mSetupWizardPackage = getSetupWizardPackageName();
2642            if (mProtectedFilters.size() > 0) {
2643                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2644                    Slog.i(TAG, "No setup wizard;"
2645                        + " All protected intents capped to priority 0");
2646                }
2647                for (ActivityIntentInfo filter : mProtectedFilters) {
2648                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2649                        if (DEBUG_FILTERS) {
2650                            Slog.i(TAG, "Found setup wizard;"
2651                                + " allow priority " + filter.getPriority() + ";"
2652                                + " package: " + filter.activity.info.packageName
2653                                + " activity: " + filter.activity.className
2654                                + " priority: " + filter.getPriority());
2655                        }
2656                        // skip setup wizard; allow it to keep the high priority filter
2657                        continue;
2658                    }
2659                    Slog.w(TAG, "Protected action; cap priority to 0;"
2660                            + " package: " + filter.activity.info.packageName
2661                            + " activity: " + filter.activity.className
2662                            + " origPrio: " + filter.getPriority());
2663                    filter.setPriority(0);
2664                }
2665            }
2666            mDeferProtectedFilters = false;
2667            mProtectedFilters.clear();
2668
2669            // Now that we know all of the shared libraries, update all clients to have
2670            // the correct library paths.
2671            updateAllSharedLibrariesLPw(null);
2672
2673            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2674                // NOTE: We ignore potential failures here during a system scan (like
2675                // the rest of the commands above) because there's precious little we
2676                // can do about it. A settings error is reported, though.
2677                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2678            }
2679
2680            // Now that we know all the packages we are keeping,
2681            // read and update their last usage times.
2682            mPackageUsage.read(mPackages);
2683            mCompilerStats.read();
2684
2685            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2686                    SystemClock.uptimeMillis());
2687            Slog.i(TAG, "Time to scan packages: "
2688                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2689                    + " seconds");
2690
2691            // If the platform SDK has changed since the last time we booted,
2692            // we need to re-grant app permission to catch any new ones that
2693            // appear.  This is really a hack, and means that apps can in some
2694            // cases get permissions that the user didn't initially explicitly
2695            // allow...  it would be nice to have some better way to handle
2696            // this situation.
2697            int updateFlags = UPDATE_PERMISSIONS_ALL;
2698            if (ver.sdkVersion != mSdkVersion) {
2699                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2700                        + mSdkVersion + "; regranting permissions for internal storage");
2701                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2702            }
2703            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2704            ver.sdkVersion = mSdkVersion;
2705
2706            // If this is the first boot or an update from pre-M, and it is a normal
2707            // boot, then we need to initialize the default preferred apps across
2708            // all defined users.
2709            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2710                for (UserInfo user : sUserManager.getUsers(true)) {
2711                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2712                    applyFactoryDefaultBrowserLPw(user.id);
2713                    primeDomainVerificationsLPw(user.id);
2714                }
2715            }
2716
2717            // Prepare storage for system user really early during boot,
2718            // since core system apps like SettingsProvider and SystemUI
2719            // can't wait for user to start
2720            final int storageFlags;
2721            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2722                storageFlags = StorageManager.FLAG_STORAGE_DE;
2723            } else {
2724                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2725            }
2726            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2727                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2728                    true /* onlyCoreApps */);
2729            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2730                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2731                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2732                traceLog.traceBegin("AppDataFixup");
2733                try {
2734                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2735                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2736                } catch (InstallerException e) {
2737                    Slog.w(TAG, "Trouble fixing GIDs", e);
2738                }
2739                traceLog.traceEnd();
2740
2741                traceLog.traceBegin("AppDataPrepare");
2742                if (deferPackages == null || deferPackages.isEmpty()) {
2743                    return;
2744                }
2745                int count = 0;
2746                for (String pkgName : deferPackages) {
2747                    PackageParser.Package pkg = null;
2748                    synchronized (mPackages) {
2749                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2750                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2751                            pkg = ps.pkg;
2752                        }
2753                    }
2754                    if (pkg != null) {
2755                        synchronized (mInstallLock) {
2756                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2757                                    true /* maybeMigrateAppData */);
2758                        }
2759                        count++;
2760                    }
2761                }
2762                traceLog.traceEnd();
2763                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2764            }, "prepareAppData");
2765
2766            // If this is first boot after an OTA, and a normal boot, then
2767            // we need to clear code cache directories.
2768            // Note that we do *not* clear the application profiles. These remain valid
2769            // across OTAs and are used to drive profile verification (post OTA) and
2770            // profile compilation (without waiting to collect a fresh set of profiles).
2771            if (mIsUpgrade && !onlyCore) {
2772                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2773                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2774                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2775                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2776                        // No apps are running this early, so no need to freeze
2777                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2778                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2779                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2780                    }
2781                }
2782                ver.fingerprint = Build.FINGERPRINT;
2783            }
2784
2785            checkDefaultBrowser();
2786
2787            // clear only after permissions and other defaults have been updated
2788            mExistingSystemPackages.clear();
2789            mPromoteSystemApps = false;
2790
2791            // All the changes are done during package scanning.
2792            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2793
2794            // can downgrade to reader
2795            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2796            mSettings.writeLPr();
2797            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2798
2799            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2800                    SystemClock.uptimeMillis());
2801
2802            if (!mOnlyCore) {
2803                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2804                mRequiredInstallerPackage = getRequiredInstallerLPr();
2805                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2806                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2807                if (mIntentFilterVerifierComponent != null) {
2808                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2809                            mIntentFilterVerifierComponent);
2810                } else {
2811                    mIntentFilterVerifier = null;
2812                }
2813                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2814                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2815                        SharedLibraryInfo.VERSION_UNDEFINED);
2816                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2817                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2818                        SharedLibraryInfo.VERSION_UNDEFINED);
2819            } else {
2820                mRequiredVerifierPackage = null;
2821                mRequiredInstallerPackage = null;
2822                mRequiredUninstallerPackage = null;
2823                mIntentFilterVerifierComponent = null;
2824                mIntentFilterVerifier = null;
2825                mServicesSystemSharedLibraryPackageName = null;
2826                mSharedSystemSharedLibraryPackageName = null;
2827            }
2828
2829            mInstallerService = new PackageInstallerService(context, this);
2830            final Pair<ComponentName, String> instantAppResolverComponent =
2831                    getInstantAppResolverLPr();
2832            if (instantAppResolverComponent != null) {
2833                if (DEBUG_EPHEMERAL) {
2834                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2835                }
2836                mInstantAppResolverConnection = new EphemeralResolverConnection(
2837                        mContext, instantAppResolverComponent.first,
2838                        instantAppResolverComponent.second);
2839                mInstantAppResolverSettingsComponent =
2840                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2841            } else {
2842                mInstantAppResolverConnection = null;
2843                mInstantAppResolverSettingsComponent = null;
2844            }
2845            updateInstantAppInstallerLocked(null);
2846
2847            // Read and update the usage of dex files.
2848            // Do this at the end of PM init so that all the packages have their
2849            // data directory reconciled.
2850            // At this point we know the code paths of the packages, so we can validate
2851            // the disk file and build the internal cache.
2852            // The usage file is expected to be small so loading and verifying it
2853            // should take a fairly small time compare to the other activities (e.g. package
2854            // scanning).
2855            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2856            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2857            for (int userId : currentUserIds) {
2858                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2859            }
2860            mDexManager.load(userPackages);
2861        } // synchronized (mPackages)
2862        } // synchronized (mInstallLock)
2863
2864        // Now after opening every single application zip, make sure they
2865        // are all flushed.  Not really needed, but keeps things nice and
2866        // tidy.
2867        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2868        Runtime.getRuntime().gc();
2869        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2870
2871        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2872        FallbackCategoryProvider.loadFallbacks();
2873        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2874
2875        // The initial scanning above does many calls into installd while
2876        // holding the mPackages lock, but we're mostly interested in yelling
2877        // once we have a booted system.
2878        mInstaller.setWarnIfHeld(mPackages);
2879
2880        // Expose private service for system components to use.
2881        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2882        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2883    }
2884
2885    private void updateInstantAppInstallerLocked(String modifiedPackage) {
2886        // we're only interested in updating the installer appliction when 1) it's not
2887        // already set or 2) the modified package is the installer
2888        if (mInstantAppInstallerActivity != null
2889                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
2890                        .equals(modifiedPackage)) {
2891            return;
2892        }
2893        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
2894    }
2895
2896    private static File preparePackageParserCache(boolean isUpgrade) {
2897        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2898            return null;
2899        }
2900
2901        // Disable package parsing on eng builds to allow for faster incremental development.
2902        if ("eng".equals(Build.TYPE)) {
2903            return null;
2904        }
2905
2906        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2907            Slog.i(TAG, "Disabling package parser cache due to system property.");
2908            return null;
2909        }
2910
2911        // The base directory for the package parser cache lives under /data/system/.
2912        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2913                "package_cache");
2914        if (cacheBaseDir == null) {
2915            return null;
2916        }
2917
2918        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2919        // This also serves to "GC" unused entries when the package cache version changes (which
2920        // can only happen during upgrades).
2921        if (isUpgrade) {
2922            FileUtils.deleteContents(cacheBaseDir);
2923        }
2924
2925
2926        // Return the versioned package cache directory. This is something like
2927        // "/data/system/package_cache/1"
2928        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2929
2930        // The following is a workaround to aid development on non-numbered userdebug
2931        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2932        // the system partition is newer.
2933        //
2934        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2935        // that starts with "eng." to signify that this is an engineering build and not
2936        // destined for release.
2937        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2938            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2939
2940            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2941            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2942            // in general and should not be used for production changes. In this specific case,
2943            // we know that they will work.
2944            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2945            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2946                FileUtils.deleteContents(cacheBaseDir);
2947                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2948            }
2949        }
2950
2951        return cacheDir;
2952    }
2953
2954    @Override
2955    public boolean isFirstBoot() {
2956        return mFirstBoot;
2957    }
2958
2959    @Override
2960    public boolean isOnlyCoreApps() {
2961        return mOnlyCore;
2962    }
2963
2964    @Override
2965    public boolean isUpgrade() {
2966        return mIsUpgrade;
2967    }
2968
2969    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2970        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2971
2972        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2973                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2974                UserHandle.USER_SYSTEM);
2975        if (matches.size() == 1) {
2976            return matches.get(0).getComponentInfo().packageName;
2977        } else if (matches.size() == 0) {
2978            Log.e(TAG, "There should probably be a verifier, but, none were found");
2979            return null;
2980        }
2981        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2982    }
2983
2984    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2985        synchronized (mPackages) {
2986            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2987            if (libraryEntry == null) {
2988                throw new IllegalStateException("Missing required shared library:" + name);
2989            }
2990            return libraryEntry.apk;
2991        }
2992    }
2993
2994    private @NonNull String getRequiredInstallerLPr() {
2995        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2996        intent.addCategory(Intent.CATEGORY_DEFAULT);
2997        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2998
2999        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3000                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3001                UserHandle.USER_SYSTEM);
3002        if (matches.size() == 1) {
3003            ResolveInfo resolveInfo = matches.get(0);
3004            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3005                throw new RuntimeException("The installer must be a privileged app");
3006            }
3007            return matches.get(0).getComponentInfo().packageName;
3008        } else {
3009            throw new RuntimeException("There must be exactly one installer; found " + matches);
3010        }
3011    }
3012
3013    private @NonNull String getRequiredUninstallerLPr() {
3014        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3015        intent.addCategory(Intent.CATEGORY_DEFAULT);
3016        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3017
3018        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3019                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3020                UserHandle.USER_SYSTEM);
3021        if (resolveInfo == null ||
3022                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3023            throw new RuntimeException("There must be exactly one uninstaller; found "
3024                    + resolveInfo);
3025        }
3026        return resolveInfo.getComponentInfo().packageName;
3027    }
3028
3029    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3030        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3031
3032        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3033                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3034                UserHandle.USER_SYSTEM);
3035        ResolveInfo best = null;
3036        final int N = matches.size();
3037        for (int i = 0; i < N; i++) {
3038            final ResolveInfo cur = matches.get(i);
3039            final String packageName = cur.getComponentInfo().packageName;
3040            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3041                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3042                continue;
3043            }
3044
3045            if (best == null || cur.priority > best.priority) {
3046                best = cur;
3047            }
3048        }
3049
3050        if (best != null) {
3051            return best.getComponentInfo().getComponentName();
3052        }
3053        Slog.w(TAG, "Intent filter verifier not found");
3054        return null;
3055    }
3056
3057    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3058        final String[] packageArray =
3059                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3060        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3061            if (DEBUG_EPHEMERAL) {
3062                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3063            }
3064            return null;
3065        }
3066
3067        final int callingUid = Binder.getCallingUid();
3068        final int resolveFlags =
3069                MATCH_DIRECT_BOOT_AWARE
3070                | MATCH_DIRECT_BOOT_UNAWARE
3071                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3072        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3073        final Intent resolverIntent = new Intent(actionName);
3074        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3075                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3076        // temporarily look for the old action
3077        if (resolvers.size() == 0) {
3078            if (DEBUG_EPHEMERAL) {
3079                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3080            }
3081            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3082            resolverIntent.setAction(actionName);
3083            resolvers = queryIntentServicesInternal(resolverIntent, null,
3084                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3085        }
3086        final int N = resolvers.size();
3087        if (N == 0) {
3088            if (DEBUG_EPHEMERAL) {
3089                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3090            }
3091            return null;
3092        }
3093
3094        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3095        for (int i = 0; i < N; i++) {
3096            final ResolveInfo info = resolvers.get(i);
3097
3098            if (info.serviceInfo == null) {
3099                continue;
3100            }
3101
3102            final String packageName = info.serviceInfo.packageName;
3103            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3104                if (DEBUG_EPHEMERAL) {
3105                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3106                            + " pkg: " + packageName + ", info:" + info);
3107                }
3108                continue;
3109            }
3110
3111            if (DEBUG_EPHEMERAL) {
3112                Slog.v(TAG, "Ephemeral resolver found;"
3113                        + " pkg: " + packageName + ", info:" + info);
3114            }
3115            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3116        }
3117        if (DEBUG_EPHEMERAL) {
3118            Slog.v(TAG, "Ephemeral resolver NOT found");
3119        }
3120        return null;
3121    }
3122
3123    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3124        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3125        intent.addCategory(Intent.CATEGORY_DEFAULT);
3126        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3127
3128        final int resolveFlags =
3129                MATCH_DIRECT_BOOT_AWARE
3130                | MATCH_DIRECT_BOOT_UNAWARE
3131                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3132        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3133                resolveFlags, UserHandle.USER_SYSTEM);
3134        // temporarily look for the old action
3135        if (matches.isEmpty()) {
3136            if (DEBUG_EPHEMERAL) {
3137                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3138            }
3139            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3140            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3141                    resolveFlags, UserHandle.USER_SYSTEM);
3142        }
3143        Iterator<ResolveInfo> iter = matches.iterator();
3144        while (iter.hasNext()) {
3145            final ResolveInfo rInfo = iter.next();
3146            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3147            if (ps != null) {
3148                final PermissionsState permissionsState = ps.getPermissionsState();
3149                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3150                    continue;
3151                }
3152            }
3153            iter.remove();
3154        }
3155        if (matches.size() == 0) {
3156            return null;
3157        } else if (matches.size() == 1) {
3158            return (ActivityInfo) matches.get(0).getComponentInfo();
3159        } else {
3160            throw new RuntimeException(
3161                    "There must be at most one ephemeral installer; found " + matches);
3162        }
3163    }
3164
3165    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3166            @NonNull ComponentName resolver) {
3167        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3168                .addCategory(Intent.CATEGORY_DEFAULT)
3169                .setPackage(resolver.getPackageName());
3170        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3171        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3172                UserHandle.USER_SYSTEM);
3173        // temporarily look for the old action
3174        if (matches.isEmpty()) {
3175            if (DEBUG_EPHEMERAL) {
3176                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3177            }
3178            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3179            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3180                    UserHandle.USER_SYSTEM);
3181        }
3182        if (matches.isEmpty()) {
3183            return null;
3184        }
3185        return matches.get(0).getComponentInfo().getComponentName();
3186    }
3187
3188    private void primeDomainVerificationsLPw(int userId) {
3189        if (DEBUG_DOMAIN_VERIFICATION) {
3190            Slog.d(TAG, "Priming domain verifications in user " + userId);
3191        }
3192
3193        SystemConfig systemConfig = SystemConfig.getInstance();
3194        ArraySet<String> packages = systemConfig.getLinkedApps();
3195
3196        for (String packageName : packages) {
3197            PackageParser.Package pkg = mPackages.get(packageName);
3198            if (pkg != null) {
3199                if (!pkg.isSystemApp()) {
3200                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3201                    continue;
3202                }
3203
3204                ArraySet<String> domains = null;
3205                for (PackageParser.Activity a : pkg.activities) {
3206                    for (ActivityIntentInfo filter : a.intents) {
3207                        if (hasValidDomains(filter)) {
3208                            if (domains == null) {
3209                                domains = new ArraySet<String>();
3210                            }
3211                            domains.addAll(filter.getHostsList());
3212                        }
3213                    }
3214                }
3215
3216                if (domains != null && domains.size() > 0) {
3217                    if (DEBUG_DOMAIN_VERIFICATION) {
3218                        Slog.v(TAG, "      + " + packageName);
3219                    }
3220                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3221                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3222                    // and then 'always' in the per-user state actually used for intent resolution.
3223                    final IntentFilterVerificationInfo ivi;
3224                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3225                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3226                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3227                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3228                } else {
3229                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3230                            + "' does not handle web links");
3231                }
3232            } else {
3233                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3234            }
3235        }
3236
3237        scheduleWritePackageRestrictionsLocked(userId);
3238        scheduleWriteSettingsLocked();
3239    }
3240
3241    private void applyFactoryDefaultBrowserLPw(int userId) {
3242        // The default browser app's package name is stored in a string resource,
3243        // with a product-specific overlay used for vendor customization.
3244        String browserPkg = mContext.getResources().getString(
3245                com.android.internal.R.string.default_browser);
3246        if (!TextUtils.isEmpty(browserPkg)) {
3247            // non-empty string => required to be a known package
3248            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3249            if (ps == null) {
3250                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3251                browserPkg = null;
3252            } else {
3253                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3254            }
3255        }
3256
3257        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3258        // default.  If there's more than one, just leave everything alone.
3259        if (browserPkg == null) {
3260            calculateDefaultBrowserLPw(userId);
3261        }
3262    }
3263
3264    private void calculateDefaultBrowserLPw(int userId) {
3265        List<String> allBrowsers = resolveAllBrowserApps(userId);
3266        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3267        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3268    }
3269
3270    private List<String> resolveAllBrowserApps(int userId) {
3271        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3272        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3273                PackageManager.MATCH_ALL, userId);
3274
3275        final int count = list.size();
3276        List<String> result = new ArrayList<String>(count);
3277        for (int i=0; i<count; i++) {
3278            ResolveInfo info = list.get(i);
3279            if (info.activityInfo == null
3280                    || !info.handleAllWebDataURI
3281                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3282                    || result.contains(info.activityInfo.packageName)) {
3283                continue;
3284            }
3285            result.add(info.activityInfo.packageName);
3286        }
3287
3288        return result;
3289    }
3290
3291    private boolean packageIsBrowser(String packageName, int userId) {
3292        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3293                PackageManager.MATCH_ALL, userId);
3294        final int N = list.size();
3295        for (int i = 0; i < N; i++) {
3296            ResolveInfo info = list.get(i);
3297            if (packageName.equals(info.activityInfo.packageName)) {
3298                return true;
3299            }
3300        }
3301        return false;
3302    }
3303
3304    private void checkDefaultBrowser() {
3305        final int myUserId = UserHandle.myUserId();
3306        final String packageName = getDefaultBrowserPackageName(myUserId);
3307        if (packageName != null) {
3308            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3309            if (info == null) {
3310                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3311                synchronized (mPackages) {
3312                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3313                }
3314            }
3315        }
3316    }
3317
3318    @Override
3319    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3320            throws RemoteException {
3321        try {
3322            return super.onTransact(code, data, reply, flags);
3323        } catch (RuntimeException e) {
3324            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3325                Slog.wtf(TAG, "Package Manager Crash", e);
3326            }
3327            throw e;
3328        }
3329    }
3330
3331    static int[] appendInts(int[] cur, int[] add) {
3332        if (add == null) return cur;
3333        if (cur == null) return add;
3334        final int N = add.length;
3335        for (int i=0; i<N; i++) {
3336            cur = appendInt(cur, add[i]);
3337        }
3338        return cur;
3339    }
3340
3341    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3342        if (!sUserManager.exists(userId)) return null;
3343        if (ps == null) {
3344            return null;
3345        }
3346        final PackageParser.Package p = ps.pkg;
3347        if (p == null) {
3348            return null;
3349        }
3350        // Filter out ephemeral app metadata:
3351        //   * The system/shell/root can see metadata for any app
3352        //   * An installed app can see metadata for 1) other installed apps
3353        //     and 2) ephemeral apps that have explicitly interacted with it
3354        //   * Ephemeral apps can only see their own data and exposed installed apps
3355        //   * Holding a signature permission allows seeing instant apps
3356        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3357        if (callingAppId != Process.SYSTEM_UID
3358                && callingAppId != Process.SHELL_UID
3359                && callingAppId != Process.ROOT_UID
3360                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3361                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3362            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3363            if (instantAppPackageName != null) {
3364                // ephemeral apps can only get information on themselves or
3365                // installed apps that are exposed.
3366                if (!instantAppPackageName.equals(p.packageName)
3367                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3368                    return null;
3369                }
3370            } else {
3371                if (ps.getInstantApp(userId)) {
3372                    // only get access to the ephemeral app if we've been granted access
3373                    if (!mInstantAppRegistry.isInstantAccessGranted(
3374                            userId, callingAppId, ps.appId)) {
3375                        return null;
3376                    }
3377                }
3378            }
3379        }
3380
3381        final PermissionsState permissionsState = ps.getPermissionsState();
3382
3383        // Compute GIDs only if requested
3384        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3385                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3386        // Compute granted permissions only if package has requested permissions
3387        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3388                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3389        final PackageUserState state = ps.readUserState(userId);
3390
3391        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3392                && ps.isSystem()) {
3393            flags |= MATCH_ANY_USER;
3394        }
3395
3396        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3397                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3398
3399        if (packageInfo == null) {
3400            return null;
3401        }
3402
3403        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3404
3405        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3406                resolveExternalPackageNameLPr(p);
3407
3408        return packageInfo;
3409    }
3410
3411    @Override
3412    public void checkPackageStartable(String packageName, int userId) {
3413        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3414
3415        synchronized (mPackages) {
3416            final PackageSetting ps = mSettings.mPackages.get(packageName);
3417            if (ps == null) {
3418                throw new SecurityException("Package " + packageName + " was not found!");
3419            }
3420
3421            if (!ps.getInstalled(userId)) {
3422                throw new SecurityException(
3423                        "Package " + packageName + " was not installed for user " + userId + "!");
3424            }
3425
3426            if (mSafeMode && !ps.isSystem()) {
3427                throw new SecurityException("Package " + packageName + " not a system app!");
3428            }
3429
3430            if (mFrozenPackages.contains(packageName)) {
3431                throw new SecurityException("Package " + packageName + " is currently frozen!");
3432            }
3433
3434            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3435                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3436                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3437            }
3438        }
3439    }
3440
3441    @Override
3442    public boolean isPackageAvailable(String packageName, int userId) {
3443        if (!sUserManager.exists(userId)) return false;
3444        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3445                false /* requireFullPermission */, false /* checkShell */, "is package available");
3446        synchronized (mPackages) {
3447            PackageParser.Package p = mPackages.get(packageName);
3448            if (p != null) {
3449                final PackageSetting ps = (PackageSetting) p.mExtras;
3450                if (ps != null) {
3451                    final PackageUserState state = ps.readUserState(userId);
3452                    if (state != null) {
3453                        return PackageParser.isAvailable(state);
3454                    }
3455                }
3456            }
3457        }
3458        return false;
3459    }
3460
3461    @Override
3462    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3463        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3464                flags, userId);
3465    }
3466
3467    @Override
3468    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3469            int flags, int userId) {
3470        return getPackageInfoInternal(versionedPackage.getPackageName(),
3471                // TODO: We will change version code to long, so in the new API it is long
3472                (int) versionedPackage.getVersionCode(), flags, userId);
3473    }
3474
3475    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3476            int flags, int userId) {
3477        if (!sUserManager.exists(userId)) return null;
3478        flags = updateFlagsForPackage(flags, userId, packageName);
3479        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3480                false /* requireFullPermission */, false /* checkShell */, "get package info");
3481
3482        // reader
3483        synchronized (mPackages) {
3484            // Normalize package name to handle renamed packages and static libs
3485            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3486
3487            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3488            if (matchFactoryOnly) {
3489                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3490                if (ps != null) {
3491                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3492                        return null;
3493                    }
3494                    return generatePackageInfo(ps, flags, userId);
3495                }
3496            }
3497
3498            PackageParser.Package p = mPackages.get(packageName);
3499            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3500                return null;
3501            }
3502            if (DEBUG_PACKAGE_INFO)
3503                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3504            if (p != null) {
3505                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3506                        Binder.getCallingUid(), userId)) {
3507                    return null;
3508                }
3509                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3510            }
3511            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3512                final PackageSetting ps = mSettings.mPackages.get(packageName);
3513                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3514                    return null;
3515                }
3516                return generatePackageInfo(ps, flags, userId);
3517            }
3518        }
3519        return null;
3520    }
3521
3522
3523    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3524        // System/shell/root get to see all static libs
3525        final int appId = UserHandle.getAppId(uid);
3526        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3527                || appId == Process.ROOT_UID) {
3528            return false;
3529        }
3530
3531        // No package means no static lib as it is always on internal storage
3532        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3533            return false;
3534        }
3535
3536        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3537                ps.pkg.staticSharedLibVersion);
3538        if (libEntry == null) {
3539            return false;
3540        }
3541
3542        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3543        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3544        if (uidPackageNames == null) {
3545            return true;
3546        }
3547
3548        for (String uidPackageName : uidPackageNames) {
3549            if (ps.name.equals(uidPackageName)) {
3550                return false;
3551            }
3552            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3553            if (uidPs != null) {
3554                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3555                        libEntry.info.getName());
3556                if (index < 0) {
3557                    continue;
3558                }
3559                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3560                    return false;
3561                }
3562            }
3563        }
3564        return true;
3565    }
3566
3567    @Override
3568    public String[] currentToCanonicalPackageNames(String[] names) {
3569        String[] out = new String[names.length];
3570        // reader
3571        synchronized (mPackages) {
3572            for (int i=names.length-1; i>=0; i--) {
3573                PackageSetting ps = mSettings.mPackages.get(names[i]);
3574                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3575            }
3576        }
3577        return out;
3578    }
3579
3580    @Override
3581    public String[] canonicalToCurrentPackageNames(String[] names) {
3582        String[] out = new String[names.length];
3583        // reader
3584        synchronized (mPackages) {
3585            for (int i=names.length-1; i>=0; i--) {
3586                String cur = mSettings.getRenamedPackageLPr(names[i]);
3587                out[i] = cur != null ? cur : names[i];
3588            }
3589        }
3590        return out;
3591    }
3592
3593    @Override
3594    public int getPackageUid(String packageName, int flags, int userId) {
3595        if (!sUserManager.exists(userId)) return -1;
3596        flags = updateFlagsForPackage(flags, userId, packageName);
3597        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3598                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3599
3600        // reader
3601        synchronized (mPackages) {
3602            final PackageParser.Package p = mPackages.get(packageName);
3603            if (p != null && p.isMatch(flags)) {
3604                return UserHandle.getUid(userId, p.applicationInfo.uid);
3605            }
3606            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3607                final PackageSetting ps = mSettings.mPackages.get(packageName);
3608                if (ps != null && ps.isMatch(flags)) {
3609                    return UserHandle.getUid(userId, ps.appId);
3610                }
3611            }
3612        }
3613
3614        return -1;
3615    }
3616
3617    @Override
3618    public int[] getPackageGids(String packageName, int flags, int userId) {
3619        if (!sUserManager.exists(userId)) return null;
3620        flags = updateFlagsForPackage(flags, userId, packageName);
3621        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3622                false /* requireFullPermission */, false /* checkShell */,
3623                "getPackageGids");
3624
3625        // reader
3626        synchronized (mPackages) {
3627            final PackageParser.Package p = mPackages.get(packageName);
3628            if (p != null && p.isMatch(flags)) {
3629                PackageSetting ps = (PackageSetting) p.mExtras;
3630                // TODO: Shouldn't this be checking for package installed state for userId and
3631                // return null?
3632                return ps.getPermissionsState().computeGids(userId);
3633            }
3634            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3635                final PackageSetting ps = mSettings.mPackages.get(packageName);
3636                if (ps != null && ps.isMatch(flags)) {
3637                    return ps.getPermissionsState().computeGids(userId);
3638                }
3639            }
3640        }
3641
3642        return null;
3643    }
3644
3645    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3646        if (bp.perm != null) {
3647            return PackageParser.generatePermissionInfo(bp.perm, flags);
3648        }
3649        PermissionInfo pi = new PermissionInfo();
3650        pi.name = bp.name;
3651        pi.packageName = bp.sourcePackage;
3652        pi.nonLocalizedLabel = bp.name;
3653        pi.protectionLevel = bp.protectionLevel;
3654        return pi;
3655    }
3656
3657    @Override
3658    public PermissionInfo getPermissionInfo(String name, int flags) {
3659        // reader
3660        synchronized (mPackages) {
3661            final BasePermission p = mSettings.mPermissions.get(name);
3662            if (p != null) {
3663                return generatePermissionInfo(p, flags);
3664            }
3665            return null;
3666        }
3667    }
3668
3669    @Override
3670    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3671            int flags) {
3672        // reader
3673        synchronized (mPackages) {
3674            if (group != null && !mPermissionGroups.containsKey(group)) {
3675                // This is thrown as NameNotFoundException
3676                return null;
3677            }
3678
3679            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3680            for (BasePermission p : mSettings.mPermissions.values()) {
3681                if (group == null) {
3682                    if (p.perm == null || p.perm.info.group == null) {
3683                        out.add(generatePermissionInfo(p, flags));
3684                    }
3685                } else {
3686                    if (p.perm != null && group.equals(p.perm.info.group)) {
3687                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3688                    }
3689                }
3690            }
3691            return new ParceledListSlice<>(out);
3692        }
3693    }
3694
3695    @Override
3696    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3697        // reader
3698        synchronized (mPackages) {
3699            return PackageParser.generatePermissionGroupInfo(
3700                    mPermissionGroups.get(name), flags);
3701        }
3702    }
3703
3704    @Override
3705    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3706        // reader
3707        synchronized (mPackages) {
3708            final int N = mPermissionGroups.size();
3709            ArrayList<PermissionGroupInfo> out
3710                    = new ArrayList<PermissionGroupInfo>(N);
3711            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3712                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3713            }
3714            return new ParceledListSlice<>(out);
3715        }
3716    }
3717
3718    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3719            int uid, int userId) {
3720        if (!sUserManager.exists(userId)) return null;
3721        PackageSetting ps = mSettings.mPackages.get(packageName);
3722        if (ps != null) {
3723            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3724                return null;
3725            }
3726            if (ps.pkg == null) {
3727                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3728                if (pInfo != null) {
3729                    return pInfo.applicationInfo;
3730                }
3731                return null;
3732            }
3733            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3734                    ps.readUserState(userId), userId);
3735            if (ai != null) {
3736                rebaseEnabledOverlays(ai, userId);
3737                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3738            }
3739            return ai;
3740        }
3741        return null;
3742    }
3743
3744    @Override
3745    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3746        if (!sUserManager.exists(userId)) return null;
3747        flags = updateFlagsForApplication(flags, userId, packageName);
3748        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3749                false /* requireFullPermission */, false /* checkShell */, "get application info");
3750
3751        // writer
3752        synchronized (mPackages) {
3753            // Normalize package name to handle renamed packages and static libs
3754            packageName = resolveInternalPackageNameLPr(packageName,
3755                    PackageManager.VERSION_CODE_HIGHEST);
3756
3757            PackageParser.Package p = mPackages.get(packageName);
3758            if (DEBUG_PACKAGE_INFO) Log.v(
3759                    TAG, "getApplicationInfo " + packageName
3760                    + ": " + p);
3761            if (p != null) {
3762                PackageSetting ps = mSettings.mPackages.get(packageName);
3763                if (ps == null) return null;
3764                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3765                    return null;
3766                }
3767                // Note: isEnabledLP() does not apply here - always return info
3768                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3769                        p, flags, ps.readUserState(userId), userId);
3770                if (ai != null) {
3771                    rebaseEnabledOverlays(ai, userId);
3772                    ai.packageName = resolveExternalPackageNameLPr(p);
3773                }
3774                return ai;
3775            }
3776            if ("android".equals(packageName)||"system".equals(packageName)) {
3777                return mAndroidApplication;
3778            }
3779            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3780                // Already generates the external package name
3781                return generateApplicationInfoFromSettingsLPw(packageName,
3782                        Binder.getCallingUid(), flags, userId);
3783            }
3784        }
3785        return null;
3786    }
3787
3788    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3789        List<String> paths = new ArrayList<>();
3790        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3791            mEnabledOverlayPaths.get(userId);
3792        if (userSpecificOverlays != null) {
3793            if (!"android".equals(ai.packageName)) {
3794                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3795                if (frameworkOverlays != null) {
3796                    paths.addAll(frameworkOverlays);
3797                }
3798            }
3799
3800            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3801            if (appOverlays != null) {
3802                paths.addAll(appOverlays);
3803            }
3804        }
3805        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3806    }
3807
3808    private String normalizePackageNameLPr(String packageName) {
3809        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3810        return normalizedPackageName != null ? normalizedPackageName : packageName;
3811    }
3812
3813    @Override
3814    public void deletePreloadsFileCache() {
3815        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3816            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3817        }
3818        File dir = Environment.getDataPreloadsFileCacheDirectory();
3819        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3820        FileUtils.deleteContents(dir);
3821    }
3822
3823    @Override
3824    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3825            final IPackageDataObserver observer) {
3826        mContext.enforceCallingOrSelfPermission(
3827                android.Manifest.permission.CLEAR_APP_CACHE, null);
3828        mHandler.post(() -> {
3829            boolean success = false;
3830            try {
3831                freeStorage(volumeUuid, freeStorageSize, 0);
3832                success = true;
3833            } catch (IOException e) {
3834                Slog.w(TAG, e);
3835            }
3836            if (observer != null) {
3837                try {
3838                    observer.onRemoveCompleted(null, success);
3839                } catch (RemoteException e) {
3840                    Slog.w(TAG, e);
3841                }
3842            }
3843        });
3844    }
3845
3846    @Override
3847    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3848            final IntentSender pi) {
3849        mContext.enforceCallingOrSelfPermission(
3850                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3851        mHandler.post(() -> {
3852            boolean success = false;
3853            try {
3854                freeStorage(volumeUuid, freeStorageSize, 0);
3855                success = true;
3856            } catch (IOException e) {
3857                Slog.w(TAG, e);
3858            }
3859            if (pi != null) {
3860                try {
3861                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3862                } catch (SendIntentException e) {
3863                    Slog.w(TAG, e);
3864                }
3865            }
3866        });
3867    }
3868
3869    /**
3870     * Blocking call to clear various types of cached data across the system
3871     * until the requested bytes are available.
3872     */
3873    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3874        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3875        final File file = storage.findPathForUuid(volumeUuid);
3876        if (file.getUsableSpace() >= bytes) return;
3877
3878        if (ENABLE_FREE_CACHE_V2) {
3879            final boolean aggressive = (storageFlags
3880                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3881            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
3882                    volumeUuid);
3883
3884            // 1. Pre-flight to determine if we have any chance to succeed
3885            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3886            if (internalVolume && (aggressive || SystemProperties
3887                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
3888                deletePreloadsFileCache();
3889                if (file.getUsableSpace() >= bytes) return;
3890            }
3891
3892            // 3. Consider parsed APK data (aggressive only)
3893            if (internalVolume && aggressive) {
3894                FileUtils.deleteContents(mCacheDir);
3895                if (file.getUsableSpace() >= bytes) return;
3896            }
3897
3898            // 4. Consider cached app data (above quotas)
3899            try {
3900                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3901            } catch (InstallerException ignored) {
3902            }
3903            if (file.getUsableSpace() >= bytes) return;
3904
3905            // 5. Consider shared libraries with refcount=0 and age>2h
3906            // 6. Consider dexopt output (aggressive only)
3907            // 7. Consider ephemeral apps not used in last week
3908
3909            // 8. Consider cached app data (below quotas)
3910            try {
3911                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3912                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3913            } catch (InstallerException ignored) {
3914            }
3915            if (file.getUsableSpace() >= bytes) return;
3916
3917            // 9. Consider DropBox entries
3918            // 10. Consider ephemeral cookies
3919
3920        } else {
3921            try {
3922                mInstaller.freeCache(volumeUuid, bytes, 0);
3923            } catch (InstallerException ignored) {
3924            }
3925            if (file.getUsableSpace() >= bytes) return;
3926        }
3927
3928        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3929    }
3930
3931    /**
3932     * Update given flags based on encryption status of current user.
3933     */
3934    private int updateFlags(int flags, int userId) {
3935        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3936                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3937            // Caller expressed an explicit opinion about what encryption
3938            // aware/unaware components they want to see, so fall through and
3939            // give them what they want
3940        } else {
3941            // Caller expressed no opinion, so match based on user state
3942            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3943                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3944            } else {
3945                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3946            }
3947        }
3948        return flags;
3949    }
3950
3951    private UserManagerInternal getUserManagerInternal() {
3952        if (mUserManagerInternal == null) {
3953            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3954        }
3955        return mUserManagerInternal;
3956    }
3957
3958    private DeviceIdleController.LocalService getDeviceIdleController() {
3959        if (mDeviceIdleController == null) {
3960            mDeviceIdleController =
3961                    LocalServices.getService(DeviceIdleController.LocalService.class);
3962        }
3963        return mDeviceIdleController;
3964    }
3965
3966    /**
3967     * Update given flags when being used to request {@link PackageInfo}.
3968     */
3969    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3970        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3971        boolean triaged = true;
3972        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3973                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3974            // Caller is asking for component details, so they'd better be
3975            // asking for specific encryption matching behavior, or be triaged
3976            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3977                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3978                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3979                triaged = false;
3980            }
3981        }
3982        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3983                | PackageManager.MATCH_SYSTEM_ONLY
3984                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3985            triaged = false;
3986        }
3987        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3988            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3989                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3990                    + Debug.getCallers(5));
3991        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3992                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3993            // If the caller wants all packages and has a restricted profile associated with it,
3994            // then match all users. This is to make sure that launchers that need to access work
3995            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3996            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3997            flags |= PackageManager.MATCH_ANY_USER;
3998        }
3999        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4000            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4001                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4002        }
4003        return updateFlags(flags, userId);
4004    }
4005
4006    /**
4007     * Update given flags when being used to request {@link ApplicationInfo}.
4008     */
4009    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4010        return updateFlagsForPackage(flags, userId, cookie);
4011    }
4012
4013    /**
4014     * Update given flags when being used to request {@link ComponentInfo}.
4015     */
4016    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4017        if (cookie instanceof Intent) {
4018            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4019                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4020            }
4021        }
4022
4023        boolean triaged = true;
4024        // Caller is asking for component details, so they'd better be
4025        // asking for specific encryption matching behavior, or be triaged
4026        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4027                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4028                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4029            triaged = false;
4030        }
4031        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4032            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4033                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4034        }
4035
4036        return updateFlags(flags, userId);
4037    }
4038
4039    /**
4040     * Update given intent when being used to request {@link ResolveInfo}.
4041     */
4042    private Intent updateIntentForResolve(Intent intent) {
4043        if (intent.getSelector() != null) {
4044            intent = intent.getSelector();
4045        }
4046        if (DEBUG_PREFERRED) {
4047            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4048        }
4049        return intent;
4050    }
4051
4052    /**
4053     * Update given flags when being used to request {@link ResolveInfo}.
4054     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4055     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4056     * flag set. However, this flag is only honoured in three circumstances:
4057     * <ul>
4058     * <li>when called from a system process</li>
4059     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4060     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4061     * action and a {@code android.intent.category.BROWSABLE} category</li>
4062     * </ul>
4063     */
4064    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4065            boolean includeInstantApps) {
4066        // Safe mode means we shouldn't match any third-party components
4067        if (mSafeMode) {
4068            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4069        }
4070        if (getInstantAppPackageName(callingUid) != null) {
4071            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4072            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4073            flags |= PackageManager.MATCH_INSTANT;
4074        } else {
4075            // Otherwise, prevent leaking ephemeral components
4076            final boolean isSpecialProcess =
4077                    callingUid == Process.SYSTEM_UID
4078                    || callingUid == Process.SHELL_UID
4079                    || callingUid == 0;
4080            final boolean allowMatchInstant =
4081                    (includeInstantApps
4082                            && Intent.ACTION_VIEW.equals(intent.getAction())
4083                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4084                            && hasWebURI(intent))
4085                    || isSpecialProcess
4086                    || mContext.checkCallingOrSelfPermission(
4087                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4088            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4089            if (!allowMatchInstant) {
4090                flags &= ~PackageManager.MATCH_INSTANT;
4091            }
4092        }
4093        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4094    }
4095
4096    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4097            int userId) {
4098        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4099        if (ret != null) {
4100            rebaseEnabledOverlays(ret.applicationInfo, userId);
4101        }
4102        return ret;
4103    }
4104
4105    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4106            PackageUserState state, int userId) {
4107        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4108        if (ai != null) {
4109            rebaseEnabledOverlays(ai.applicationInfo, userId);
4110        }
4111        return ai;
4112    }
4113
4114    @Override
4115    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4116        if (!sUserManager.exists(userId)) return null;
4117        flags = updateFlagsForComponent(flags, userId, component);
4118        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4119                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4120        synchronized (mPackages) {
4121            PackageParser.Activity a = mActivities.mActivities.get(component);
4122
4123            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4124            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4125                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4126                if (ps == null) return null;
4127                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4128            }
4129            if (mResolveComponentName.equals(component)) {
4130                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4131                        userId);
4132            }
4133        }
4134        return null;
4135    }
4136
4137    @Override
4138    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4139            String resolvedType) {
4140        synchronized (mPackages) {
4141            if (component.equals(mResolveComponentName)) {
4142                // The resolver supports EVERYTHING!
4143                return true;
4144            }
4145            PackageParser.Activity a = mActivities.mActivities.get(component);
4146            if (a == null) {
4147                return false;
4148            }
4149            for (int i=0; i<a.intents.size(); i++) {
4150                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4151                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4152                    return true;
4153                }
4154            }
4155            return false;
4156        }
4157    }
4158
4159    @Override
4160    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4161        if (!sUserManager.exists(userId)) return null;
4162        flags = updateFlagsForComponent(flags, userId, component);
4163        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4164                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4165        synchronized (mPackages) {
4166            PackageParser.Activity a = mReceivers.mActivities.get(component);
4167            if (DEBUG_PACKAGE_INFO) Log.v(
4168                TAG, "getReceiverInfo " + component + ": " + a);
4169            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4170                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4171                if (ps == null) return null;
4172                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4173            }
4174        }
4175        return null;
4176    }
4177
4178    @Override
4179    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4180        if (!sUserManager.exists(userId)) return null;
4181        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4182
4183        flags = updateFlagsForPackage(flags, userId, null);
4184
4185        final boolean canSeeStaticLibraries =
4186                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4187                        == PERMISSION_GRANTED
4188                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4189                        == PERMISSION_GRANTED
4190                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4191                        == PERMISSION_GRANTED
4192                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4193                        == PERMISSION_GRANTED;
4194
4195        synchronized (mPackages) {
4196            List<SharedLibraryInfo> result = null;
4197
4198            final int libCount = mSharedLibraries.size();
4199            for (int i = 0; i < libCount; i++) {
4200                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4201                if (versionedLib == null) {
4202                    continue;
4203                }
4204
4205                final int versionCount = versionedLib.size();
4206                for (int j = 0; j < versionCount; j++) {
4207                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4208                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4209                        break;
4210                    }
4211                    final long identity = Binder.clearCallingIdentity();
4212                    try {
4213                        // TODO: We will change version code to long, so in the new API it is long
4214                        PackageInfo packageInfo = getPackageInfoVersioned(
4215                                libInfo.getDeclaringPackage(), flags, userId);
4216                        if (packageInfo == null) {
4217                            continue;
4218                        }
4219                    } finally {
4220                        Binder.restoreCallingIdentity(identity);
4221                    }
4222
4223                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4224                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4225                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4226
4227                    if (result == null) {
4228                        result = new ArrayList<>();
4229                    }
4230                    result.add(resLibInfo);
4231                }
4232            }
4233
4234            return result != null ? new ParceledListSlice<>(result) : null;
4235        }
4236    }
4237
4238    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4239            SharedLibraryInfo libInfo, int flags, int userId) {
4240        List<VersionedPackage> versionedPackages = null;
4241        final int packageCount = mSettings.mPackages.size();
4242        for (int i = 0; i < packageCount; i++) {
4243            PackageSetting ps = mSettings.mPackages.valueAt(i);
4244
4245            if (ps == null) {
4246                continue;
4247            }
4248
4249            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4250                continue;
4251            }
4252
4253            final String libName = libInfo.getName();
4254            if (libInfo.isStatic()) {
4255                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4256                if (libIdx < 0) {
4257                    continue;
4258                }
4259                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4260                    continue;
4261                }
4262                if (versionedPackages == null) {
4263                    versionedPackages = new ArrayList<>();
4264                }
4265                // If the dependent is a static shared lib, use the public package name
4266                String dependentPackageName = ps.name;
4267                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4268                    dependentPackageName = ps.pkg.manifestPackageName;
4269                }
4270                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4271            } else if (ps.pkg != null) {
4272                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4273                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4274                    if (versionedPackages == null) {
4275                        versionedPackages = new ArrayList<>();
4276                    }
4277                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4278                }
4279            }
4280        }
4281
4282        return versionedPackages;
4283    }
4284
4285    @Override
4286    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4287        if (!sUserManager.exists(userId)) return null;
4288        flags = updateFlagsForComponent(flags, userId, component);
4289        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4290                false /* requireFullPermission */, false /* checkShell */, "get service info");
4291        synchronized (mPackages) {
4292            PackageParser.Service s = mServices.mServices.get(component);
4293            if (DEBUG_PACKAGE_INFO) Log.v(
4294                TAG, "getServiceInfo " + component + ": " + s);
4295            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4296                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4297                if (ps == null) return null;
4298                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4299                        ps.readUserState(userId), userId);
4300                if (si != null) {
4301                    rebaseEnabledOverlays(si.applicationInfo, userId);
4302                }
4303                return si;
4304            }
4305        }
4306        return null;
4307    }
4308
4309    @Override
4310    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4311        if (!sUserManager.exists(userId)) return null;
4312        flags = updateFlagsForComponent(flags, userId, component);
4313        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4314                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4315        synchronized (mPackages) {
4316            PackageParser.Provider p = mProviders.mProviders.get(component);
4317            if (DEBUG_PACKAGE_INFO) Log.v(
4318                TAG, "getProviderInfo " + component + ": " + p);
4319            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4320                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4321                if (ps == null) return null;
4322                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4323                        ps.readUserState(userId), userId);
4324                if (pi != null) {
4325                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4326                }
4327                return pi;
4328            }
4329        }
4330        return null;
4331    }
4332
4333    @Override
4334    public String[] getSystemSharedLibraryNames() {
4335        synchronized (mPackages) {
4336            Set<String> libs = null;
4337            final int libCount = mSharedLibraries.size();
4338            for (int i = 0; i < libCount; i++) {
4339                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4340                if (versionedLib == null) {
4341                    continue;
4342                }
4343                final int versionCount = versionedLib.size();
4344                for (int j = 0; j < versionCount; j++) {
4345                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4346                    if (!libEntry.info.isStatic()) {
4347                        if (libs == null) {
4348                            libs = new ArraySet<>();
4349                        }
4350                        libs.add(libEntry.info.getName());
4351                        break;
4352                    }
4353                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4354                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4355                            UserHandle.getUserId(Binder.getCallingUid()))) {
4356                        if (libs == null) {
4357                            libs = new ArraySet<>();
4358                        }
4359                        libs.add(libEntry.info.getName());
4360                        break;
4361                    }
4362                }
4363            }
4364
4365            if (libs != null) {
4366                String[] libsArray = new String[libs.size()];
4367                libs.toArray(libsArray);
4368                return libsArray;
4369            }
4370
4371            return null;
4372        }
4373    }
4374
4375    @Override
4376    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4377        synchronized (mPackages) {
4378            return mServicesSystemSharedLibraryPackageName;
4379        }
4380    }
4381
4382    @Override
4383    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4384        synchronized (mPackages) {
4385            return mSharedSystemSharedLibraryPackageName;
4386        }
4387    }
4388
4389    private void updateSequenceNumberLP(String packageName, int[] userList) {
4390        for (int i = userList.length - 1; i >= 0; --i) {
4391            final int userId = userList[i];
4392            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4393            if (changedPackages == null) {
4394                changedPackages = new SparseArray<>();
4395                mChangedPackages.put(userId, changedPackages);
4396            }
4397            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4398            if (sequenceNumbers == null) {
4399                sequenceNumbers = new HashMap<>();
4400                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4401            }
4402            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4403            if (sequenceNumber != null) {
4404                changedPackages.remove(sequenceNumber);
4405            }
4406            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4407            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4408        }
4409        mChangedPackagesSequenceNumber++;
4410    }
4411
4412    @Override
4413    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4414        synchronized (mPackages) {
4415            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4416                return null;
4417            }
4418            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4419            if (changedPackages == null) {
4420                return null;
4421            }
4422            final List<String> packageNames =
4423                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4424            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4425                final String packageName = changedPackages.get(i);
4426                if (packageName != null) {
4427                    packageNames.add(packageName);
4428                }
4429            }
4430            return packageNames.isEmpty()
4431                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4432        }
4433    }
4434
4435    @Override
4436    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4437        ArrayList<FeatureInfo> res;
4438        synchronized (mAvailableFeatures) {
4439            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4440            res.addAll(mAvailableFeatures.values());
4441        }
4442        final FeatureInfo fi = new FeatureInfo();
4443        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4444                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4445        res.add(fi);
4446
4447        return new ParceledListSlice<>(res);
4448    }
4449
4450    @Override
4451    public boolean hasSystemFeature(String name, int version) {
4452        synchronized (mAvailableFeatures) {
4453            final FeatureInfo feat = mAvailableFeatures.get(name);
4454            if (feat == null) {
4455                return false;
4456            } else {
4457                return feat.version >= version;
4458            }
4459        }
4460    }
4461
4462    @Override
4463    public int checkPermission(String permName, String pkgName, int userId) {
4464        if (!sUserManager.exists(userId)) {
4465            return PackageManager.PERMISSION_DENIED;
4466        }
4467
4468        synchronized (mPackages) {
4469            final PackageParser.Package p = mPackages.get(pkgName);
4470            if (p != null && p.mExtras != null) {
4471                final PackageSetting ps = (PackageSetting) p.mExtras;
4472                final PermissionsState permissionsState = ps.getPermissionsState();
4473                if (permissionsState.hasPermission(permName, userId)) {
4474                    return PackageManager.PERMISSION_GRANTED;
4475                }
4476                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4477                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4478                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4479                    return PackageManager.PERMISSION_GRANTED;
4480                }
4481            }
4482        }
4483
4484        return PackageManager.PERMISSION_DENIED;
4485    }
4486
4487    @Override
4488    public int checkUidPermission(String permName, int uid) {
4489        final int userId = UserHandle.getUserId(uid);
4490
4491        if (!sUserManager.exists(userId)) {
4492            return PackageManager.PERMISSION_DENIED;
4493        }
4494
4495        synchronized (mPackages) {
4496            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4497            if (obj != null) {
4498                final SettingBase ps = (SettingBase) obj;
4499                final PermissionsState permissionsState = ps.getPermissionsState();
4500                if (permissionsState.hasPermission(permName, userId)) {
4501                    return PackageManager.PERMISSION_GRANTED;
4502                }
4503                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4504                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4505                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4506                    return PackageManager.PERMISSION_GRANTED;
4507                }
4508            } else {
4509                ArraySet<String> perms = mSystemPermissions.get(uid);
4510                if (perms != null) {
4511                    if (perms.contains(permName)) {
4512                        return PackageManager.PERMISSION_GRANTED;
4513                    }
4514                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4515                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4516                        return PackageManager.PERMISSION_GRANTED;
4517                    }
4518                }
4519            }
4520        }
4521
4522        return PackageManager.PERMISSION_DENIED;
4523    }
4524
4525    @Override
4526    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4527        if (UserHandle.getCallingUserId() != userId) {
4528            mContext.enforceCallingPermission(
4529                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4530                    "isPermissionRevokedByPolicy for user " + userId);
4531        }
4532
4533        if (checkPermission(permission, packageName, userId)
4534                == PackageManager.PERMISSION_GRANTED) {
4535            return false;
4536        }
4537
4538        final long identity = Binder.clearCallingIdentity();
4539        try {
4540            final int flags = getPermissionFlags(permission, packageName, userId);
4541            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4542        } finally {
4543            Binder.restoreCallingIdentity(identity);
4544        }
4545    }
4546
4547    @Override
4548    public String getPermissionControllerPackageName() {
4549        synchronized (mPackages) {
4550            return mRequiredInstallerPackage;
4551        }
4552    }
4553
4554    /**
4555     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4556     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4557     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4558     * @param message the message to log on security exception
4559     */
4560    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4561            boolean checkShell, String message) {
4562        if (userId < 0) {
4563            throw new IllegalArgumentException("Invalid userId " + userId);
4564        }
4565        if (checkShell) {
4566            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4567        }
4568        if (userId == UserHandle.getUserId(callingUid)) return;
4569        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4570            if (requireFullPermission) {
4571                mContext.enforceCallingOrSelfPermission(
4572                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4573            } else {
4574                try {
4575                    mContext.enforceCallingOrSelfPermission(
4576                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4577                } catch (SecurityException se) {
4578                    mContext.enforceCallingOrSelfPermission(
4579                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4580                }
4581            }
4582        }
4583    }
4584
4585    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4586        if (callingUid == Process.SHELL_UID) {
4587            if (userHandle >= 0
4588                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4589                throw new SecurityException("Shell does not have permission to access user "
4590                        + userHandle);
4591            } else if (userHandle < 0) {
4592                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4593                        + Debug.getCallers(3));
4594            }
4595        }
4596    }
4597
4598    private BasePermission findPermissionTreeLP(String permName) {
4599        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4600            if (permName.startsWith(bp.name) &&
4601                    permName.length() > bp.name.length() &&
4602                    permName.charAt(bp.name.length()) == '.') {
4603                return bp;
4604            }
4605        }
4606        return null;
4607    }
4608
4609    private BasePermission checkPermissionTreeLP(String permName) {
4610        if (permName != null) {
4611            BasePermission bp = findPermissionTreeLP(permName);
4612            if (bp != null) {
4613                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4614                    return bp;
4615                }
4616                throw new SecurityException("Calling uid "
4617                        + Binder.getCallingUid()
4618                        + " is not allowed to add to permission tree "
4619                        + bp.name + " owned by uid " + bp.uid);
4620            }
4621        }
4622        throw new SecurityException("No permission tree found for " + permName);
4623    }
4624
4625    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4626        if (s1 == null) {
4627            return s2 == null;
4628        }
4629        if (s2 == null) {
4630            return false;
4631        }
4632        if (s1.getClass() != s2.getClass()) {
4633            return false;
4634        }
4635        return s1.equals(s2);
4636    }
4637
4638    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4639        if (pi1.icon != pi2.icon) return false;
4640        if (pi1.logo != pi2.logo) return false;
4641        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4642        if (!compareStrings(pi1.name, pi2.name)) return false;
4643        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4644        // We'll take care of setting this one.
4645        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4646        // These are not currently stored in settings.
4647        //if (!compareStrings(pi1.group, pi2.group)) return false;
4648        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4649        //if (pi1.labelRes != pi2.labelRes) return false;
4650        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4651        return true;
4652    }
4653
4654    int permissionInfoFootprint(PermissionInfo info) {
4655        int size = info.name.length();
4656        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4657        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4658        return size;
4659    }
4660
4661    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4662        int size = 0;
4663        for (BasePermission perm : mSettings.mPermissions.values()) {
4664            if (perm.uid == tree.uid) {
4665                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4666            }
4667        }
4668        return size;
4669    }
4670
4671    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4672        // We calculate the max size of permissions defined by this uid and throw
4673        // if that plus the size of 'info' would exceed our stated maximum.
4674        if (tree.uid != Process.SYSTEM_UID) {
4675            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4676            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4677                throw new SecurityException("Permission tree size cap exceeded");
4678            }
4679        }
4680    }
4681
4682    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4683        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4684            throw new SecurityException("Label must be specified in permission");
4685        }
4686        BasePermission tree = checkPermissionTreeLP(info.name);
4687        BasePermission bp = mSettings.mPermissions.get(info.name);
4688        boolean added = bp == null;
4689        boolean changed = true;
4690        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4691        if (added) {
4692            enforcePermissionCapLocked(info, tree);
4693            bp = new BasePermission(info.name, tree.sourcePackage,
4694                    BasePermission.TYPE_DYNAMIC);
4695        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4696            throw new SecurityException(
4697                    "Not allowed to modify non-dynamic permission "
4698                    + info.name);
4699        } else {
4700            if (bp.protectionLevel == fixedLevel
4701                    && bp.perm.owner.equals(tree.perm.owner)
4702                    && bp.uid == tree.uid
4703                    && comparePermissionInfos(bp.perm.info, info)) {
4704                changed = false;
4705            }
4706        }
4707        bp.protectionLevel = fixedLevel;
4708        info = new PermissionInfo(info);
4709        info.protectionLevel = fixedLevel;
4710        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4711        bp.perm.info.packageName = tree.perm.info.packageName;
4712        bp.uid = tree.uid;
4713        if (added) {
4714            mSettings.mPermissions.put(info.name, bp);
4715        }
4716        if (changed) {
4717            if (!async) {
4718                mSettings.writeLPr();
4719            } else {
4720                scheduleWriteSettingsLocked();
4721            }
4722        }
4723        return added;
4724    }
4725
4726    @Override
4727    public boolean addPermission(PermissionInfo info) {
4728        synchronized (mPackages) {
4729            return addPermissionLocked(info, false);
4730        }
4731    }
4732
4733    @Override
4734    public boolean addPermissionAsync(PermissionInfo info) {
4735        synchronized (mPackages) {
4736            return addPermissionLocked(info, true);
4737        }
4738    }
4739
4740    @Override
4741    public void removePermission(String name) {
4742        synchronized (mPackages) {
4743            checkPermissionTreeLP(name);
4744            BasePermission bp = mSettings.mPermissions.get(name);
4745            if (bp != null) {
4746                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4747                    throw new SecurityException(
4748                            "Not allowed to modify non-dynamic permission "
4749                            + name);
4750                }
4751                mSettings.mPermissions.remove(name);
4752                mSettings.writeLPr();
4753            }
4754        }
4755    }
4756
4757    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4758            BasePermission bp) {
4759        int index = pkg.requestedPermissions.indexOf(bp.name);
4760        if (index == -1) {
4761            throw new SecurityException("Package " + pkg.packageName
4762                    + " has not requested permission " + bp.name);
4763        }
4764        if (!bp.isRuntime() && !bp.isDevelopment()) {
4765            throw new SecurityException("Permission " + bp.name
4766                    + " is not a changeable permission type");
4767        }
4768    }
4769
4770    @Override
4771    public void grantRuntimePermission(String packageName, String name, final int userId) {
4772        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4773    }
4774
4775    private void grantRuntimePermission(String packageName, String name, final int userId,
4776            boolean overridePolicy) {
4777        if (!sUserManager.exists(userId)) {
4778            Log.e(TAG, "No such user:" + userId);
4779            return;
4780        }
4781
4782        mContext.enforceCallingOrSelfPermission(
4783                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4784                "grantRuntimePermission");
4785
4786        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4787                true /* requireFullPermission */, true /* checkShell */,
4788                "grantRuntimePermission");
4789
4790        final int uid;
4791        final SettingBase sb;
4792
4793        synchronized (mPackages) {
4794            final PackageParser.Package pkg = mPackages.get(packageName);
4795            if (pkg == null) {
4796                throw new IllegalArgumentException("Unknown package: " + packageName);
4797            }
4798
4799            final BasePermission bp = mSettings.mPermissions.get(name);
4800            if (bp == null) {
4801                throw new IllegalArgumentException("Unknown permission: " + name);
4802            }
4803
4804            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4805
4806            // If a permission review is required for legacy apps we represent
4807            // their permissions as always granted runtime ones since we need
4808            // to keep the review required permission flag per user while an
4809            // install permission's state is shared across all users.
4810            if (mPermissionReviewRequired
4811                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4812                    && bp.isRuntime()) {
4813                return;
4814            }
4815
4816            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4817            sb = (SettingBase) pkg.mExtras;
4818            if (sb == null) {
4819                throw new IllegalArgumentException("Unknown package: " + packageName);
4820            }
4821
4822            final PermissionsState permissionsState = sb.getPermissionsState();
4823
4824            final int flags = permissionsState.getPermissionFlags(name, userId);
4825            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4826                throw new SecurityException("Cannot grant system fixed permission "
4827                        + name + " for package " + packageName);
4828            }
4829            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4830                throw new SecurityException("Cannot grant policy fixed permission "
4831                        + name + " for package " + packageName);
4832            }
4833
4834            if (bp.isDevelopment()) {
4835                // Development permissions must be handled specially, since they are not
4836                // normal runtime permissions.  For now they apply to all users.
4837                if (permissionsState.grantInstallPermission(bp) !=
4838                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4839                    scheduleWriteSettingsLocked();
4840                }
4841                return;
4842            }
4843
4844            final PackageSetting ps = mSettings.mPackages.get(packageName);
4845            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4846                throw new SecurityException("Cannot grant non-ephemeral permission"
4847                        + name + " for package " + packageName);
4848            }
4849
4850            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4851                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4852                return;
4853            }
4854
4855            final int result = permissionsState.grantRuntimePermission(bp, userId);
4856            switch (result) {
4857                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4858                    return;
4859                }
4860
4861                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4862                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4863                    mHandler.post(new Runnable() {
4864                        @Override
4865                        public void run() {
4866                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4867                        }
4868                    });
4869                }
4870                break;
4871            }
4872
4873            if (bp.isRuntime()) {
4874                logPermissionGranted(mContext, name, packageName);
4875            }
4876
4877            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4878
4879            // Not critical if that is lost - app has to request again.
4880            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4881        }
4882
4883        // Only need to do this if user is initialized. Otherwise it's a new user
4884        // and there are no processes running as the user yet and there's no need
4885        // to make an expensive call to remount processes for the changed permissions.
4886        if (READ_EXTERNAL_STORAGE.equals(name)
4887                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4888            final long token = Binder.clearCallingIdentity();
4889            try {
4890                if (sUserManager.isInitialized(userId)) {
4891                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4892                            StorageManagerInternal.class);
4893                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4894                }
4895            } finally {
4896                Binder.restoreCallingIdentity(token);
4897            }
4898        }
4899    }
4900
4901    @Override
4902    public void revokeRuntimePermission(String packageName, String name, int userId) {
4903        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4904    }
4905
4906    private void revokeRuntimePermission(String packageName, String name, int userId,
4907            boolean overridePolicy) {
4908        if (!sUserManager.exists(userId)) {
4909            Log.e(TAG, "No such user:" + userId);
4910            return;
4911        }
4912
4913        mContext.enforceCallingOrSelfPermission(
4914                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4915                "revokeRuntimePermission");
4916
4917        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4918                true /* requireFullPermission */, true /* checkShell */,
4919                "revokeRuntimePermission");
4920
4921        final int appId;
4922
4923        synchronized (mPackages) {
4924            final PackageParser.Package pkg = mPackages.get(packageName);
4925            if (pkg == null) {
4926                throw new IllegalArgumentException("Unknown package: " + packageName);
4927            }
4928
4929            final BasePermission bp = mSettings.mPermissions.get(name);
4930            if (bp == null) {
4931                throw new IllegalArgumentException("Unknown permission: " + name);
4932            }
4933
4934            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4935
4936            // If a permission review is required for legacy apps we represent
4937            // their permissions as always granted runtime ones since we need
4938            // to keep the review required permission flag per user while an
4939            // install permission's state is shared across all users.
4940            if (mPermissionReviewRequired
4941                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4942                    && bp.isRuntime()) {
4943                return;
4944            }
4945
4946            SettingBase sb = (SettingBase) pkg.mExtras;
4947            if (sb == null) {
4948                throw new IllegalArgumentException("Unknown package: " + packageName);
4949            }
4950
4951            final PermissionsState permissionsState = sb.getPermissionsState();
4952
4953            final int flags = permissionsState.getPermissionFlags(name, userId);
4954            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4955                throw new SecurityException("Cannot revoke system fixed permission "
4956                        + name + " for package " + packageName);
4957            }
4958            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4959                throw new SecurityException("Cannot revoke policy fixed permission "
4960                        + name + " for package " + packageName);
4961            }
4962
4963            if (bp.isDevelopment()) {
4964                // Development permissions must be handled specially, since they are not
4965                // normal runtime permissions.  For now they apply to all users.
4966                if (permissionsState.revokeInstallPermission(bp) !=
4967                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4968                    scheduleWriteSettingsLocked();
4969                }
4970                return;
4971            }
4972
4973            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4974                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4975                return;
4976            }
4977
4978            if (bp.isRuntime()) {
4979                logPermissionRevoked(mContext, name, packageName);
4980            }
4981
4982            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4983
4984            // Critical, after this call app should never have the permission.
4985            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4986
4987            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4988        }
4989
4990        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4991    }
4992
4993    /**
4994     * Get the first event id for the permission.
4995     *
4996     * <p>There are four events for each permission: <ul>
4997     *     <li>Request permission: first id + 0</li>
4998     *     <li>Grant permission: first id + 1</li>
4999     *     <li>Request for permission denied: first id + 2</li>
5000     *     <li>Revoke permission: first id + 3</li>
5001     * </ul></p>
5002     *
5003     * @param name name of the permission
5004     *
5005     * @return The first event id for the permission
5006     */
5007    private static int getBaseEventId(@NonNull String name) {
5008        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5009
5010        if (eventIdIndex == -1) {
5011            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5012                    || "user".equals(Build.TYPE)) {
5013                Log.i(TAG, "Unknown permission " + name);
5014
5015                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5016            } else {
5017                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5018                //
5019                // Also update
5020                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5021                // - metrics_constants.proto
5022                throw new IllegalStateException("Unknown permission " + name);
5023            }
5024        }
5025
5026        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5027    }
5028
5029    /**
5030     * Log that a permission was revoked.
5031     *
5032     * @param context Context of the caller
5033     * @param name name of the permission
5034     * @param packageName package permission if for
5035     */
5036    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5037            @NonNull String packageName) {
5038        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5039    }
5040
5041    /**
5042     * Log that a permission request was granted.
5043     *
5044     * @param context Context of the caller
5045     * @param name name of the permission
5046     * @param packageName package permission if for
5047     */
5048    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5049            @NonNull String packageName) {
5050        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5051    }
5052
5053    @Override
5054    public void resetRuntimePermissions() {
5055        mContext.enforceCallingOrSelfPermission(
5056                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5057                "revokeRuntimePermission");
5058
5059        int callingUid = Binder.getCallingUid();
5060        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5061            mContext.enforceCallingOrSelfPermission(
5062                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5063                    "resetRuntimePermissions");
5064        }
5065
5066        synchronized (mPackages) {
5067            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5068            for (int userId : UserManagerService.getInstance().getUserIds()) {
5069                final int packageCount = mPackages.size();
5070                for (int i = 0; i < packageCount; i++) {
5071                    PackageParser.Package pkg = mPackages.valueAt(i);
5072                    if (!(pkg.mExtras instanceof PackageSetting)) {
5073                        continue;
5074                    }
5075                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5076                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5077                }
5078            }
5079        }
5080    }
5081
5082    @Override
5083    public int getPermissionFlags(String name, String packageName, int userId) {
5084        if (!sUserManager.exists(userId)) {
5085            return 0;
5086        }
5087
5088        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5089
5090        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5091                true /* requireFullPermission */, false /* checkShell */,
5092                "getPermissionFlags");
5093
5094        synchronized (mPackages) {
5095            final PackageParser.Package pkg = mPackages.get(packageName);
5096            if (pkg == null) {
5097                return 0;
5098            }
5099
5100            final BasePermission bp = mSettings.mPermissions.get(name);
5101            if (bp == null) {
5102                return 0;
5103            }
5104
5105            SettingBase sb = (SettingBase) pkg.mExtras;
5106            if (sb == null) {
5107                return 0;
5108            }
5109
5110            PermissionsState permissionsState = sb.getPermissionsState();
5111            return permissionsState.getPermissionFlags(name, userId);
5112        }
5113    }
5114
5115    @Override
5116    public void updatePermissionFlags(String name, String packageName, int flagMask,
5117            int flagValues, int userId) {
5118        if (!sUserManager.exists(userId)) {
5119            return;
5120        }
5121
5122        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5123
5124        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5125                true /* requireFullPermission */, true /* checkShell */,
5126                "updatePermissionFlags");
5127
5128        // Only the system can change these flags and nothing else.
5129        if (getCallingUid() != Process.SYSTEM_UID) {
5130            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5131            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5132            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5133            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5134            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5135        }
5136
5137        synchronized (mPackages) {
5138            final PackageParser.Package pkg = mPackages.get(packageName);
5139            if (pkg == null) {
5140                throw new IllegalArgumentException("Unknown package: " + packageName);
5141            }
5142
5143            final BasePermission bp = mSettings.mPermissions.get(name);
5144            if (bp == null) {
5145                throw new IllegalArgumentException("Unknown permission: " + name);
5146            }
5147
5148            SettingBase sb = (SettingBase) pkg.mExtras;
5149            if (sb == null) {
5150                throw new IllegalArgumentException("Unknown package: " + packageName);
5151            }
5152
5153            PermissionsState permissionsState = sb.getPermissionsState();
5154
5155            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5156
5157            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5158                // Install and runtime permissions are stored in different places,
5159                // so figure out what permission changed and persist the change.
5160                if (permissionsState.getInstallPermissionState(name) != null) {
5161                    scheduleWriteSettingsLocked();
5162                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5163                        || hadState) {
5164                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5165                }
5166            }
5167        }
5168    }
5169
5170    /**
5171     * Update the permission flags for all packages and runtime permissions of a user in order
5172     * to allow device or profile owner to remove POLICY_FIXED.
5173     */
5174    @Override
5175    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5176        if (!sUserManager.exists(userId)) {
5177            return;
5178        }
5179
5180        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5181
5182        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5183                true /* requireFullPermission */, true /* checkShell */,
5184                "updatePermissionFlagsForAllApps");
5185
5186        // Only the system can change system fixed flags.
5187        if (getCallingUid() != Process.SYSTEM_UID) {
5188            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5189            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5190        }
5191
5192        synchronized (mPackages) {
5193            boolean changed = false;
5194            final int packageCount = mPackages.size();
5195            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5196                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5197                SettingBase sb = (SettingBase) pkg.mExtras;
5198                if (sb == null) {
5199                    continue;
5200                }
5201                PermissionsState permissionsState = sb.getPermissionsState();
5202                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5203                        userId, flagMask, flagValues);
5204            }
5205            if (changed) {
5206                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5207            }
5208        }
5209    }
5210
5211    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5212        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5213                != PackageManager.PERMISSION_GRANTED
5214            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5215                != PackageManager.PERMISSION_GRANTED) {
5216            throw new SecurityException(message + " requires "
5217                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5218                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5219        }
5220    }
5221
5222    @Override
5223    public boolean shouldShowRequestPermissionRationale(String permissionName,
5224            String packageName, int userId) {
5225        if (UserHandle.getCallingUserId() != userId) {
5226            mContext.enforceCallingPermission(
5227                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5228                    "canShowRequestPermissionRationale for user " + userId);
5229        }
5230
5231        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5232        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5233            return false;
5234        }
5235
5236        if (checkPermission(permissionName, packageName, userId)
5237                == PackageManager.PERMISSION_GRANTED) {
5238            return false;
5239        }
5240
5241        final int flags;
5242
5243        final long identity = Binder.clearCallingIdentity();
5244        try {
5245            flags = getPermissionFlags(permissionName,
5246                    packageName, userId);
5247        } finally {
5248            Binder.restoreCallingIdentity(identity);
5249        }
5250
5251        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5252                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5253                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5254
5255        if ((flags & fixedFlags) != 0) {
5256            return false;
5257        }
5258
5259        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5260    }
5261
5262    @Override
5263    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5264        mContext.enforceCallingOrSelfPermission(
5265                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5266                "addOnPermissionsChangeListener");
5267
5268        synchronized (mPackages) {
5269            mOnPermissionChangeListeners.addListenerLocked(listener);
5270        }
5271    }
5272
5273    @Override
5274    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5275        synchronized (mPackages) {
5276            mOnPermissionChangeListeners.removeListenerLocked(listener);
5277        }
5278    }
5279
5280    @Override
5281    public boolean isProtectedBroadcast(String actionName) {
5282        synchronized (mPackages) {
5283            if (mProtectedBroadcasts.contains(actionName)) {
5284                return true;
5285            } else if (actionName != null) {
5286                // TODO: remove these terrible hacks
5287                if (actionName.startsWith("android.net.netmon.lingerExpired")
5288                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5289                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5290                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5291                    return true;
5292                }
5293            }
5294        }
5295        return false;
5296    }
5297
5298    @Override
5299    public int checkSignatures(String pkg1, String pkg2) {
5300        synchronized (mPackages) {
5301            final PackageParser.Package p1 = mPackages.get(pkg1);
5302            final PackageParser.Package p2 = mPackages.get(pkg2);
5303            if (p1 == null || p1.mExtras == null
5304                    || p2 == null || p2.mExtras == null) {
5305                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5306            }
5307            return compareSignatures(p1.mSignatures, p2.mSignatures);
5308        }
5309    }
5310
5311    @Override
5312    public int checkUidSignatures(int uid1, int uid2) {
5313        // Map to base uids.
5314        uid1 = UserHandle.getAppId(uid1);
5315        uid2 = UserHandle.getAppId(uid2);
5316        // reader
5317        synchronized (mPackages) {
5318            Signature[] s1;
5319            Signature[] s2;
5320            Object obj = mSettings.getUserIdLPr(uid1);
5321            if (obj != null) {
5322                if (obj instanceof SharedUserSetting) {
5323                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5324                } else if (obj instanceof PackageSetting) {
5325                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5326                } else {
5327                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5328                }
5329            } else {
5330                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5331            }
5332            obj = mSettings.getUserIdLPr(uid2);
5333            if (obj != null) {
5334                if (obj instanceof SharedUserSetting) {
5335                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5336                } else if (obj instanceof PackageSetting) {
5337                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5338                } else {
5339                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5340                }
5341            } else {
5342                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5343            }
5344            return compareSignatures(s1, s2);
5345        }
5346    }
5347
5348    /**
5349     * This method should typically only be used when granting or revoking
5350     * permissions, since the app may immediately restart after this call.
5351     * <p>
5352     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5353     * guard your work against the app being relaunched.
5354     */
5355    private void killUid(int appId, int userId, String reason) {
5356        final long identity = Binder.clearCallingIdentity();
5357        try {
5358            IActivityManager am = ActivityManager.getService();
5359            if (am != null) {
5360                try {
5361                    am.killUid(appId, userId, reason);
5362                } catch (RemoteException e) {
5363                    /* ignore - same process */
5364                }
5365            }
5366        } finally {
5367            Binder.restoreCallingIdentity(identity);
5368        }
5369    }
5370
5371    /**
5372     * Compares two sets of signatures. Returns:
5373     * <br />
5374     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5375     * <br />
5376     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5377     * <br />
5378     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5379     * <br />
5380     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5381     * <br />
5382     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5383     */
5384    static int compareSignatures(Signature[] s1, Signature[] s2) {
5385        if (s1 == null) {
5386            return s2 == null
5387                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5388                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5389        }
5390
5391        if (s2 == null) {
5392            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5393        }
5394
5395        if (s1.length != s2.length) {
5396            return PackageManager.SIGNATURE_NO_MATCH;
5397        }
5398
5399        // Since both signature sets are of size 1, we can compare without HashSets.
5400        if (s1.length == 1) {
5401            return s1[0].equals(s2[0]) ?
5402                    PackageManager.SIGNATURE_MATCH :
5403                    PackageManager.SIGNATURE_NO_MATCH;
5404        }
5405
5406        ArraySet<Signature> set1 = new ArraySet<Signature>();
5407        for (Signature sig : s1) {
5408            set1.add(sig);
5409        }
5410        ArraySet<Signature> set2 = new ArraySet<Signature>();
5411        for (Signature sig : s2) {
5412            set2.add(sig);
5413        }
5414        // Make sure s2 contains all signatures in s1.
5415        if (set1.equals(set2)) {
5416            return PackageManager.SIGNATURE_MATCH;
5417        }
5418        return PackageManager.SIGNATURE_NO_MATCH;
5419    }
5420
5421    /**
5422     * If the database version for this type of package (internal storage or
5423     * external storage) is less than the version where package signatures
5424     * were updated, return true.
5425     */
5426    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5427        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5428        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5429    }
5430
5431    /**
5432     * Used for backward compatibility to make sure any packages with
5433     * certificate chains get upgraded to the new style. {@code existingSigs}
5434     * will be in the old format (since they were stored on disk from before the
5435     * system upgrade) and {@code scannedSigs} will be in the newer format.
5436     */
5437    private int compareSignaturesCompat(PackageSignatures existingSigs,
5438            PackageParser.Package scannedPkg) {
5439        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5440            return PackageManager.SIGNATURE_NO_MATCH;
5441        }
5442
5443        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5444        for (Signature sig : existingSigs.mSignatures) {
5445            existingSet.add(sig);
5446        }
5447        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5448        for (Signature sig : scannedPkg.mSignatures) {
5449            try {
5450                Signature[] chainSignatures = sig.getChainSignatures();
5451                for (Signature chainSig : chainSignatures) {
5452                    scannedCompatSet.add(chainSig);
5453                }
5454            } catch (CertificateEncodingException e) {
5455                scannedCompatSet.add(sig);
5456            }
5457        }
5458        /*
5459         * Make sure the expanded scanned set contains all signatures in the
5460         * existing one.
5461         */
5462        if (scannedCompatSet.equals(existingSet)) {
5463            // Migrate the old signatures to the new scheme.
5464            existingSigs.assignSignatures(scannedPkg.mSignatures);
5465            // The new KeySets will be re-added later in the scanning process.
5466            synchronized (mPackages) {
5467                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5468            }
5469            return PackageManager.SIGNATURE_MATCH;
5470        }
5471        return PackageManager.SIGNATURE_NO_MATCH;
5472    }
5473
5474    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5475        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5476        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5477    }
5478
5479    private int compareSignaturesRecover(PackageSignatures existingSigs,
5480            PackageParser.Package scannedPkg) {
5481        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5482            return PackageManager.SIGNATURE_NO_MATCH;
5483        }
5484
5485        String msg = null;
5486        try {
5487            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5488                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5489                        + scannedPkg.packageName);
5490                return PackageManager.SIGNATURE_MATCH;
5491            }
5492        } catch (CertificateException e) {
5493            msg = e.getMessage();
5494        }
5495
5496        logCriticalInfo(Log.INFO,
5497                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5498        return PackageManager.SIGNATURE_NO_MATCH;
5499    }
5500
5501    @Override
5502    public List<String> getAllPackages() {
5503        synchronized (mPackages) {
5504            return new ArrayList<String>(mPackages.keySet());
5505        }
5506    }
5507
5508    @Override
5509    public String[] getPackagesForUid(int uid) {
5510        final int userId = UserHandle.getUserId(uid);
5511        uid = UserHandle.getAppId(uid);
5512        // reader
5513        synchronized (mPackages) {
5514            Object obj = mSettings.getUserIdLPr(uid);
5515            if (obj instanceof SharedUserSetting) {
5516                final SharedUserSetting sus = (SharedUserSetting) obj;
5517                final int N = sus.packages.size();
5518                String[] res = new String[N];
5519                final Iterator<PackageSetting> it = sus.packages.iterator();
5520                int i = 0;
5521                while (it.hasNext()) {
5522                    PackageSetting ps = it.next();
5523                    if (ps.getInstalled(userId)) {
5524                        res[i++] = ps.name;
5525                    } else {
5526                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5527                    }
5528                }
5529                return res;
5530            } else if (obj instanceof PackageSetting) {
5531                final PackageSetting ps = (PackageSetting) obj;
5532                if (ps.getInstalled(userId)) {
5533                    return new String[]{ps.name};
5534                }
5535            }
5536        }
5537        return null;
5538    }
5539
5540    @Override
5541    public String getNameForUid(int uid) {
5542        // reader
5543        synchronized (mPackages) {
5544            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5545            if (obj instanceof SharedUserSetting) {
5546                final SharedUserSetting sus = (SharedUserSetting) obj;
5547                return sus.name + ":" + sus.userId;
5548            } else if (obj instanceof PackageSetting) {
5549                final PackageSetting ps = (PackageSetting) obj;
5550                return ps.name;
5551            }
5552        }
5553        return null;
5554    }
5555
5556    @Override
5557    public int getUidForSharedUser(String sharedUserName) {
5558        if(sharedUserName == null) {
5559            return -1;
5560        }
5561        // reader
5562        synchronized (mPackages) {
5563            SharedUserSetting suid;
5564            try {
5565                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5566                if (suid != null) {
5567                    return suid.userId;
5568                }
5569            } catch (PackageManagerException ignore) {
5570                // can't happen, but, still need to catch it
5571            }
5572            return -1;
5573        }
5574    }
5575
5576    @Override
5577    public int getFlagsForUid(int uid) {
5578        synchronized (mPackages) {
5579            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5580            if (obj instanceof SharedUserSetting) {
5581                final SharedUserSetting sus = (SharedUserSetting) obj;
5582                return sus.pkgFlags;
5583            } else if (obj instanceof PackageSetting) {
5584                final PackageSetting ps = (PackageSetting) obj;
5585                return ps.pkgFlags;
5586            }
5587        }
5588        return 0;
5589    }
5590
5591    @Override
5592    public int getPrivateFlagsForUid(int uid) {
5593        synchronized (mPackages) {
5594            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5595            if (obj instanceof SharedUserSetting) {
5596                final SharedUserSetting sus = (SharedUserSetting) obj;
5597                return sus.pkgPrivateFlags;
5598            } else if (obj instanceof PackageSetting) {
5599                final PackageSetting ps = (PackageSetting) obj;
5600                return ps.pkgPrivateFlags;
5601            }
5602        }
5603        return 0;
5604    }
5605
5606    @Override
5607    public boolean isUidPrivileged(int uid) {
5608        uid = UserHandle.getAppId(uid);
5609        // reader
5610        synchronized (mPackages) {
5611            Object obj = mSettings.getUserIdLPr(uid);
5612            if (obj instanceof SharedUserSetting) {
5613                final SharedUserSetting sus = (SharedUserSetting) obj;
5614                final Iterator<PackageSetting> it = sus.packages.iterator();
5615                while (it.hasNext()) {
5616                    if (it.next().isPrivileged()) {
5617                        return true;
5618                    }
5619                }
5620            } else if (obj instanceof PackageSetting) {
5621                final PackageSetting ps = (PackageSetting) obj;
5622                return ps.isPrivileged();
5623            }
5624        }
5625        return false;
5626    }
5627
5628    @Override
5629    public String[] getAppOpPermissionPackages(String permissionName) {
5630        synchronized (mPackages) {
5631            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5632            if (pkgs == null) {
5633                return null;
5634            }
5635            return pkgs.toArray(new String[pkgs.size()]);
5636        }
5637    }
5638
5639    @Override
5640    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5641            int flags, int userId) {
5642        return resolveIntentInternal(
5643                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
5644    }
5645
5646    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5647            int flags, int userId, boolean includeInstantApps) {
5648        try {
5649            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5650
5651            if (!sUserManager.exists(userId)) return null;
5652            final int callingUid = Binder.getCallingUid();
5653            flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
5654            enforceCrossUserPermission(callingUid, userId,
5655                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5656
5657            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5658            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5659                    flags, userId, includeInstantApps);
5660            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5661
5662            final ResolveInfo bestChoice =
5663                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5664            return bestChoice;
5665        } finally {
5666            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5667        }
5668    }
5669
5670    @Override
5671    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5672        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5673            throw new SecurityException(
5674                    "findPersistentPreferredActivity can only be run by the system");
5675        }
5676        if (!sUserManager.exists(userId)) {
5677            return null;
5678        }
5679        final int callingUid = Binder.getCallingUid();
5680        intent = updateIntentForResolve(intent);
5681        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5682        final int flags = updateFlagsForResolve(
5683                0, userId, intent, callingUid, false /*includeInstantApps*/);
5684        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5685                userId);
5686        synchronized (mPackages) {
5687            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5688                    userId);
5689        }
5690    }
5691
5692    @Override
5693    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5694            IntentFilter filter, int match, ComponentName activity) {
5695        final int userId = UserHandle.getCallingUserId();
5696        if (DEBUG_PREFERRED) {
5697            Log.v(TAG, "setLastChosenActivity intent=" + intent
5698                + " resolvedType=" + resolvedType
5699                + " flags=" + flags
5700                + " filter=" + filter
5701                + " match=" + match
5702                + " activity=" + activity);
5703            filter.dump(new PrintStreamPrinter(System.out), "    ");
5704        }
5705        intent.setComponent(null);
5706        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5707                userId);
5708        // Find any earlier preferred or last chosen entries and nuke them
5709        findPreferredActivity(intent, resolvedType,
5710                flags, query, 0, false, true, false, userId);
5711        // Add the new activity as the last chosen for this filter
5712        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5713                "Setting last chosen");
5714    }
5715
5716    @Override
5717    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5718        final int userId = UserHandle.getCallingUserId();
5719        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5720        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5721                userId);
5722        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5723                false, false, false, userId);
5724    }
5725
5726    /**
5727     * Returns whether or not instant apps have been disabled remotely.
5728     */
5729    private boolean isEphemeralDisabled() {
5730        return mEphemeralAppsDisabled;
5731    }
5732
5733    private boolean isEphemeralAllowed(
5734            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5735            boolean skipPackageCheck) {
5736        final int callingUser = UserHandle.getCallingUserId();
5737        if (mInstantAppResolverConnection == null) {
5738            return false;
5739        }
5740        if (mInstantAppInstallerActivity == null) {
5741            return false;
5742        }
5743        if (intent.getComponent() != null) {
5744            return false;
5745        }
5746        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5747            return false;
5748        }
5749        if (!skipPackageCheck && intent.getPackage() != null) {
5750            return false;
5751        }
5752        final boolean isWebUri = hasWebURI(intent);
5753        if (!isWebUri || intent.getData().getHost() == null) {
5754            return false;
5755        }
5756        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5757        // Or if there's already an ephemeral app installed that handles the action
5758        synchronized (mPackages) {
5759            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5760            for (int n = 0; n < count; n++) {
5761                final ResolveInfo info = resolvedActivities.get(n);
5762                final String packageName = info.activityInfo.packageName;
5763                final PackageSetting ps = mSettings.mPackages.get(packageName);
5764                if (ps != null) {
5765                    // only check domain verification status if the app is not a browser
5766                    if (!info.handleAllWebDataURI) {
5767                        // Try to get the status from User settings first
5768                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5769                        final int status = (int) (packedStatus >> 32);
5770                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5771                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5772                            if (DEBUG_EPHEMERAL) {
5773                                Slog.v(TAG, "DENY instant app;"
5774                                    + " pkg: " + packageName + ", status: " + status);
5775                            }
5776                            return false;
5777                        }
5778                    }
5779                    if (ps.getInstantApp(userId)) {
5780                        if (DEBUG_EPHEMERAL) {
5781                            Slog.v(TAG, "DENY instant app installed;"
5782                                    + " pkg: " + packageName);
5783                        }
5784                        return false;
5785                    }
5786                }
5787            }
5788        }
5789        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5790        return true;
5791    }
5792
5793    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5794            Intent origIntent, String resolvedType, String callingPackage,
5795            int userId) {
5796        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5797                new InstantAppRequest(responseObj, origIntent, resolvedType,
5798                        callingPackage, userId));
5799        mHandler.sendMessage(msg);
5800    }
5801
5802    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5803            int flags, List<ResolveInfo> query, int userId) {
5804        if (query != null) {
5805            final int N = query.size();
5806            if (N == 1) {
5807                return query.get(0);
5808            } else if (N > 1) {
5809                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5810                // If there is more than one activity with the same priority,
5811                // then let the user decide between them.
5812                ResolveInfo r0 = query.get(0);
5813                ResolveInfo r1 = query.get(1);
5814                if (DEBUG_INTENT_MATCHING || debug) {
5815                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5816                            + r1.activityInfo.name + "=" + r1.priority);
5817                }
5818                // If the first activity has a higher priority, or a different
5819                // default, then it is always desirable to pick it.
5820                if (r0.priority != r1.priority
5821                        || r0.preferredOrder != r1.preferredOrder
5822                        || r0.isDefault != r1.isDefault) {
5823                    return query.get(0);
5824                }
5825                // If we have saved a preference for a preferred activity for
5826                // this Intent, use that.
5827                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5828                        flags, query, r0.priority, true, false, debug, userId);
5829                if (ri != null) {
5830                    return ri;
5831                }
5832                // If we have an ephemeral app, use it
5833                for (int i = 0; i < N; i++) {
5834                    ri = query.get(i);
5835                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5836                        return ri;
5837                    }
5838                }
5839                ri = new ResolveInfo(mResolveInfo);
5840                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5841                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5842                // If all of the options come from the same package, show the application's
5843                // label and icon instead of the generic resolver's.
5844                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5845                // and then throw away the ResolveInfo itself, meaning that the caller loses
5846                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5847                // a fallback for this case; we only set the target package's resources on
5848                // the ResolveInfo, not the ActivityInfo.
5849                final String intentPackage = intent.getPackage();
5850                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5851                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5852                    ri.resolvePackageName = intentPackage;
5853                    if (userNeedsBadging(userId)) {
5854                        ri.noResourceId = true;
5855                    } else {
5856                        ri.icon = appi.icon;
5857                    }
5858                    ri.iconResourceId = appi.icon;
5859                    ri.labelRes = appi.labelRes;
5860                }
5861                ri.activityInfo.applicationInfo = new ApplicationInfo(
5862                        ri.activityInfo.applicationInfo);
5863                if (userId != 0) {
5864                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5865                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5866                }
5867                // Make sure that the resolver is displayable in car mode
5868                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5869                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5870                return ri;
5871            }
5872        }
5873        return null;
5874    }
5875
5876    /**
5877     * Return true if the given list is not empty and all of its contents have
5878     * an activityInfo with the given package name.
5879     */
5880    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5881        if (ArrayUtils.isEmpty(list)) {
5882            return false;
5883        }
5884        for (int i = 0, N = list.size(); i < N; i++) {
5885            final ResolveInfo ri = list.get(i);
5886            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5887            if (ai == null || !packageName.equals(ai.packageName)) {
5888                return false;
5889            }
5890        }
5891        return true;
5892    }
5893
5894    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5895            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5896        final int N = query.size();
5897        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5898                .get(userId);
5899        // Get the list of persistent preferred activities that handle the intent
5900        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5901        List<PersistentPreferredActivity> pprefs = ppir != null
5902                ? ppir.queryIntent(intent, resolvedType,
5903                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5904                        userId)
5905                : null;
5906        if (pprefs != null && pprefs.size() > 0) {
5907            final int M = pprefs.size();
5908            for (int i=0; i<M; i++) {
5909                final PersistentPreferredActivity ppa = pprefs.get(i);
5910                if (DEBUG_PREFERRED || debug) {
5911                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5912                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5913                            + "\n  component=" + ppa.mComponent);
5914                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5915                }
5916                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5917                        flags | MATCH_DISABLED_COMPONENTS, userId);
5918                if (DEBUG_PREFERRED || debug) {
5919                    Slog.v(TAG, "Found persistent preferred activity:");
5920                    if (ai != null) {
5921                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5922                    } else {
5923                        Slog.v(TAG, "  null");
5924                    }
5925                }
5926                if (ai == null) {
5927                    // This previously registered persistent preferred activity
5928                    // component is no longer known. Ignore it and do NOT remove it.
5929                    continue;
5930                }
5931                for (int j=0; j<N; j++) {
5932                    final ResolveInfo ri = query.get(j);
5933                    if (!ri.activityInfo.applicationInfo.packageName
5934                            .equals(ai.applicationInfo.packageName)) {
5935                        continue;
5936                    }
5937                    if (!ri.activityInfo.name.equals(ai.name)) {
5938                        continue;
5939                    }
5940                    //  Found a persistent preference that can handle the intent.
5941                    if (DEBUG_PREFERRED || debug) {
5942                        Slog.v(TAG, "Returning persistent preferred activity: " +
5943                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5944                    }
5945                    return ri;
5946                }
5947            }
5948        }
5949        return null;
5950    }
5951
5952    // TODO: handle preferred activities missing while user has amnesia
5953    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5954            List<ResolveInfo> query, int priority, boolean always,
5955            boolean removeMatches, boolean debug, int userId) {
5956        if (!sUserManager.exists(userId)) return null;
5957        final int callingUid = Binder.getCallingUid();
5958        flags = updateFlagsForResolve(
5959                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5960        intent = updateIntentForResolve(intent);
5961        // writer
5962        synchronized (mPackages) {
5963            // Try to find a matching persistent preferred activity.
5964            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5965                    debug, userId);
5966
5967            // If a persistent preferred activity matched, use it.
5968            if (pri != null) {
5969                return pri;
5970            }
5971
5972            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5973            // Get the list of preferred activities that handle the intent
5974            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5975            List<PreferredActivity> prefs = pir != null
5976                    ? pir.queryIntent(intent, resolvedType,
5977                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5978                            userId)
5979                    : null;
5980            if (prefs != null && prefs.size() > 0) {
5981                boolean changed = false;
5982                try {
5983                    // First figure out how good the original match set is.
5984                    // We will only allow preferred activities that came
5985                    // from the same match quality.
5986                    int match = 0;
5987
5988                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5989
5990                    final int N = query.size();
5991                    for (int j=0; j<N; j++) {
5992                        final ResolveInfo ri = query.get(j);
5993                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5994                                + ": 0x" + Integer.toHexString(match));
5995                        if (ri.match > match) {
5996                            match = ri.match;
5997                        }
5998                    }
5999
6000                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6001                            + Integer.toHexString(match));
6002
6003                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6004                    final int M = prefs.size();
6005                    for (int i=0; i<M; i++) {
6006                        final PreferredActivity pa = prefs.get(i);
6007                        if (DEBUG_PREFERRED || debug) {
6008                            Slog.v(TAG, "Checking PreferredActivity ds="
6009                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6010                                    + "\n  component=" + pa.mPref.mComponent);
6011                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6012                        }
6013                        if (pa.mPref.mMatch != match) {
6014                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6015                                    + Integer.toHexString(pa.mPref.mMatch));
6016                            continue;
6017                        }
6018                        // If it's not an "always" type preferred activity and that's what we're
6019                        // looking for, skip it.
6020                        if (always && !pa.mPref.mAlways) {
6021                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6022                            continue;
6023                        }
6024                        final ActivityInfo ai = getActivityInfo(
6025                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6026                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6027                                userId);
6028                        if (DEBUG_PREFERRED || debug) {
6029                            Slog.v(TAG, "Found preferred activity:");
6030                            if (ai != null) {
6031                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6032                            } else {
6033                                Slog.v(TAG, "  null");
6034                            }
6035                        }
6036                        if (ai == null) {
6037                            // This previously registered preferred activity
6038                            // component is no longer known.  Most likely an update
6039                            // to the app was installed and in the new version this
6040                            // component no longer exists.  Clean it up by removing
6041                            // it from the preferred activities list, and skip it.
6042                            Slog.w(TAG, "Removing dangling preferred activity: "
6043                                    + pa.mPref.mComponent);
6044                            pir.removeFilter(pa);
6045                            changed = true;
6046                            continue;
6047                        }
6048                        for (int j=0; j<N; j++) {
6049                            final ResolveInfo ri = query.get(j);
6050                            if (!ri.activityInfo.applicationInfo.packageName
6051                                    .equals(ai.applicationInfo.packageName)) {
6052                                continue;
6053                            }
6054                            if (!ri.activityInfo.name.equals(ai.name)) {
6055                                continue;
6056                            }
6057
6058                            if (removeMatches) {
6059                                pir.removeFilter(pa);
6060                                changed = true;
6061                                if (DEBUG_PREFERRED) {
6062                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6063                                }
6064                                break;
6065                            }
6066
6067                            // Okay we found a previously set preferred or last chosen app.
6068                            // If the result set is different from when this
6069                            // was created, we need to clear it and re-ask the
6070                            // user their preference, if we're looking for an "always" type entry.
6071                            if (always && !pa.mPref.sameSet(query)) {
6072                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6073                                        + intent + " type " + resolvedType);
6074                                if (DEBUG_PREFERRED) {
6075                                    Slog.v(TAG, "Removing preferred activity since set changed "
6076                                            + pa.mPref.mComponent);
6077                                }
6078                                pir.removeFilter(pa);
6079                                // Re-add the filter as a "last chosen" entry (!always)
6080                                PreferredActivity lastChosen = new PreferredActivity(
6081                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6082                                pir.addFilter(lastChosen);
6083                                changed = true;
6084                                return null;
6085                            }
6086
6087                            // Yay! Either the set matched or we're looking for the last chosen
6088                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6089                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6090                            return ri;
6091                        }
6092                    }
6093                } finally {
6094                    if (changed) {
6095                        if (DEBUG_PREFERRED) {
6096                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6097                        }
6098                        scheduleWritePackageRestrictionsLocked(userId);
6099                    }
6100                }
6101            }
6102        }
6103        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6104        return null;
6105    }
6106
6107    /*
6108     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6109     */
6110    @Override
6111    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6112            int targetUserId) {
6113        mContext.enforceCallingOrSelfPermission(
6114                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6115        List<CrossProfileIntentFilter> matches =
6116                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6117        if (matches != null) {
6118            int size = matches.size();
6119            for (int i = 0; i < size; i++) {
6120                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6121            }
6122        }
6123        if (hasWebURI(intent)) {
6124            // cross-profile app linking works only towards the parent.
6125            final int callingUid = Binder.getCallingUid();
6126            final UserInfo parent = getProfileParent(sourceUserId);
6127            synchronized(mPackages) {
6128                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6129                        false /*includeInstantApps*/);
6130                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6131                        intent, resolvedType, flags, sourceUserId, parent.id);
6132                return xpDomainInfo != null;
6133            }
6134        }
6135        return false;
6136    }
6137
6138    private UserInfo getProfileParent(int userId) {
6139        final long identity = Binder.clearCallingIdentity();
6140        try {
6141            return sUserManager.getProfileParent(userId);
6142        } finally {
6143            Binder.restoreCallingIdentity(identity);
6144        }
6145    }
6146
6147    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6148            String resolvedType, int userId) {
6149        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6150        if (resolver != null) {
6151            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6152        }
6153        return null;
6154    }
6155
6156    @Override
6157    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6158            String resolvedType, int flags, int userId) {
6159        try {
6160            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6161
6162            return new ParceledListSlice<>(
6163                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6164        } finally {
6165            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6166        }
6167    }
6168
6169    /**
6170     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6171     * instant, returns {@code null}.
6172     */
6173    private String getInstantAppPackageName(int callingUid) {
6174        // If the caller is an isolated app use the owner's uid for the lookup.
6175        if (Process.isIsolated(callingUid)) {
6176            callingUid = mIsolatedOwners.get(callingUid);
6177        }
6178        final int appId = UserHandle.getAppId(callingUid);
6179        synchronized (mPackages) {
6180            final Object obj = mSettings.getUserIdLPr(appId);
6181            if (obj instanceof PackageSetting) {
6182                final PackageSetting ps = (PackageSetting) obj;
6183                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6184                return isInstantApp ? ps.pkg.packageName : null;
6185            }
6186        }
6187        return null;
6188    }
6189
6190    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6191            String resolvedType, int flags, int userId) {
6192        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6193    }
6194
6195    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6196            String resolvedType, int flags, int userId, boolean includeInstantApps) {
6197        if (!sUserManager.exists(userId)) return Collections.emptyList();
6198        final int callingUid = Binder.getCallingUid();
6199        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6200        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
6201        enforceCrossUserPermission(callingUid, userId,
6202                false /* requireFullPermission */, false /* checkShell */,
6203                "query intent activities");
6204        ComponentName comp = intent.getComponent();
6205        if (comp == null) {
6206            if (intent.getSelector() != null) {
6207                intent = intent.getSelector();
6208                comp = intent.getComponent();
6209            }
6210        }
6211
6212        if (comp != null) {
6213            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6214            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6215            if (ai != null) {
6216                // When specifying an explicit component, we prevent the activity from being
6217                // used when either 1) the calling package is normal and the activity is within
6218                // an ephemeral application or 2) the calling package is ephemeral and the
6219                // activity is not visible to ephemeral applications.
6220                final boolean matchInstantApp =
6221                        (flags & PackageManager.MATCH_INSTANT) != 0;
6222                final boolean matchVisibleToInstantAppOnly =
6223                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6224                final boolean isCallerInstantApp =
6225                        instantAppPkgName != null;
6226                final boolean isTargetSameInstantApp =
6227                        comp.getPackageName().equals(instantAppPkgName);
6228                final boolean isTargetInstantApp =
6229                        (ai.applicationInfo.privateFlags
6230                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6231                final boolean isTargetHiddenFromInstantApp =
6232                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6233                final boolean blockResolution =
6234                        !isTargetSameInstantApp
6235                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6236                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6237                                        && isTargetHiddenFromInstantApp));
6238                if (!blockResolution) {
6239                    final ResolveInfo ri = new ResolveInfo();
6240                    ri.activityInfo = ai;
6241                    list.add(ri);
6242                }
6243            }
6244            return applyPostResolutionFilter(list, instantAppPkgName);
6245        }
6246
6247        // reader
6248        boolean sortResult = false;
6249        boolean addEphemeral = false;
6250        List<ResolveInfo> result;
6251        final String pkgName = intent.getPackage();
6252        final boolean ephemeralDisabled = isEphemeralDisabled();
6253        synchronized (mPackages) {
6254            if (pkgName == null) {
6255                List<CrossProfileIntentFilter> matchingFilters =
6256                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6257                // Check for results that need to skip the current profile.
6258                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6259                        resolvedType, flags, userId);
6260                if (xpResolveInfo != null) {
6261                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6262                    xpResult.add(xpResolveInfo);
6263                    return applyPostResolutionFilter(
6264                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6265                }
6266
6267                // Check for results in the current profile.
6268                result = filterIfNotSystemUser(mActivities.queryIntent(
6269                        intent, resolvedType, flags, userId), userId);
6270                addEphemeral = !ephemeralDisabled
6271                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6272                // Check for cross profile results.
6273                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6274                xpResolveInfo = queryCrossProfileIntents(
6275                        matchingFilters, intent, resolvedType, flags, userId,
6276                        hasNonNegativePriorityResult);
6277                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6278                    boolean isVisibleToUser = filterIfNotSystemUser(
6279                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6280                    if (isVisibleToUser) {
6281                        result.add(xpResolveInfo);
6282                        sortResult = true;
6283                    }
6284                }
6285                if (hasWebURI(intent)) {
6286                    CrossProfileDomainInfo xpDomainInfo = null;
6287                    final UserInfo parent = getProfileParent(userId);
6288                    if (parent != null) {
6289                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6290                                flags, userId, parent.id);
6291                    }
6292                    if (xpDomainInfo != null) {
6293                        if (xpResolveInfo != null) {
6294                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6295                            // in the result.
6296                            result.remove(xpResolveInfo);
6297                        }
6298                        if (result.size() == 0 && !addEphemeral) {
6299                            // No result in current profile, but found candidate in parent user.
6300                            // And we are not going to add emphemeral app, so we can return the
6301                            // result straight away.
6302                            result.add(xpDomainInfo.resolveInfo);
6303                            return applyPostResolutionFilter(result, instantAppPkgName);
6304                        }
6305                    } else if (result.size() <= 1 && !addEphemeral) {
6306                        // No result in parent user and <= 1 result in current profile, and we
6307                        // are not going to add emphemeral app, so we can return the result without
6308                        // further processing.
6309                        return applyPostResolutionFilter(result, instantAppPkgName);
6310                    }
6311                    // We have more than one candidate (combining results from current and parent
6312                    // profile), so we need filtering and sorting.
6313                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6314                            intent, flags, result, xpDomainInfo, userId);
6315                    sortResult = true;
6316                }
6317            } else {
6318                final PackageParser.Package pkg = mPackages.get(pkgName);
6319                if (pkg != null) {
6320                    return applyPostResolutionFilter(filterIfNotSystemUser(
6321                            mActivities.queryIntentForPackage(
6322                                    intent, resolvedType, flags, pkg.activities, userId),
6323                            userId), instantAppPkgName);
6324                } else {
6325                    // the caller wants to resolve for a particular package; however, there
6326                    // were no installed results, so, try to find an ephemeral result
6327                    addEphemeral = !ephemeralDisabled
6328                            && isEphemeralAllowed(
6329                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6330                    result = new ArrayList<ResolveInfo>();
6331                }
6332            }
6333        }
6334        if (addEphemeral) {
6335            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6336            final InstantAppRequest requestObject = new InstantAppRequest(
6337                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6338                    null /*callingPackage*/, userId);
6339            final AuxiliaryResolveInfo auxiliaryResponse =
6340                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6341                            mContext, mInstantAppResolverConnection, requestObject);
6342            if (auxiliaryResponse != null) {
6343                if (DEBUG_EPHEMERAL) {
6344                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6345                }
6346                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6347                final PackageSetting ps =
6348                        mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6349                if (ps != null) {
6350                    ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6351                            mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6352                    ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6353                    ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6354                    // make sure this resolver is the default
6355                    ephemeralInstaller.isDefault = true;
6356                    ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6357                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6358                    // add a non-generic filter
6359                    ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6360                    ephemeralInstaller.filter.addDataPath(
6361                            intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6362                    ephemeralInstaller.instantAppAvailable = true;
6363                    result.add(ephemeralInstaller);
6364                }
6365            }
6366            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6367        }
6368        if (sortResult) {
6369            Collections.sort(result, mResolvePrioritySorter);
6370        }
6371        return applyPostResolutionFilter(result, instantAppPkgName);
6372    }
6373
6374    private static class CrossProfileDomainInfo {
6375        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6376        ResolveInfo resolveInfo;
6377        /* Best domain verification status of the activities found in the other profile */
6378        int bestDomainVerificationStatus;
6379    }
6380
6381    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6382            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6383        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6384                sourceUserId)) {
6385            return null;
6386        }
6387        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6388                resolvedType, flags, parentUserId);
6389
6390        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6391            return null;
6392        }
6393        CrossProfileDomainInfo result = null;
6394        int size = resultTargetUser.size();
6395        for (int i = 0; i < size; i++) {
6396            ResolveInfo riTargetUser = resultTargetUser.get(i);
6397            // Intent filter verification is only for filters that specify a host. So don't return
6398            // those that handle all web uris.
6399            if (riTargetUser.handleAllWebDataURI) {
6400                continue;
6401            }
6402            String packageName = riTargetUser.activityInfo.packageName;
6403            PackageSetting ps = mSettings.mPackages.get(packageName);
6404            if (ps == null) {
6405                continue;
6406            }
6407            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6408            int status = (int)(verificationState >> 32);
6409            if (result == null) {
6410                result = new CrossProfileDomainInfo();
6411                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6412                        sourceUserId, parentUserId);
6413                result.bestDomainVerificationStatus = status;
6414            } else {
6415                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6416                        result.bestDomainVerificationStatus);
6417            }
6418        }
6419        // Don't consider matches with status NEVER across profiles.
6420        if (result != null && result.bestDomainVerificationStatus
6421                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6422            return null;
6423        }
6424        return result;
6425    }
6426
6427    /**
6428     * Verification statuses are ordered from the worse to the best, except for
6429     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6430     */
6431    private int bestDomainVerificationStatus(int status1, int status2) {
6432        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6433            return status2;
6434        }
6435        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6436            return status1;
6437        }
6438        return (int) MathUtils.max(status1, status2);
6439    }
6440
6441    private boolean isUserEnabled(int userId) {
6442        long callingId = Binder.clearCallingIdentity();
6443        try {
6444            UserInfo userInfo = sUserManager.getUserInfo(userId);
6445            return userInfo != null && userInfo.isEnabled();
6446        } finally {
6447            Binder.restoreCallingIdentity(callingId);
6448        }
6449    }
6450
6451    /**
6452     * Filter out activities with systemUserOnly flag set, when current user is not System.
6453     *
6454     * @return filtered list
6455     */
6456    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6457        if (userId == UserHandle.USER_SYSTEM) {
6458            return resolveInfos;
6459        }
6460        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6461            ResolveInfo info = resolveInfos.get(i);
6462            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6463                resolveInfos.remove(i);
6464            }
6465        }
6466        return resolveInfos;
6467    }
6468
6469    /**
6470     * Filters out ephemeral activities.
6471     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6472     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6473     *
6474     * @param resolveInfos The pre-filtered list of resolved activities
6475     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6476     *          is performed.
6477     * @return A filtered list of resolved activities.
6478     */
6479    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6480            String ephemeralPkgName) {
6481        // TODO: When adding on-demand split support for non-instant apps, remove this check
6482        // and always apply post filtering
6483        if (ephemeralPkgName == null) {
6484            return resolveInfos;
6485        }
6486        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6487            final ResolveInfo info = resolveInfos.get(i);
6488            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6489            // allow activities that are defined in the provided package
6490            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6491                if (info.activityInfo.splitName != null
6492                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6493                                info.activityInfo.splitName)) {
6494                    // requested activity is defined in a split that hasn't been installed yet.
6495                    // add the installer to the resolve list
6496                    if (DEBUG_EPHEMERAL) {
6497                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6498                    }
6499                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6500                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6501                            info.activityInfo.packageName, info.activityInfo.splitName,
6502                            info.activityInfo.applicationInfo.versionCode);
6503                    // make sure this resolver is the default
6504                    installerInfo.isDefault = true;
6505                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6506                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6507                    // add a non-generic filter
6508                    installerInfo.filter = new IntentFilter();
6509                    // load resources from the correct package
6510                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6511                    resolveInfos.set(i, installerInfo);
6512                }
6513                continue;
6514            }
6515            // allow activities that have been explicitly exposed to ephemeral apps
6516            if (!isEphemeralApp
6517                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6518                continue;
6519            }
6520            resolveInfos.remove(i);
6521        }
6522        return resolveInfos;
6523    }
6524
6525    /**
6526     * @param resolveInfos list of resolve infos in descending priority order
6527     * @return if the list contains a resolve info with non-negative priority
6528     */
6529    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6530        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6531    }
6532
6533    private static boolean hasWebURI(Intent intent) {
6534        if (intent.getData() == null) {
6535            return false;
6536        }
6537        final String scheme = intent.getScheme();
6538        if (TextUtils.isEmpty(scheme)) {
6539            return false;
6540        }
6541        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6542    }
6543
6544    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6545            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6546            int userId) {
6547        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6548
6549        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6550            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6551                    candidates.size());
6552        }
6553
6554        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6555        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6556        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6557        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6558        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6559        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6560
6561        synchronized (mPackages) {
6562            final int count = candidates.size();
6563            // First, try to use linked apps. Partition the candidates into four lists:
6564            // one for the final results, one for the "do not use ever", one for "undefined status"
6565            // and finally one for "browser app type".
6566            for (int n=0; n<count; n++) {
6567                ResolveInfo info = candidates.get(n);
6568                String packageName = info.activityInfo.packageName;
6569                PackageSetting ps = mSettings.mPackages.get(packageName);
6570                if (ps != null) {
6571                    // Add to the special match all list (Browser use case)
6572                    if (info.handleAllWebDataURI) {
6573                        matchAllList.add(info);
6574                        continue;
6575                    }
6576                    // Try to get the status from User settings first
6577                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6578                    int status = (int)(packedStatus >> 32);
6579                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6580                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6581                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6582                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6583                                    + " : linkgen=" + linkGeneration);
6584                        }
6585                        // Use link-enabled generation as preferredOrder, i.e.
6586                        // prefer newly-enabled over earlier-enabled.
6587                        info.preferredOrder = linkGeneration;
6588                        alwaysList.add(info);
6589                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6590                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6591                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6592                        }
6593                        neverList.add(info);
6594                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6595                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6596                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6597                        }
6598                        alwaysAskList.add(info);
6599                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6600                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6601                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6602                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6603                        }
6604                        undefinedList.add(info);
6605                    }
6606                }
6607            }
6608
6609            // We'll want to include browser possibilities in a few cases
6610            boolean includeBrowser = false;
6611
6612            // First try to add the "always" resolution(s) for the current user, if any
6613            if (alwaysList.size() > 0) {
6614                result.addAll(alwaysList);
6615            } else {
6616                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6617                result.addAll(undefinedList);
6618                // Maybe add one for the other profile.
6619                if (xpDomainInfo != null && (
6620                        xpDomainInfo.bestDomainVerificationStatus
6621                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6622                    result.add(xpDomainInfo.resolveInfo);
6623                }
6624                includeBrowser = true;
6625            }
6626
6627            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6628            // If there were 'always' entries their preferred order has been set, so we also
6629            // back that off to make the alternatives equivalent
6630            if (alwaysAskList.size() > 0) {
6631                for (ResolveInfo i : result) {
6632                    i.preferredOrder = 0;
6633                }
6634                result.addAll(alwaysAskList);
6635                includeBrowser = true;
6636            }
6637
6638            if (includeBrowser) {
6639                // Also add browsers (all of them or only the default one)
6640                if (DEBUG_DOMAIN_VERIFICATION) {
6641                    Slog.v(TAG, "   ...including browsers in candidate set");
6642                }
6643                if ((matchFlags & MATCH_ALL) != 0) {
6644                    result.addAll(matchAllList);
6645                } else {
6646                    // Browser/generic handling case.  If there's a default browser, go straight
6647                    // to that (but only if there is no other higher-priority match).
6648                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6649                    int maxMatchPrio = 0;
6650                    ResolveInfo defaultBrowserMatch = null;
6651                    final int numCandidates = matchAllList.size();
6652                    for (int n = 0; n < numCandidates; n++) {
6653                        ResolveInfo info = matchAllList.get(n);
6654                        // track the highest overall match priority...
6655                        if (info.priority > maxMatchPrio) {
6656                            maxMatchPrio = info.priority;
6657                        }
6658                        // ...and the highest-priority default browser match
6659                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6660                            if (defaultBrowserMatch == null
6661                                    || (defaultBrowserMatch.priority < info.priority)) {
6662                                if (debug) {
6663                                    Slog.v(TAG, "Considering default browser match " + info);
6664                                }
6665                                defaultBrowserMatch = info;
6666                            }
6667                        }
6668                    }
6669                    if (defaultBrowserMatch != null
6670                            && defaultBrowserMatch.priority >= maxMatchPrio
6671                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6672                    {
6673                        if (debug) {
6674                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6675                        }
6676                        result.add(defaultBrowserMatch);
6677                    } else {
6678                        result.addAll(matchAllList);
6679                    }
6680                }
6681
6682                // If there is nothing selected, add all candidates and remove the ones that the user
6683                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6684                if (result.size() == 0) {
6685                    result.addAll(candidates);
6686                    result.removeAll(neverList);
6687                }
6688            }
6689        }
6690        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6691            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6692                    result.size());
6693            for (ResolveInfo info : result) {
6694                Slog.v(TAG, "  + " + info.activityInfo);
6695            }
6696        }
6697        return result;
6698    }
6699
6700    // Returns a packed value as a long:
6701    //
6702    // high 'int'-sized word: link status: undefined/ask/never/always.
6703    // low 'int'-sized word: relative priority among 'always' results.
6704    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6705        long result = ps.getDomainVerificationStatusForUser(userId);
6706        // if none available, get the master status
6707        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6708            if (ps.getIntentFilterVerificationInfo() != null) {
6709                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6710            }
6711        }
6712        return result;
6713    }
6714
6715    private ResolveInfo querySkipCurrentProfileIntents(
6716            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6717            int flags, int sourceUserId) {
6718        if (matchingFilters != null) {
6719            int size = matchingFilters.size();
6720            for (int i = 0; i < size; i ++) {
6721                CrossProfileIntentFilter filter = matchingFilters.get(i);
6722                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6723                    // Checking if there are activities in the target user that can handle the
6724                    // intent.
6725                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6726                            resolvedType, flags, sourceUserId);
6727                    if (resolveInfo != null) {
6728                        return resolveInfo;
6729                    }
6730                }
6731            }
6732        }
6733        return null;
6734    }
6735
6736    // Return matching ResolveInfo in target user if any.
6737    private ResolveInfo queryCrossProfileIntents(
6738            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6739            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6740        if (matchingFilters != null) {
6741            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6742            // match the same intent. For performance reasons, it is better not to
6743            // run queryIntent twice for the same userId
6744            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6745            int size = matchingFilters.size();
6746            for (int i = 0; i < size; i++) {
6747                CrossProfileIntentFilter filter = matchingFilters.get(i);
6748                int targetUserId = filter.getTargetUserId();
6749                boolean skipCurrentProfile =
6750                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6751                boolean skipCurrentProfileIfNoMatchFound =
6752                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6753                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6754                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6755                    // Checking if there are activities in the target user that can handle the
6756                    // intent.
6757                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6758                            resolvedType, flags, sourceUserId);
6759                    if (resolveInfo != null) return resolveInfo;
6760                    alreadyTriedUserIds.put(targetUserId, true);
6761                }
6762            }
6763        }
6764        return null;
6765    }
6766
6767    /**
6768     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6769     * will forward the intent to the filter's target user.
6770     * Otherwise, returns null.
6771     */
6772    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6773            String resolvedType, int flags, int sourceUserId) {
6774        int targetUserId = filter.getTargetUserId();
6775        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6776                resolvedType, flags, targetUserId);
6777        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6778            // If all the matches in the target profile are suspended, return null.
6779            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6780                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6781                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6782                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6783                            targetUserId);
6784                }
6785            }
6786        }
6787        return null;
6788    }
6789
6790    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6791            int sourceUserId, int targetUserId) {
6792        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6793        long ident = Binder.clearCallingIdentity();
6794        boolean targetIsProfile;
6795        try {
6796            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6797        } finally {
6798            Binder.restoreCallingIdentity(ident);
6799        }
6800        String className;
6801        if (targetIsProfile) {
6802            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6803        } else {
6804            className = FORWARD_INTENT_TO_PARENT;
6805        }
6806        ComponentName forwardingActivityComponentName = new ComponentName(
6807                mAndroidApplication.packageName, className);
6808        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6809                sourceUserId);
6810        if (!targetIsProfile) {
6811            forwardingActivityInfo.showUserIcon = targetUserId;
6812            forwardingResolveInfo.noResourceId = true;
6813        }
6814        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6815        forwardingResolveInfo.priority = 0;
6816        forwardingResolveInfo.preferredOrder = 0;
6817        forwardingResolveInfo.match = 0;
6818        forwardingResolveInfo.isDefault = true;
6819        forwardingResolveInfo.filter = filter;
6820        forwardingResolveInfo.targetUserId = targetUserId;
6821        return forwardingResolveInfo;
6822    }
6823
6824    @Override
6825    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6826            Intent[] specifics, String[] specificTypes, Intent intent,
6827            String resolvedType, int flags, int userId) {
6828        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6829                specificTypes, intent, resolvedType, flags, userId));
6830    }
6831
6832    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6833            Intent[] specifics, String[] specificTypes, Intent intent,
6834            String resolvedType, int flags, int userId) {
6835        if (!sUserManager.exists(userId)) return Collections.emptyList();
6836        final int callingUid = Binder.getCallingUid();
6837        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
6838                false /*includeInstantApps*/);
6839        enforceCrossUserPermission(callingUid, userId,
6840                false /*requireFullPermission*/, false /*checkShell*/,
6841                "query intent activity options");
6842        final String resultsAction = intent.getAction();
6843
6844        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6845                | PackageManager.GET_RESOLVED_FILTER, userId);
6846
6847        if (DEBUG_INTENT_MATCHING) {
6848            Log.v(TAG, "Query " + intent + ": " + results);
6849        }
6850
6851        int specificsPos = 0;
6852        int N;
6853
6854        // todo: note that the algorithm used here is O(N^2).  This
6855        // isn't a problem in our current environment, but if we start running
6856        // into situations where we have more than 5 or 10 matches then this
6857        // should probably be changed to something smarter...
6858
6859        // First we go through and resolve each of the specific items
6860        // that were supplied, taking care of removing any corresponding
6861        // duplicate items in the generic resolve list.
6862        if (specifics != null) {
6863            for (int i=0; i<specifics.length; i++) {
6864                final Intent sintent = specifics[i];
6865                if (sintent == null) {
6866                    continue;
6867                }
6868
6869                if (DEBUG_INTENT_MATCHING) {
6870                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6871                }
6872
6873                String action = sintent.getAction();
6874                if (resultsAction != null && resultsAction.equals(action)) {
6875                    // If this action was explicitly requested, then don't
6876                    // remove things that have it.
6877                    action = null;
6878                }
6879
6880                ResolveInfo ri = null;
6881                ActivityInfo ai = null;
6882
6883                ComponentName comp = sintent.getComponent();
6884                if (comp == null) {
6885                    ri = resolveIntent(
6886                        sintent,
6887                        specificTypes != null ? specificTypes[i] : null,
6888                            flags, userId);
6889                    if (ri == null) {
6890                        continue;
6891                    }
6892                    if (ri == mResolveInfo) {
6893                        // ACK!  Must do something better with this.
6894                    }
6895                    ai = ri.activityInfo;
6896                    comp = new ComponentName(ai.applicationInfo.packageName,
6897                            ai.name);
6898                } else {
6899                    ai = getActivityInfo(comp, flags, userId);
6900                    if (ai == null) {
6901                        continue;
6902                    }
6903                }
6904
6905                // Look for any generic query activities that are duplicates
6906                // of this specific one, and remove them from the results.
6907                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6908                N = results.size();
6909                int j;
6910                for (j=specificsPos; j<N; j++) {
6911                    ResolveInfo sri = results.get(j);
6912                    if ((sri.activityInfo.name.equals(comp.getClassName())
6913                            && sri.activityInfo.applicationInfo.packageName.equals(
6914                                    comp.getPackageName()))
6915                        || (action != null && sri.filter.matchAction(action))) {
6916                        results.remove(j);
6917                        if (DEBUG_INTENT_MATCHING) Log.v(
6918                            TAG, "Removing duplicate item from " + j
6919                            + " due to specific " + specificsPos);
6920                        if (ri == null) {
6921                            ri = sri;
6922                        }
6923                        j--;
6924                        N--;
6925                    }
6926                }
6927
6928                // Add this specific item to its proper place.
6929                if (ri == null) {
6930                    ri = new ResolveInfo();
6931                    ri.activityInfo = ai;
6932                }
6933                results.add(specificsPos, ri);
6934                ri.specificIndex = i;
6935                specificsPos++;
6936            }
6937        }
6938
6939        // Now we go through the remaining generic results and remove any
6940        // duplicate actions that are found here.
6941        N = results.size();
6942        for (int i=specificsPos; i<N-1; i++) {
6943            final ResolveInfo rii = results.get(i);
6944            if (rii.filter == null) {
6945                continue;
6946            }
6947
6948            // Iterate over all of the actions of this result's intent
6949            // filter...  typically this should be just one.
6950            final Iterator<String> it = rii.filter.actionsIterator();
6951            if (it == null) {
6952                continue;
6953            }
6954            while (it.hasNext()) {
6955                final String action = it.next();
6956                if (resultsAction != null && resultsAction.equals(action)) {
6957                    // If this action was explicitly requested, then don't
6958                    // remove things that have it.
6959                    continue;
6960                }
6961                for (int j=i+1; j<N; j++) {
6962                    final ResolveInfo rij = results.get(j);
6963                    if (rij.filter != null && rij.filter.hasAction(action)) {
6964                        results.remove(j);
6965                        if (DEBUG_INTENT_MATCHING) Log.v(
6966                            TAG, "Removing duplicate item from " + j
6967                            + " due to action " + action + " at " + i);
6968                        j--;
6969                        N--;
6970                    }
6971                }
6972            }
6973
6974            // If the caller didn't request filter information, drop it now
6975            // so we don't have to marshall/unmarshall it.
6976            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6977                rii.filter = null;
6978            }
6979        }
6980
6981        // Filter out the caller activity if so requested.
6982        if (caller != null) {
6983            N = results.size();
6984            for (int i=0; i<N; i++) {
6985                ActivityInfo ainfo = results.get(i).activityInfo;
6986                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6987                        && caller.getClassName().equals(ainfo.name)) {
6988                    results.remove(i);
6989                    break;
6990                }
6991            }
6992        }
6993
6994        // If the caller didn't request filter information,
6995        // drop them now so we don't have to
6996        // marshall/unmarshall it.
6997        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6998            N = results.size();
6999            for (int i=0; i<N; i++) {
7000                results.get(i).filter = null;
7001            }
7002        }
7003
7004        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7005        return results;
7006    }
7007
7008    @Override
7009    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7010            String resolvedType, int flags, int userId) {
7011        return new ParceledListSlice<>(
7012                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7013    }
7014
7015    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7016            String resolvedType, int flags, int userId) {
7017        if (!sUserManager.exists(userId)) return Collections.emptyList();
7018        final int callingUid = Binder.getCallingUid();
7019        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7020                false /*includeInstantApps*/);
7021        ComponentName comp = intent.getComponent();
7022        if (comp == null) {
7023            if (intent.getSelector() != null) {
7024                intent = intent.getSelector();
7025                comp = intent.getComponent();
7026            }
7027        }
7028        if (comp != null) {
7029            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7030            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7031            if (ai != null) {
7032                ResolveInfo ri = new ResolveInfo();
7033                ri.activityInfo = ai;
7034                list.add(ri);
7035            }
7036            return list;
7037        }
7038
7039        // reader
7040        synchronized (mPackages) {
7041            String pkgName = intent.getPackage();
7042            if (pkgName == null) {
7043                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7044            }
7045            final PackageParser.Package pkg = mPackages.get(pkgName);
7046            if (pkg != null) {
7047                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7048                        userId);
7049            }
7050            return Collections.emptyList();
7051        }
7052    }
7053
7054    @Override
7055    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7056        final int callingUid = Binder.getCallingUid();
7057        return resolveServiceInternal(
7058                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7059    }
7060
7061    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7062            int userId, int callingUid, boolean includeInstantApps) {
7063        if (!sUserManager.exists(userId)) return null;
7064        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7065        List<ResolveInfo> query = queryIntentServicesInternal(
7066                intent, resolvedType, flags, userId, callingUid, includeInstantApps);
7067        if (query != null) {
7068            if (query.size() >= 1) {
7069                // If there is more than one service with the same priority,
7070                // just arbitrarily pick the first one.
7071                return query.get(0);
7072            }
7073        }
7074        return null;
7075    }
7076
7077    @Override
7078    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7079            String resolvedType, int flags, int userId) {
7080        final int callingUid = Binder.getCallingUid();
7081        return new ParceledListSlice<>(queryIntentServicesInternal(
7082                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7083    }
7084
7085    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7086            String resolvedType, int flags, int userId, int callingUid,
7087            boolean includeInstantApps) {
7088        if (!sUserManager.exists(userId)) return Collections.emptyList();
7089        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7090        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7091        ComponentName comp = intent.getComponent();
7092        if (comp == null) {
7093            if (intent.getSelector() != null) {
7094                intent = intent.getSelector();
7095                comp = intent.getComponent();
7096            }
7097        }
7098        if (comp != null) {
7099            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7100            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7101            if (si != null) {
7102                // When specifying an explicit component, we prevent the service from being
7103                // used when either 1) the service is in an instant application and the
7104                // caller is not the same instant application or 2) the calling package is
7105                // ephemeral and the activity is not visible to ephemeral applications.
7106                final boolean matchInstantApp =
7107                        (flags & PackageManager.MATCH_INSTANT) != 0;
7108                final boolean matchVisibleToInstantAppOnly =
7109                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7110                final boolean isCallerInstantApp =
7111                        instantAppPkgName != null;
7112                final boolean isTargetSameInstantApp =
7113                        comp.getPackageName().equals(instantAppPkgName);
7114                final boolean isTargetInstantApp =
7115                        (si.applicationInfo.privateFlags
7116                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7117                final boolean isTargetHiddenFromInstantApp =
7118                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
7119                final boolean blockResolution =
7120                        !isTargetSameInstantApp
7121                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7122                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7123                                        && isTargetHiddenFromInstantApp));
7124                if (!blockResolution) {
7125                    final ResolveInfo ri = new ResolveInfo();
7126                    ri.serviceInfo = si;
7127                    list.add(ri);
7128                }
7129            }
7130            return list;
7131        }
7132
7133        // reader
7134        synchronized (mPackages) {
7135            String pkgName = intent.getPackage();
7136            if (pkgName == null) {
7137                return applyPostServiceResolutionFilter(
7138                        mServices.queryIntent(intent, resolvedType, flags, userId),
7139                        instantAppPkgName);
7140            }
7141            final PackageParser.Package pkg = mPackages.get(pkgName);
7142            if (pkg != null) {
7143                return applyPostServiceResolutionFilter(
7144                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7145                                userId),
7146                        instantAppPkgName);
7147            }
7148            return Collections.emptyList();
7149        }
7150    }
7151
7152    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7153            String instantAppPkgName) {
7154        // TODO: When adding on-demand split support for non-instant apps, remove this check
7155        // and always apply post filtering
7156        if (instantAppPkgName == null) {
7157            return resolveInfos;
7158        }
7159        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7160            final ResolveInfo info = resolveInfos.get(i);
7161            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7162            // allow services that are defined in the provided package
7163            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7164                if (info.serviceInfo.splitName != null
7165                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7166                                info.serviceInfo.splitName)) {
7167                    // requested service is defined in a split that hasn't been installed yet.
7168                    // add the installer to the resolve list
7169                    if (DEBUG_EPHEMERAL) {
7170                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7171                    }
7172                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7173                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7174                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7175                            info.serviceInfo.applicationInfo.versionCode);
7176                    // make sure this resolver is the default
7177                    installerInfo.isDefault = true;
7178                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7179                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7180                    // add a non-generic filter
7181                    installerInfo.filter = new IntentFilter();
7182                    // load resources from the correct package
7183                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7184                    resolveInfos.set(i, installerInfo);
7185                }
7186                continue;
7187            }
7188            // allow services that have been explicitly exposed to ephemeral apps
7189            if (!isEphemeralApp
7190                    && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
7191                continue;
7192            }
7193            resolveInfos.remove(i);
7194        }
7195        return resolveInfos;
7196    }
7197
7198    @Override
7199    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7200            String resolvedType, int flags, int userId) {
7201        return new ParceledListSlice<>(
7202                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7203    }
7204
7205    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7206            Intent intent, String resolvedType, int flags, int userId) {
7207        if (!sUserManager.exists(userId)) return Collections.emptyList();
7208        final int callingUid = Binder.getCallingUid();
7209        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7210        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7211                false /*includeInstantApps*/);
7212        ComponentName comp = intent.getComponent();
7213        if (comp == null) {
7214            if (intent.getSelector() != null) {
7215                intent = intent.getSelector();
7216                comp = intent.getComponent();
7217            }
7218        }
7219        if (comp != null) {
7220            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7221            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7222            if (pi != null) {
7223                // When specifying an explicit component, we prevent the provider from being
7224                // used when either 1) the provider is in an instant application and the
7225                // caller is not the same instant application or 2) the calling package is an
7226                // instant application and the provider is not visible to instant applications.
7227                final boolean matchInstantApp =
7228                        (flags & PackageManager.MATCH_INSTANT) != 0;
7229                final boolean matchVisibleToInstantAppOnly =
7230                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7231                final boolean isCallerInstantApp =
7232                        instantAppPkgName != null;
7233                final boolean isTargetSameInstantApp =
7234                        comp.getPackageName().equals(instantAppPkgName);
7235                final boolean isTargetInstantApp =
7236                        (pi.applicationInfo.privateFlags
7237                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7238                final boolean isTargetHiddenFromInstantApp =
7239                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
7240                final boolean blockResolution =
7241                        !isTargetSameInstantApp
7242                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7243                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7244                                        && isTargetHiddenFromInstantApp));
7245                if (!blockResolution) {
7246                    final ResolveInfo ri = new ResolveInfo();
7247                    ri.providerInfo = pi;
7248                    list.add(ri);
7249                }
7250            }
7251            return list;
7252        }
7253
7254        // reader
7255        synchronized (mPackages) {
7256            String pkgName = intent.getPackage();
7257            if (pkgName == null) {
7258                return applyPostContentProviderResolutionFilter(
7259                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7260                        instantAppPkgName);
7261            }
7262            final PackageParser.Package pkg = mPackages.get(pkgName);
7263            if (pkg != null) {
7264                return applyPostContentProviderResolutionFilter(
7265                        mProviders.queryIntentForPackage(
7266                        intent, resolvedType, flags, pkg.providers, userId),
7267                        instantAppPkgName);
7268            }
7269            return Collections.emptyList();
7270        }
7271    }
7272
7273    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7274            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7275        // TODO: When adding on-demand split support for non-instant applications, remove
7276        // this check and always apply post filtering
7277        if (instantAppPkgName == null) {
7278            return resolveInfos;
7279        }
7280        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7281            final ResolveInfo info = resolveInfos.get(i);
7282            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7283            // allow providers that are defined in the provided package
7284            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7285                if (info.providerInfo.splitName != null
7286                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7287                                info.providerInfo.splitName)) {
7288                    // requested provider is defined in a split that hasn't been installed yet.
7289                    // add the installer to the resolve list
7290                    if (DEBUG_EPHEMERAL) {
7291                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7292                    }
7293                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7294                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7295                            info.providerInfo.packageName, info.providerInfo.splitName,
7296                            info.providerInfo.applicationInfo.versionCode);
7297                    // make sure this resolver is the default
7298                    installerInfo.isDefault = true;
7299                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7300                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7301                    // add a non-generic filter
7302                    installerInfo.filter = new IntentFilter();
7303                    // load resources from the correct package
7304                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7305                    resolveInfos.set(i, installerInfo);
7306                }
7307                continue;
7308            }
7309            // allow providers that have been explicitly exposed to instant applications
7310            if (!isEphemeralApp
7311                    && ((info.providerInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
7312                continue;
7313            }
7314            resolveInfos.remove(i);
7315        }
7316        return resolveInfos;
7317    }
7318
7319    @Override
7320    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7321        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7322        flags = updateFlagsForPackage(flags, userId, null);
7323        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7324        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7325                true /* requireFullPermission */, false /* checkShell */,
7326                "get installed packages");
7327
7328        // writer
7329        synchronized (mPackages) {
7330            ArrayList<PackageInfo> list;
7331            if (listUninstalled) {
7332                list = new ArrayList<>(mSettings.mPackages.size());
7333                for (PackageSetting ps : mSettings.mPackages.values()) {
7334                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7335                        continue;
7336                    }
7337                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7338                    if (pi != null) {
7339                        list.add(pi);
7340                    }
7341                }
7342            } else {
7343                list = new ArrayList<>(mPackages.size());
7344                for (PackageParser.Package p : mPackages.values()) {
7345                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7346                            Binder.getCallingUid(), userId)) {
7347                        continue;
7348                    }
7349                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7350                            p.mExtras, flags, userId);
7351                    if (pi != null) {
7352                        list.add(pi);
7353                    }
7354                }
7355            }
7356
7357            return new ParceledListSlice<>(list);
7358        }
7359    }
7360
7361    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7362            String[] permissions, boolean[] tmp, int flags, int userId) {
7363        int numMatch = 0;
7364        final PermissionsState permissionsState = ps.getPermissionsState();
7365        for (int i=0; i<permissions.length; i++) {
7366            final String permission = permissions[i];
7367            if (permissionsState.hasPermission(permission, userId)) {
7368                tmp[i] = true;
7369                numMatch++;
7370            } else {
7371                tmp[i] = false;
7372            }
7373        }
7374        if (numMatch == 0) {
7375            return;
7376        }
7377        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7378
7379        // The above might return null in cases of uninstalled apps or install-state
7380        // skew across users/profiles.
7381        if (pi != null) {
7382            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7383                if (numMatch == permissions.length) {
7384                    pi.requestedPermissions = permissions;
7385                } else {
7386                    pi.requestedPermissions = new String[numMatch];
7387                    numMatch = 0;
7388                    for (int i=0; i<permissions.length; i++) {
7389                        if (tmp[i]) {
7390                            pi.requestedPermissions[numMatch] = permissions[i];
7391                            numMatch++;
7392                        }
7393                    }
7394                }
7395            }
7396            list.add(pi);
7397        }
7398    }
7399
7400    @Override
7401    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7402            String[] permissions, int flags, int userId) {
7403        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7404        flags = updateFlagsForPackage(flags, userId, permissions);
7405        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7406                true /* requireFullPermission */, false /* checkShell */,
7407                "get packages holding permissions");
7408        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7409
7410        // writer
7411        synchronized (mPackages) {
7412            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7413            boolean[] tmpBools = new boolean[permissions.length];
7414            if (listUninstalled) {
7415                for (PackageSetting ps : mSettings.mPackages.values()) {
7416                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7417                            userId);
7418                }
7419            } else {
7420                for (PackageParser.Package pkg : mPackages.values()) {
7421                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7422                    if (ps != null) {
7423                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7424                                userId);
7425                    }
7426                }
7427            }
7428
7429            return new ParceledListSlice<PackageInfo>(list);
7430        }
7431    }
7432
7433    @Override
7434    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7435        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7436        flags = updateFlagsForApplication(flags, userId, null);
7437        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7438
7439        // writer
7440        synchronized (mPackages) {
7441            ArrayList<ApplicationInfo> list;
7442            if (listUninstalled) {
7443                list = new ArrayList<>(mSettings.mPackages.size());
7444                for (PackageSetting ps : mSettings.mPackages.values()) {
7445                    ApplicationInfo ai;
7446                    int effectiveFlags = flags;
7447                    if (ps.isSystem()) {
7448                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7449                    }
7450                    if (ps.pkg != null) {
7451                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7452                            continue;
7453                        }
7454                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7455                                ps.readUserState(userId), userId);
7456                        if (ai != null) {
7457                            rebaseEnabledOverlays(ai, userId);
7458                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7459                        }
7460                    } else {
7461                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7462                        // and already converts to externally visible package name
7463                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7464                                Binder.getCallingUid(), effectiveFlags, userId);
7465                    }
7466                    if (ai != null) {
7467                        list.add(ai);
7468                    }
7469                }
7470            } else {
7471                list = new ArrayList<>(mPackages.size());
7472                for (PackageParser.Package p : mPackages.values()) {
7473                    if (p.mExtras != null) {
7474                        PackageSetting ps = (PackageSetting) p.mExtras;
7475                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7476                            continue;
7477                        }
7478                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7479                                ps.readUserState(userId), userId);
7480                        if (ai != null) {
7481                            rebaseEnabledOverlays(ai, userId);
7482                            ai.packageName = resolveExternalPackageNameLPr(p);
7483                            list.add(ai);
7484                        }
7485                    }
7486                }
7487            }
7488
7489            return new ParceledListSlice<>(list);
7490        }
7491    }
7492
7493    @Override
7494    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7495        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7496            return null;
7497        }
7498
7499        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7500                "getEphemeralApplications");
7501        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7502                true /* requireFullPermission */, false /* checkShell */,
7503                "getEphemeralApplications");
7504        synchronized (mPackages) {
7505            List<InstantAppInfo> instantApps = mInstantAppRegistry
7506                    .getInstantAppsLPr(userId);
7507            if (instantApps != null) {
7508                return new ParceledListSlice<>(instantApps);
7509            }
7510        }
7511        return null;
7512    }
7513
7514    @Override
7515    public boolean isInstantApp(String packageName, int userId) {
7516        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7517                true /* requireFullPermission */, false /* checkShell */,
7518                "isInstantApp");
7519        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7520            return false;
7521        }
7522        int uid = Binder.getCallingUid();
7523        if (Process.isIsolated(uid)) {
7524            uid = mIsolatedOwners.get(uid);
7525        }
7526
7527        synchronized (mPackages) {
7528            final PackageSetting ps = mSettings.mPackages.get(packageName);
7529            PackageParser.Package pkg = mPackages.get(packageName);
7530            final boolean returnAllowed =
7531                    ps != null
7532                    && (isCallerSameApp(packageName, uid)
7533                            || mContext.checkCallingOrSelfPermission(
7534                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7535                                            == PERMISSION_GRANTED
7536                            || mInstantAppRegistry.isInstantAccessGranted(
7537                                    userId, UserHandle.getAppId(uid), ps.appId));
7538            if (returnAllowed) {
7539                return ps.getInstantApp(userId);
7540            }
7541        }
7542        return false;
7543    }
7544
7545    @Override
7546    public byte[] getInstantAppCookie(String packageName, int userId) {
7547        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7548            return null;
7549        }
7550
7551        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7552                true /* requireFullPermission */, false /* checkShell */,
7553                "getInstantAppCookie");
7554        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7555            return null;
7556        }
7557        synchronized (mPackages) {
7558            return mInstantAppRegistry.getInstantAppCookieLPw(
7559                    packageName, userId);
7560        }
7561    }
7562
7563    @Override
7564    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7565        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7566            return true;
7567        }
7568
7569        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7570                true /* requireFullPermission */, true /* checkShell */,
7571                "setInstantAppCookie");
7572        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7573            return false;
7574        }
7575        synchronized (mPackages) {
7576            return mInstantAppRegistry.setInstantAppCookieLPw(
7577                    packageName, cookie, userId);
7578        }
7579    }
7580
7581    @Override
7582    public Bitmap getInstantAppIcon(String packageName, int userId) {
7583        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7584            return null;
7585        }
7586
7587        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7588                "getInstantAppIcon");
7589
7590        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7591                true /* requireFullPermission */, false /* checkShell */,
7592                "getInstantAppIcon");
7593
7594        synchronized (mPackages) {
7595            return mInstantAppRegistry.getInstantAppIconLPw(
7596                    packageName, userId);
7597        }
7598    }
7599
7600    private boolean isCallerSameApp(String packageName, int uid) {
7601        PackageParser.Package pkg = mPackages.get(packageName);
7602        return pkg != null
7603                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7604    }
7605
7606    @Override
7607    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7608        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7609    }
7610
7611    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7612        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7613
7614        // reader
7615        synchronized (mPackages) {
7616            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7617            final int userId = UserHandle.getCallingUserId();
7618            while (i.hasNext()) {
7619                final PackageParser.Package p = i.next();
7620                if (p.applicationInfo == null) continue;
7621
7622                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7623                        && !p.applicationInfo.isDirectBootAware();
7624                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7625                        && p.applicationInfo.isDirectBootAware();
7626
7627                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7628                        && (!mSafeMode || isSystemApp(p))
7629                        && (matchesUnaware || matchesAware)) {
7630                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7631                    if (ps != null) {
7632                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7633                                ps.readUserState(userId), userId);
7634                        if (ai != null) {
7635                            rebaseEnabledOverlays(ai, userId);
7636                            finalList.add(ai);
7637                        }
7638                    }
7639                }
7640            }
7641        }
7642
7643        return finalList;
7644    }
7645
7646    @Override
7647    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7648        if (!sUserManager.exists(userId)) return null;
7649        flags = updateFlagsForComponent(flags, userId, name);
7650        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7651        // reader
7652        synchronized (mPackages) {
7653            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7654            PackageSetting ps = provider != null
7655                    ? mSettings.mPackages.get(provider.owner.packageName)
7656                    : null;
7657            if (ps != null) {
7658                final boolean isInstantApp = ps.getInstantApp(userId);
7659                // normal application; filter out instant application provider
7660                if (instantAppPkgName == null && isInstantApp) {
7661                    return null;
7662                }
7663                // instant application; filter out other instant applications
7664                if (instantAppPkgName != null
7665                        && isInstantApp
7666                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7667                    return null;
7668                }
7669                // instant application; filter out non-exposed provider
7670                if (instantAppPkgName != null
7671                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0) {
7672                    return null;
7673                }
7674                // provider not enabled
7675                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7676                    return null;
7677                }
7678                return PackageParser.generateProviderInfo(
7679                        provider, flags, ps.readUserState(userId), userId);
7680            }
7681            return null;
7682        }
7683    }
7684
7685    /**
7686     * @deprecated
7687     */
7688    @Deprecated
7689    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7690        // reader
7691        synchronized (mPackages) {
7692            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7693                    .entrySet().iterator();
7694            final int userId = UserHandle.getCallingUserId();
7695            while (i.hasNext()) {
7696                Map.Entry<String, PackageParser.Provider> entry = i.next();
7697                PackageParser.Provider p = entry.getValue();
7698                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7699
7700                if (ps != null && p.syncable
7701                        && (!mSafeMode || (p.info.applicationInfo.flags
7702                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7703                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7704                            ps.readUserState(userId), userId);
7705                    if (info != null) {
7706                        outNames.add(entry.getKey());
7707                        outInfo.add(info);
7708                    }
7709                }
7710            }
7711        }
7712    }
7713
7714    @Override
7715    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7716            int uid, int flags, String metaDataKey) {
7717        final int userId = processName != null ? UserHandle.getUserId(uid)
7718                : UserHandle.getCallingUserId();
7719        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7720        flags = updateFlagsForComponent(flags, userId, processName);
7721
7722        ArrayList<ProviderInfo> finalList = null;
7723        // reader
7724        synchronized (mPackages) {
7725            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7726            while (i.hasNext()) {
7727                final PackageParser.Provider p = i.next();
7728                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7729                if (ps != null && p.info.authority != null
7730                        && (processName == null
7731                                || (p.info.processName.equals(processName)
7732                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7733                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7734
7735                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7736                    // parameter.
7737                    if (metaDataKey != null
7738                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7739                        continue;
7740                    }
7741
7742                    if (finalList == null) {
7743                        finalList = new ArrayList<ProviderInfo>(3);
7744                    }
7745                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7746                            ps.readUserState(userId), userId);
7747                    if (info != null) {
7748                        finalList.add(info);
7749                    }
7750                }
7751            }
7752        }
7753
7754        if (finalList != null) {
7755            Collections.sort(finalList, mProviderInitOrderSorter);
7756            return new ParceledListSlice<ProviderInfo>(finalList);
7757        }
7758
7759        return ParceledListSlice.emptyList();
7760    }
7761
7762    @Override
7763    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7764        // reader
7765        synchronized (mPackages) {
7766            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7767            return PackageParser.generateInstrumentationInfo(i, flags);
7768        }
7769    }
7770
7771    @Override
7772    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7773            String targetPackage, int flags) {
7774        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7775    }
7776
7777    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7778            int flags) {
7779        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7780
7781        // reader
7782        synchronized (mPackages) {
7783            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7784            while (i.hasNext()) {
7785                final PackageParser.Instrumentation p = i.next();
7786                if (targetPackage == null
7787                        || targetPackage.equals(p.info.targetPackage)) {
7788                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7789                            flags);
7790                    if (ii != null) {
7791                        finalList.add(ii);
7792                    }
7793                }
7794            }
7795        }
7796
7797        return finalList;
7798    }
7799
7800    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7801        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7802        try {
7803            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7804        } finally {
7805            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7806        }
7807    }
7808
7809    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7810        final File[] files = dir.listFiles();
7811        if (ArrayUtils.isEmpty(files)) {
7812            Log.d(TAG, "No files in app dir " + dir);
7813            return;
7814        }
7815
7816        if (DEBUG_PACKAGE_SCANNING) {
7817            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7818                    + " flags=0x" + Integer.toHexString(parseFlags));
7819        }
7820        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7821                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7822
7823        // Submit files for parsing in parallel
7824        int fileCount = 0;
7825        for (File file : files) {
7826            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7827                    && !PackageInstallerService.isStageName(file.getName());
7828            if (!isPackage) {
7829                // Ignore entries which are not packages
7830                continue;
7831            }
7832            parallelPackageParser.submit(file, parseFlags);
7833            fileCount++;
7834        }
7835
7836        // Process results one by one
7837        for (; fileCount > 0; fileCount--) {
7838            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7839            Throwable throwable = parseResult.throwable;
7840            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7841
7842            if (throwable == null) {
7843                // Static shared libraries have synthetic package names
7844                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7845                    renameStaticSharedLibraryPackage(parseResult.pkg);
7846                }
7847                try {
7848                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7849                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7850                                currentTime, null);
7851                    }
7852                } catch (PackageManagerException e) {
7853                    errorCode = e.error;
7854                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7855                }
7856            } else if (throwable instanceof PackageParser.PackageParserException) {
7857                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7858                        throwable;
7859                errorCode = e.error;
7860                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7861            } else {
7862                throw new IllegalStateException("Unexpected exception occurred while parsing "
7863                        + parseResult.scanFile, throwable);
7864            }
7865
7866            // Delete invalid userdata apps
7867            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7868                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7869                logCriticalInfo(Log.WARN,
7870                        "Deleting invalid package at " + parseResult.scanFile);
7871                removeCodePathLI(parseResult.scanFile);
7872            }
7873        }
7874        parallelPackageParser.close();
7875    }
7876
7877    private static File getSettingsProblemFile() {
7878        File dataDir = Environment.getDataDirectory();
7879        File systemDir = new File(dataDir, "system");
7880        File fname = new File(systemDir, "uiderrors.txt");
7881        return fname;
7882    }
7883
7884    static void reportSettingsProblem(int priority, String msg) {
7885        logCriticalInfo(priority, msg);
7886    }
7887
7888    public static void logCriticalInfo(int priority, String msg) {
7889        Slog.println(priority, TAG, msg);
7890        EventLogTags.writePmCriticalInfo(msg);
7891        try {
7892            File fname = getSettingsProblemFile();
7893            FileOutputStream out = new FileOutputStream(fname, true);
7894            PrintWriter pw = new FastPrintWriter(out);
7895            SimpleDateFormat formatter = new SimpleDateFormat();
7896            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7897            pw.println(dateString + ": " + msg);
7898            pw.close();
7899            FileUtils.setPermissions(
7900                    fname.toString(),
7901                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7902                    -1, -1);
7903        } catch (java.io.IOException e) {
7904        }
7905    }
7906
7907    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7908        if (srcFile.isDirectory()) {
7909            final File baseFile = new File(pkg.baseCodePath);
7910            long maxModifiedTime = baseFile.lastModified();
7911            if (pkg.splitCodePaths != null) {
7912                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7913                    final File splitFile = new File(pkg.splitCodePaths[i]);
7914                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7915                }
7916            }
7917            return maxModifiedTime;
7918        }
7919        return srcFile.lastModified();
7920    }
7921
7922    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7923            final int policyFlags) throws PackageManagerException {
7924        // When upgrading from pre-N MR1, verify the package time stamp using the package
7925        // directory and not the APK file.
7926        final long lastModifiedTime = mIsPreNMR1Upgrade
7927                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7928        if (ps != null
7929                && ps.codePath.equals(srcFile)
7930                && ps.timeStamp == lastModifiedTime
7931                && !isCompatSignatureUpdateNeeded(pkg)
7932                && !isRecoverSignatureUpdateNeeded(pkg)) {
7933            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7934            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7935            ArraySet<PublicKey> signingKs;
7936            synchronized (mPackages) {
7937                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7938            }
7939            if (ps.signatures.mSignatures != null
7940                    && ps.signatures.mSignatures.length != 0
7941                    && signingKs != null) {
7942                // Optimization: reuse the existing cached certificates
7943                // if the package appears to be unchanged.
7944                pkg.mSignatures = ps.signatures.mSignatures;
7945                pkg.mSigningKeys = signingKs;
7946                return;
7947            }
7948
7949            Slog.w(TAG, "PackageSetting for " + ps.name
7950                    + " is missing signatures.  Collecting certs again to recover them.");
7951        } else {
7952            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7953        }
7954
7955        try {
7956            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7957            PackageParser.collectCertificates(pkg, policyFlags);
7958        } catch (PackageParserException e) {
7959            throw PackageManagerException.from(e);
7960        } finally {
7961            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7962        }
7963    }
7964
7965    /**
7966     *  Traces a package scan.
7967     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7968     */
7969    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7970            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7971        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7972        try {
7973            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7974        } finally {
7975            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7976        }
7977    }
7978
7979    /**
7980     *  Scans a package and returns the newly parsed package.
7981     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7982     */
7983    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7984            long currentTime, UserHandle user) throws PackageManagerException {
7985        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7986        PackageParser pp = new PackageParser();
7987        pp.setSeparateProcesses(mSeparateProcesses);
7988        pp.setOnlyCoreApps(mOnlyCore);
7989        pp.setDisplayMetrics(mMetrics);
7990        pp.setCallback(mPackageParserCallback);
7991
7992        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7993            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7994        }
7995
7996        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7997        final PackageParser.Package pkg;
7998        try {
7999            pkg = pp.parsePackage(scanFile, parseFlags);
8000        } catch (PackageParserException e) {
8001            throw PackageManagerException.from(e);
8002        } finally {
8003            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8004        }
8005
8006        // Static shared libraries have synthetic package names
8007        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8008            renameStaticSharedLibraryPackage(pkg);
8009        }
8010
8011        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8012    }
8013
8014    /**
8015     *  Scans a package and returns the newly parsed package.
8016     *  @throws PackageManagerException on a parse error.
8017     */
8018    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8019            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8020            throws PackageManagerException {
8021        // If the package has children and this is the first dive in the function
8022        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8023        // packages (parent and children) would be successfully scanned before the
8024        // actual scan since scanning mutates internal state and we want to atomically
8025        // install the package and its children.
8026        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8027            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8028                scanFlags |= SCAN_CHECK_ONLY;
8029            }
8030        } else {
8031            scanFlags &= ~SCAN_CHECK_ONLY;
8032        }
8033
8034        // Scan the parent
8035        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8036                scanFlags, currentTime, user);
8037
8038        // Scan the children
8039        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8040        for (int i = 0; i < childCount; i++) {
8041            PackageParser.Package childPackage = pkg.childPackages.get(i);
8042            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8043                    currentTime, user);
8044        }
8045
8046
8047        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8048            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8049        }
8050
8051        return scannedPkg;
8052    }
8053
8054    /**
8055     *  Scans a package and returns the newly parsed package.
8056     *  @throws PackageManagerException on a parse error.
8057     */
8058    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8059            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8060            throws PackageManagerException {
8061        PackageSetting ps = null;
8062        PackageSetting updatedPkg;
8063        // reader
8064        synchronized (mPackages) {
8065            // Look to see if we already know about this package.
8066            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8067            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8068                // This package has been renamed to its original name.  Let's
8069                // use that.
8070                ps = mSettings.getPackageLPr(oldName);
8071            }
8072            // If there was no original package, see one for the real package name.
8073            if (ps == null) {
8074                ps = mSettings.getPackageLPr(pkg.packageName);
8075            }
8076            // Check to see if this package could be hiding/updating a system
8077            // package.  Must look for it either under the original or real
8078            // package name depending on our state.
8079            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8080            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8081
8082            // If this is a package we don't know about on the system partition, we
8083            // may need to remove disabled child packages on the system partition
8084            // or may need to not add child packages if the parent apk is updated
8085            // on the data partition and no longer defines this child package.
8086            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8087                // If this is a parent package for an updated system app and this system
8088                // app got an OTA update which no longer defines some of the child packages
8089                // we have to prune them from the disabled system packages.
8090                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8091                if (disabledPs != null) {
8092                    final int scannedChildCount = (pkg.childPackages != null)
8093                            ? pkg.childPackages.size() : 0;
8094                    final int disabledChildCount = disabledPs.childPackageNames != null
8095                            ? disabledPs.childPackageNames.size() : 0;
8096                    for (int i = 0; i < disabledChildCount; i++) {
8097                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8098                        boolean disabledPackageAvailable = false;
8099                        for (int j = 0; j < scannedChildCount; j++) {
8100                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8101                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8102                                disabledPackageAvailable = true;
8103                                break;
8104                            }
8105                         }
8106                         if (!disabledPackageAvailable) {
8107                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8108                         }
8109                    }
8110                }
8111            }
8112        }
8113
8114        boolean updatedPkgBetter = false;
8115        // First check if this is a system package that may involve an update
8116        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8117            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8118            // it needs to drop FLAG_PRIVILEGED.
8119            if (locationIsPrivileged(scanFile)) {
8120                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8121            } else {
8122                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8123            }
8124
8125            if (ps != null && !ps.codePath.equals(scanFile)) {
8126                // The path has changed from what was last scanned...  check the
8127                // version of the new path against what we have stored to determine
8128                // what to do.
8129                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8130                if (pkg.mVersionCode <= ps.versionCode) {
8131                    // The system package has been updated and the code path does not match
8132                    // Ignore entry. Skip it.
8133                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8134                            + " ignored: updated version " + ps.versionCode
8135                            + " better than this " + pkg.mVersionCode);
8136                    if (!updatedPkg.codePath.equals(scanFile)) {
8137                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8138                                + ps.name + " changing from " + updatedPkg.codePathString
8139                                + " to " + scanFile);
8140                        updatedPkg.codePath = scanFile;
8141                        updatedPkg.codePathString = scanFile.toString();
8142                        updatedPkg.resourcePath = scanFile;
8143                        updatedPkg.resourcePathString = scanFile.toString();
8144                    }
8145                    updatedPkg.pkg = pkg;
8146                    updatedPkg.versionCode = pkg.mVersionCode;
8147
8148                    // Update the disabled system child packages to point to the package too.
8149                    final int childCount = updatedPkg.childPackageNames != null
8150                            ? updatedPkg.childPackageNames.size() : 0;
8151                    for (int i = 0; i < childCount; i++) {
8152                        String childPackageName = updatedPkg.childPackageNames.get(i);
8153                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8154                                childPackageName);
8155                        if (updatedChildPkg != null) {
8156                            updatedChildPkg.pkg = pkg;
8157                            updatedChildPkg.versionCode = pkg.mVersionCode;
8158                        }
8159                    }
8160
8161                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8162                            + scanFile + " ignored: updated version " + ps.versionCode
8163                            + " better than this " + pkg.mVersionCode);
8164                } else {
8165                    // The current app on the system partition is better than
8166                    // what we have updated to on the data partition; switch
8167                    // back to the system partition version.
8168                    // At this point, its safely assumed that package installation for
8169                    // apps in system partition will go through. If not there won't be a working
8170                    // version of the app
8171                    // writer
8172                    synchronized (mPackages) {
8173                        // Just remove the loaded entries from package lists.
8174                        mPackages.remove(ps.name);
8175                    }
8176
8177                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8178                            + " reverting from " + ps.codePathString
8179                            + ": new version " + pkg.mVersionCode
8180                            + " better than installed " + ps.versionCode);
8181
8182                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8183                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8184                    synchronized (mInstallLock) {
8185                        args.cleanUpResourcesLI();
8186                    }
8187                    synchronized (mPackages) {
8188                        mSettings.enableSystemPackageLPw(ps.name);
8189                    }
8190                    updatedPkgBetter = true;
8191                }
8192            }
8193        }
8194
8195        if (updatedPkg != null) {
8196            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8197            // initially
8198            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8199
8200            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8201            // flag set initially
8202            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8203                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8204            }
8205        }
8206
8207        // Verify certificates against what was last scanned
8208        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8209
8210        /*
8211         * A new system app appeared, but we already had a non-system one of the
8212         * same name installed earlier.
8213         */
8214        boolean shouldHideSystemApp = false;
8215        if (updatedPkg == null && ps != null
8216                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8217            /*
8218             * Check to make sure the signatures match first. If they don't,
8219             * wipe the installed application and its data.
8220             */
8221            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8222                    != PackageManager.SIGNATURE_MATCH) {
8223                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8224                        + " signatures don't match existing userdata copy; removing");
8225                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8226                        "scanPackageInternalLI")) {
8227                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8228                }
8229                ps = null;
8230            } else {
8231                /*
8232                 * If the newly-added system app is an older version than the
8233                 * already installed version, hide it. It will be scanned later
8234                 * and re-added like an update.
8235                 */
8236                if (pkg.mVersionCode <= ps.versionCode) {
8237                    shouldHideSystemApp = true;
8238                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8239                            + " but new version " + pkg.mVersionCode + " better than installed "
8240                            + ps.versionCode + "; hiding system");
8241                } else {
8242                    /*
8243                     * The newly found system app is a newer version that the
8244                     * one previously installed. Simply remove the
8245                     * already-installed application and replace it with our own
8246                     * while keeping the application data.
8247                     */
8248                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8249                            + " reverting from " + ps.codePathString + ": new version "
8250                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8251                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8252                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8253                    synchronized (mInstallLock) {
8254                        args.cleanUpResourcesLI();
8255                    }
8256                }
8257            }
8258        }
8259
8260        // The apk is forward locked (not public) if its code and resources
8261        // are kept in different files. (except for app in either system or
8262        // vendor path).
8263        // TODO grab this value from PackageSettings
8264        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8265            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8266                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8267            }
8268        }
8269
8270        // TODO: extend to support forward-locked splits
8271        String resourcePath = null;
8272        String baseResourcePath = null;
8273        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8274            if (ps != null && ps.resourcePathString != null) {
8275                resourcePath = ps.resourcePathString;
8276                baseResourcePath = ps.resourcePathString;
8277            } else {
8278                // Should not happen at all. Just log an error.
8279                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8280            }
8281        } else {
8282            resourcePath = pkg.codePath;
8283            baseResourcePath = pkg.baseCodePath;
8284        }
8285
8286        // Set application objects path explicitly.
8287        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8288        pkg.setApplicationInfoCodePath(pkg.codePath);
8289        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8290        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8291        pkg.setApplicationInfoResourcePath(resourcePath);
8292        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8293        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8294
8295        final int userId = ((user == null) ? 0 : user.getIdentifier());
8296        if (ps != null && ps.getInstantApp(userId)) {
8297            scanFlags |= SCAN_AS_INSTANT_APP;
8298        }
8299
8300        // Note that we invoke the following method only if we are about to unpack an application
8301        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8302                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8303
8304        /*
8305         * If the system app should be overridden by a previously installed
8306         * data, hide the system app now and let the /data/app scan pick it up
8307         * again.
8308         */
8309        if (shouldHideSystemApp) {
8310            synchronized (mPackages) {
8311                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8312            }
8313        }
8314
8315        return scannedPkg;
8316    }
8317
8318    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8319        // Derive the new package synthetic package name
8320        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8321                + pkg.staticSharedLibVersion);
8322    }
8323
8324    private static String fixProcessName(String defProcessName,
8325            String processName) {
8326        if (processName == null) {
8327            return defProcessName;
8328        }
8329        return processName;
8330    }
8331
8332    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8333            throws PackageManagerException {
8334        if (pkgSetting.signatures.mSignatures != null) {
8335            // Already existing package. Make sure signatures match
8336            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8337                    == PackageManager.SIGNATURE_MATCH;
8338            if (!match) {
8339                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8340                        == PackageManager.SIGNATURE_MATCH;
8341            }
8342            if (!match) {
8343                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8344                        == PackageManager.SIGNATURE_MATCH;
8345            }
8346            if (!match) {
8347                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8348                        + pkg.packageName + " signatures do not match the "
8349                        + "previously installed version; ignoring!");
8350            }
8351        }
8352
8353        // Check for shared user signatures
8354        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8355            // Already existing package. Make sure signatures match
8356            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8357                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8358            if (!match) {
8359                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8360                        == PackageManager.SIGNATURE_MATCH;
8361            }
8362            if (!match) {
8363                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8364                        == PackageManager.SIGNATURE_MATCH;
8365            }
8366            if (!match) {
8367                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8368                        "Package " + pkg.packageName
8369                        + " has no signatures that match those in shared user "
8370                        + pkgSetting.sharedUser.name + "; ignoring!");
8371            }
8372        }
8373    }
8374
8375    /**
8376     * Enforces that only the system UID or root's UID can call a method exposed
8377     * via Binder.
8378     *
8379     * @param message used as message if SecurityException is thrown
8380     * @throws SecurityException if the caller is not system or root
8381     */
8382    private static final void enforceSystemOrRoot(String message) {
8383        final int uid = Binder.getCallingUid();
8384        if (uid != Process.SYSTEM_UID && uid != 0) {
8385            throw new SecurityException(message);
8386        }
8387    }
8388
8389    @Override
8390    public void performFstrimIfNeeded() {
8391        enforceSystemOrRoot("Only the system can request fstrim");
8392
8393        // Before everything else, see whether we need to fstrim.
8394        try {
8395            IStorageManager sm = PackageHelper.getStorageManager();
8396            if (sm != null) {
8397                boolean doTrim = false;
8398                final long interval = android.provider.Settings.Global.getLong(
8399                        mContext.getContentResolver(),
8400                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8401                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8402                if (interval > 0) {
8403                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8404                    if (timeSinceLast > interval) {
8405                        doTrim = true;
8406                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8407                                + "; running immediately");
8408                    }
8409                }
8410                if (doTrim) {
8411                    final boolean dexOptDialogShown;
8412                    synchronized (mPackages) {
8413                        dexOptDialogShown = mDexOptDialogShown;
8414                    }
8415                    if (!isFirstBoot() && dexOptDialogShown) {
8416                        try {
8417                            ActivityManager.getService().showBootMessage(
8418                                    mContext.getResources().getString(
8419                                            R.string.android_upgrading_fstrim), true);
8420                        } catch (RemoteException e) {
8421                        }
8422                    }
8423                    sm.runMaintenance();
8424                }
8425            } else {
8426                Slog.e(TAG, "storageManager service unavailable!");
8427            }
8428        } catch (RemoteException e) {
8429            // Can't happen; StorageManagerService is local
8430        }
8431    }
8432
8433    @Override
8434    public void updatePackagesIfNeeded() {
8435        enforceSystemOrRoot("Only the system can request package update");
8436
8437        // We need to re-extract after an OTA.
8438        boolean causeUpgrade = isUpgrade();
8439
8440        // First boot or factory reset.
8441        // Note: we also handle devices that are upgrading to N right now as if it is their
8442        //       first boot, as they do not have profile data.
8443        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8444
8445        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8446        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8447
8448        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8449            return;
8450        }
8451
8452        List<PackageParser.Package> pkgs;
8453        synchronized (mPackages) {
8454            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8455        }
8456
8457        final long startTime = System.nanoTime();
8458        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8459                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8460
8461        final int elapsedTimeSeconds =
8462                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8463
8464        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8465        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8466        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8467        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8468        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8469    }
8470
8471    /**
8472     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8473     * containing statistics about the invocation. The array consists of three elements,
8474     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8475     * and {@code numberOfPackagesFailed}.
8476     */
8477    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8478            String compilerFilter) {
8479
8480        int numberOfPackagesVisited = 0;
8481        int numberOfPackagesOptimized = 0;
8482        int numberOfPackagesSkipped = 0;
8483        int numberOfPackagesFailed = 0;
8484        final int numberOfPackagesToDexopt = pkgs.size();
8485
8486        for (PackageParser.Package pkg : pkgs) {
8487            numberOfPackagesVisited++;
8488
8489            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8490                if (DEBUG_DEXOPT) {
8491                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8492                }
8493                numberOfPackagesSkipped++;
8494                continue;
8495            }
8496
8497            if (DEBUG_DEXOPT) {
8498                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8499                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8500            }
8501
8502            if (showDialog) {
8503                try {
8504                    ActivityManager.getService().showBootMessage(
8505                            mContext.getResources().getString(R.string.android_upgrading_apk,
8506                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8507                } catch (RemoteException e) {
8508                }
8509                synchronized (mPackages) {
8510                    mDexOptDialogShown = true;
8511                }
8512            }
8513
8514            // If the OTA updates a system app which was previously preopted to a non-preopted state
8515            // the app might end up being verified at runtime. That's because by default the apps
8516            // are verify-profile but for preopted apps there's no profile.
8517            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8518            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8519            // filter (by default interpret-only).
8520            // Note that at this stage unused apps are already filtered.
8521            if (isSystemApp(pkg) &&
8522                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8523                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8524                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8525            }
8526
8527            // checkProfiles is false to avoid merging profiles during boot which
8528            // might interfere with background compilation (b/28612421).
8529            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8530            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8531            // trade-off worth doing to save boot time work.
8532            int dexOptStatus = performDexOptTraced(pkg.packageName,
8533                    false /* checkProfiles */,
8534                    compilerFilter,
8535                    false /* force */);
8536            switch (dexOptStatus) {
8537                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8538                    numberOfPackagesOptimized++;
8539                    break;
8540                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8541                    numberOfPackagesSkipped++;
8542                    break;
8543                case PackageDexOptimizer.DEX_OPT_FAILED:
8544                    numberOfPackagesFailed++;
8545                    break;
8546                default:
8547                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8548                    break;
8549            }
8550        }
8551
8552        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8553                numberOfPackagesFailed };
8554    }
8555
8556    @Override
8557    public void notifyPackageUse(String packageName, int reason) {
8558        synchronized (mPackages) {
8559            PackageParser.Package p = mPackages.get(packageName);
8560            if (p == null) {
8561                return;
8562            }
8563            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8564        }
8565    }
8566
8567    @Override
8568    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8569        int userId = UserHandle.getCallingUserId();
8570        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8571        if (ai == null) {
8572            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8573                + loadingPackageName + ", user=" + userId);
8574            return;
8575        }
8576        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8577    }
8578
8579    // TODO: this is not used nor needed. Delete it.
8580    @Override
8581    public boolean performDexOptIfNeeded(String packageName) {
8582        int dexOptStatus = performDexOptTraced(packageName,
8583                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8584        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8585    }
8586
8587    @Override
8588    public boolean performDexOpt(String packageName,
8589            boolean checkProfiles, int compileReason, boolean force) {
8590        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8591                getCompilerFilterForReason(compileReason), force);
8592        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8593    }
8594
8595    @Override
8596    public boolean performDexOptMode(String packageName,
8597            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8598        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8599                targetCompilerFilter, force);
8600        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8601    }
8602
8603    private int performDexOptTraced(String packageName,
8604                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8605        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8606        try {
8607            return performDexOptInternal(packageName, checkProfiles,
8608                    targetCompilerFilter, force);
8609        } finally {
8610            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8611        }
8612    }
8613
8614    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8615    // if the package can now be considered up to date for the given filter.
8616    private int performDexOptInternal(String packageName,
8617                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8618        PackageParser.Package p;
8619        synchronized (mPackages) {
8620            p = mPackages.get(packageName);
8621            if (p == null) {
8622                // Package could not be found. Report failure.
8623                return PackageDexOptimizer.DEX_OPT_FAILED;
8624            }
8625            mPackageUsage.maybeWriteAsync(mPackages);
8626            mCompilerStats.maybeWriteAsync();
8627        }
8628        long callingId = Binder.clearCallingIdentity();
8629        try {
8630            synchronized (mInstallLock) {
8631                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8632                        targetCompilerFilter, force);
8633            }
8634        } finally {
8635            Binder.restoreCallingIdentity(callingId);
8636        }
8637    }
8638
8639    public ArraySet<String> getOptimizablePackages() {
8640        ArraySet<String> pkgs = new ArraySet<String>();
8641        synchronized (mPackages) {
8642            for (PackageParser.Package p : mPackages.values()) {
8643                if (PackageDexOptimizer.canOptimizePackage(p)) {
8644                    pkgs.add(p.packageName);
8645                }
8646            }
8647        }
8648        return pkgs;
8649    }
8650
8651    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8652            boolean checkProfiles, String targetCompilerFilter,
8653            boolean force) {
8654        // Select the dex optimizer based on the force parameter.
8655        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8656        //       allocate an object here.
8657        PackageDexOptimizer pdo = force
8658                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8659                : mPackageDexOptimizer;
8660
8661        // Dexopt all dependencies first. Note: we ignore the return value and march on
8662        // on errors.
8663        // Note that we are going to call performDexOpt on those libraries as many times as
8664        // they are referenced in packages. When we do a batch of performDexOpt (for example
8665        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8666        // and the first package that uses the library will dexopt it. The
8667        // others will see that the compiled code for the library is up to date.
8668        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8669        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8670        if (!deps.isEmpty()) {
8671            for (PackageParser.Package depPackage : deps) {
8672                // TODO: Analyze and investigate if we (should) profile libraries.
8673                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8674                        false /* checkProfiles */,
8675                        targetCompilerFilter,
8676                        getOrCreateCompilerPackageStats(depPackage),
8677                        true /* isUsedByOtherApps */);
8678            }
8679        }
8680        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8681                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8682                mDexManager.isUsedByOtherApps(p.packageName));
8683    }
8684
8685    // Performs dexopt on the used secondary dex files belonging to the given package.
8686    // Returns true if all dex files were process successfully (which could mean either dexopt or
8687    // skip). Returns false if any of the files caused errors.
8688    @Override
8689    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8690            boolean force) {
8691        mDexManager.reconcileSecondaryDexFiles(packageName);
8692        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8693    }
8694
8695    public boolean performDexOptSecondary(String packageName, int compileReason,
8696            boolean force) {
8697        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8698    }
8699
8700    /**
8701     * Reconcile the information we have about the secondary dex files belonging to
8702     * {@code packagName} and the actual dex files. For all dex files that were
8703     * deleted, update the internal records and delete the generated oat files.
8704     */
8705    @Override
8706    public void reconcileSecondaryDexFiles(String packageName) {
8707        mDexManager.reconcileSecondaryDexFiles(packageName);
8708    }
8709
8710    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8711    // a reference there.
8712    /*package*/ DexManager getDexManager() {
8713        return mDexManager;
8714    }
8715
8716    /**
8717     * Execute the background dexopt job immediately.
8718     */
8719    @Override
8720    public boolean runBackgroundDexoptJob() {
8721        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8722    }
8723
8724    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8725        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8726                || p.usesStaticLibraries != null) {
8727            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8728            Set<String> collectedNames = new HashSet<>();
8729            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8730
8731            retValue.remove(p);
8732
8733            return retValue;
8734        } else {
8735            return Collections.emptyList();
8736        }
8737    }
8738
8739    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8740            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8741        if (!collectedNames.contains(p.packageName)) {
8742            collectedNames.add(p.packageName);
8743            collected.add(p);
8744
8745            if (p.usesLibraries != null) {
8746                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8747                        null, collected, collectedNames);
8748            }
8749            if (p.usesOptionalLibraries != null) {
8750                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8751                        null, collected, collectedNames);
8752            }
8753            if (p.usesStaticLibraries != null) {
8754                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8755                        p.usesStaticLibrariesVersions, collected, collectedNames);
8756            }
8757        }
8758    }
8759
8760    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8761            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8762        final int libNameCount = libs.size();
8763        for (int i = 0; i < libNameCount; i++) {
8764            String libName = libs.get(i);
8765            int version = (versions != null && versions.length == libNameCount)
8766                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8767            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8768            if (libPkg != null) {
8769                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8770            }
8771        }
8772    }
8773
8774    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8775        synchronized (mPackages) {
8776            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8777            if (libEntry != null) {
8778                return mPackages.get(libEntry.apk);
8779            }
8780            return null;
8781        }
8782    }
8783
8784    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8785        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8786        if (versionedLib == null) {
8787            return null;
8788        }
8789        return versionedLib.get(version);
8790    }
8791
8792    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8793        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8794                pkg.staticSharedLibName);
8795        if (versionedLib == null) {
8796            return null;
8797        }
8798        int previousLibVersion = -1;
8799        final int versionCount = versionedLib.size();
8800        for (int i = 0; i < versionCount; i++) {
8801            final int libVersion = versionedLib.keyAt(i);
8802            if (libVersion < pkg.staticSharedLibVersion) {
8803                previousLibVersion = Math.max(previousLibVersion, libVersion);
8804            }
8805        }
8806        if (previousLibVersion >= 0) {
8807            return versionedLib.get(previousLibVersion);
8808        }
8809        return null;
8810    }
8811
8812    public void shutdown() {
8813        mPackageUsage.writeNow(mPackages);
8814        mCompilerStats.writeNow();
8815    }
8816
8817    @Override
8818    public void dumpProfiles(String packageName) {
8819        PackageParser.Package pkg;
8820        synchronized (mPackages) {
8821            pkg = mPackages.get(packageName);
8822            if (pkg == null) {
8823                throw new IllegalArgumentException("Unknown package: " + packageName);
8824            }
8825        }
8826        /* Only the shell, root, or the app user should be able to dump profiles. */
8827        int callingUid = Binder.getCallingUid();
8828        if (callingUid != Process.SHELL_UID &&
8829            callingUid != Process.ROOT_UID &&
8830            callingUid != pkg.applicationInfo.uid) {
8831            throw new SecurityException("dumpProfiles");
8832        }
8833
8834        synchronized (mInstallLock) {
8835            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8836            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8837            try {
8838                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8839                String codePaths = TextUtils.join(";", allCodePaths);
8840                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8841            } catch (InstallerException e) {
8842                Slog.w(TAG, "Failed to dump profiles", e);
8843            }
8844            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8845        }
8846    }
8847
8848    @Override
8849    public void forceDexOpt(String packageName) {
8850        enforceSystemOrRoot("forceDexOpt");
8851
8852        PackageParser.Package pkg;
8853        synchronized (mPackages) {
8854            pkg = mPackages.get(packageName);
8855            if (pkg == null) {
8856                throw new IllegalArgumentException("Unknown package: " + packageName);
8857            }
8858        }
8859
8860        synchronized (mInstallLock) {
8861            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8862
8863            // Whoever is calling forceDexOpt wants a fully compiled package.
8864            // Don't use profiles since that may cause compilation to be skipped.
8865            final int res = performDexOptInternalWithDependenciesLI(pkg,
8866                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8867                    true /* force */);
8868
8869            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8870            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8871                throw new IllegalStateException("Failed to dexopt: " + res);
8872            }
8873        }
8874    }
8875
8876    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8877        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8878            Slog.w(TAG, "Unable to update from " + oldPkg.name
8879                    + " to " + newPkg.packageName
8880                    + ": old package not in system partition");
8881            return false;
8882        } else if (mPackages.get(oldPkg.name) != null) {
8883            Slog.w(TAG, "Unable to update from " + oldPkg.name
8884                    + " to " + newPkg.packageName
8885                    + ": old package still exists");
8886            return false;
8887        }
8888        return true;
8889    }
8890
8891    void removeCodePathLI(File codePath) {
8892        if (codePath.isDirectory()) {
8893            try {
8894                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8895            } catch (InstallerException e) {
8896                Slog.w(TAG, "Failed to remove code path", e);
8897            }
8898        } else {
8899            codePath.delete();
8900        }
8901    }
8902
8903    private int[] resolveUserIds(int userId) {
8904        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8905    }
8906
8907    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8908        if (pkg == null) {
8909            Slog.wtf(TAG, "Package was null!", new Throwable());
8910            return;
8911        }
8912        clearAppDataLeafLIF(pkg, userId, flags);
8913        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8914        for (int i = 0; i < childCount; i++) {
8915            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8916        }
8917    }
8918
8919    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8920        final PackageSetting ps;
8921        synchronized (mPackages) {
8922            ps = mSettings.mPackages.get(pkg.packageName);
8923        }
8924        for (int realUserId : resolveUserIds(userId)) {
8925            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8926            try {
8927                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8928                        ceDataInode);
8929            } catch (InstallerException e) {
8930                Slog.w(TAG, String.valueOf(e));
8931            }
8932        }
8933    }
8934
8935    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8936        if (pkg == null) {
8937            Slog.wtf(TAG, "Package was null!", new Throwable());
8938            return;
8939        }
8940        destroyAppDataLeafLIF(pkg, userId, flags);
8941        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8942        for (int i = 0; i < childCount; i++) {
8943            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8944        }
8945    }
8946
8947    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8948        final PackageSetting ps;
8949        synchronized (mPackages) {
8950            ps = mSettings.mPackages.get(pkg.packageName);
8951        }
8952        for (int realUserId : resolveUserIds(userId)) {
8953            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8954            try {
8955                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8956                        ceDataInode);
8957            } catch (InstallerException e) {
8958                Slog.w(TAG, String.valueOf(e));
8959            }
8960            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8961        }
8962    }
8963
8964    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8965        if (pkg == null) {
8966            Slog.wtf(TAG, "Package was null!", new Throwable());
8967            return;
8968        }
8969        destroyAppProfilesLeafLIF(pkg);
8970        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8971        for (int i = 0; i < childCount; i++) {
8972            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8973        }
8974    }
8975
8976    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8977        try {
8978            mInstaller.destroyAppProfiles(pkg.packageName);
8979        } catch (InstallerException e) {
8980            Slog.w(TAG, String.valueOf(e));
8981        }
8982    }
8983
8984    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8985        if (pkg == null) {
8986            Slog.wtf(TAG, "Package was null!", new Throwable());
8987            return;
8988        }
8989        clearAppProfilesLeafLIF(pkg);
8990        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8991        for (int i = 0; i < childCount; i++) {
8992            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8993        }
8994    }
8995
8996    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8997        try {
8998            mInstaller.clearAppProfiles(pkg.packageName);
8999        } catch (InstallerException e) {
9000            Slog.w(TAG, String.valueOf(e));
9001        }
9002    }
9003
9004    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9005            long lastUpdateTime) {
9006        // Set parent install/update time
9007        PackageSetting ps = (PackageSetting) pkg.mExtras;
9008        if (ps != null) {
9009            ps.firstInstallTime = firstInstallTime;
9010            ps.lastUpdateTime = lastUpdateTime;
9011        }
9012        // Set children install/update time
9013        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9014        for (int i = 0; i < childCount; i++) {
9015            PackageParser.Package childPkg = pkg.childPackages.get(i);
9016            ps = (PackageSetting) childPkg.mExtras;
9017            if (ps != null) {
9018                ps.firstInstallTime = firstInstallTime;
9019                ps.lastUpdateTime = lastUpdateTime;
9020            }
9021        }
9022    }
9023
9024    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9025            PackageParser.Package changingLib) {
9026        if (file.path != null) {
9027            usesLibraryFiles.add(file.path);
9028            return;
9029        }
9030        PackageParser.Package p = mPackages.get(file.apk);
9031        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9032            // If we are doing this while in the middle of updating a library apk,
9033            // then we need to make sure to use that new apk for determining the
9034            // dependencies here.  (We haven't yet finished committing the new apk
9035            // to the package manager state.)
9036            if (p == null || p.packageName.equals(changingLib.packageName)) {
9037                p = changingLib;
9038            }
9039        }
9040        if (p != null) {
9041            usesLibraryFiles.addAll(p.getAllCodePaths());
9042        }
9043    }
9044
9045    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9046            PackageParser.Package changingLib) throws PackageManagerException {
9047        if (pkg == null) {
9048            return;
9049        }
9050        ArraySet<String> usesLibraryFiles = null;
9051        if (pkg.usesLibraries != null) {
9052            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9053                    null, null, pkg.packageName, changingLib, true, null);
9054        }
9055        if (pkg.usesStaticLibraries != null) {
9056            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9057                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9058                    pkg.packageName, changingLib, true, usesLibraryFiles);
9059        }
9060        if (pkg.usesOptionalLibraries != null) {
9061            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9062                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9063        }
9064        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9065            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9066        } else {
9067            pkg.usesLibraryFiles = null;
9068        }
9069    }
9070
9071    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9072            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9073            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9074            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9075            throws PackageManagerException {
9076        final int libCount = requestedLibraries.size();
9077        for (int i = 0; i < libCount; i++) {
9078            final String libName = requestedLibraries.get(i);
9079            final int libVersion = requiredVersions != null ? requiredVersions[i]
9080                    : SharedLibraryInfo.VERSION_UNDEFINED;
9081            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9082            if (libEntry == null) {
9083                if (required) {
9084                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9085                            "Package " + packageName + " requires unavailable shared library "
9086                                    + libName + "; failing!");
9087                } else {
9088                    Slog.w(TAG, "Package " + packageName
9089                            + " desires unavailable shared library "
9090                            + libName + "; ignoring!");
9091                }
9092            } else {
9093                if (requiredVersions != null && requiredCertDigests != null) {
9094                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9095                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9096                            "Package " + packageName + " requires unavailable static shared"
9097                                    + " library " + libName + " version "
9098                                    + libEntry.info.getVersion() + "; failing!");
9099                    }
9100
9101                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9102                    if (libPkg == null) {
9103                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9104                                "Package " + packageName + " requires unavailable static shared"
9105                                        + " library; failing!");
9106                    }
9107
9108                    String expectedCertDigest = requiredCertDigests[i];
9109                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9110                                libPkg.mSignatures[0]);
9111                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9112                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9113                                "Package " + packageName + " requires differently signed" +
9114                                        " static shared library; failing!");
9115                    }
9116                }
9117
9118                if (outUsedLibraries == null) {
9119                    outUsedLibraries = new ArraySet<>();
9120                }
9121                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9122            }
9123        }
9124        return outUsedLibraries;
9125    }
9126
9127    private static boolean hasString(List<String> list, List<String> which) {
9128        if (list == null) {
9129            return false;
9130        }
9131        for (int i=list.size()-1; i>=0; i--) {
9132            for (int j=which.size()-1; j>=0; j--) {
9133                if (which.get(j).equals(list.get(i))) {
9134                    return true;
9135                }
9136            }
9137        }
9138        return false;
9139    }
9140
9141    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9142            PackageParser.Package changingPkg) {
9143        ArrayList<PackageParser.Package> res = null;
9144        for (PackageParser.Package pkg : mPackages.values()) {
9145            if (changingPkg != null
9146                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9147                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9148                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9149                            changingPkg.staticSharedLibName)) {
9150                return null;
9151            }
9152            if (res == null) {
9153                res = new ArrayList<>();
9154            }
9155            res.add(pkg);
9156            try {
9157                updateSharedLibrariesLPr(pkg, changingPkg);
9158            } catch (PackageManagerException e) {
9159                // If a system app update or an app and a required lib missing we
9160                // delete the package and for updated system apps keep the data as
9161                // it is better for the user to reinstall than to be in an limbo
9162                // state. Also libs disappearing under an app should never happen
9163                // - just in case.
9164                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9165                    final int flags = pkg.isUpdatedSystemApp()
9166                            ? PackageManager.DELETE_KEEP_DATA : 0;
9167                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9168                            flags , null, true, null);
9169                }
9170                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9171            }
9172        }
9173        return res;
9174    }
9175
9176    /**
9177     * Derive the value of the {@code cpuAbiOverride} based on the provided
9178     * value and an optional stored value from the package settings.
9179     */
9180    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9181        String cpuAbiOverride = null;
9182
9183        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9184            cpuAbiOverride = null;
9185        } else if (abiOverride != null) {
9186            cpuAbiOverride = abiOverride;
9187        } else if (settings != null) {
9188            cpuAbiOverride = settings.cpuAbiOverrideString;
9189        }
9190
9191        return cpuAbiOverride;
9192    }
9193
9194    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9195            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9196                    throws PackageManagerException {
9197        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9198        // If the package has children and this is the first dive in the function
9199        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9200        // whether all packages (parent and children) would be successfully scanned
9201        // before the actual scan since scanning mutates internal state and we want
9202        // to atomically install the package and its children.
9203        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9204            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9205                scanFlags |= SCAN_CHECK_ONLY;
9206            }
9207        } else {
9208            scanFlags &= ~SCAN_CHECK_ONLY;
9209        }
9210
9211        final PackageParser.Package scannedPkg;
9212        try {
9213            // Scan the parent
9214            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9215            // Scan the children
9216            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9217            for (int i = 0; i < childCount; i++) {
9218                PackageParser.Package childPkg = pkg.childPackages.get(i);
9219                scanPackageLI(childPkg, policyFlags,
9220                        scanFlags, currentTime, user);
9221            }
9222        } finally {
9223            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9224        }
9225
9226        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9227            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9228        }
9229
9230        return scannedPkg;
9231    }
9232
9233    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9234            int scanFlags, long currentTime, @Nullable UserHandle user)
9235                    throws PackageManagerException {
9236        boolean success = false;
9237        try {
9238            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9239                    currentTime, user);
9240            success = true;
9241            return res;
9242        } finally {
9243            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9244                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9245                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9246                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9247                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9248            }
9249        }
9250    }
9251
9252    /**
9253     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9254     */
9255    private static boolean apkHasCode(String fileName) {
9256        StrictJarFile jarFile = null;
9257        try {
9258            jarFile = new StrictJarFile(fileName,
9259                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9260            return jarFile.findEntry("classes.dex") != null;
9261        } catch (IOException ignore) {
9262        } finally {
9263            try {
9264                if (jarFile != null) {
9265                    jarFile.close();
9266                }
9267            } catch (IOException ignore) {}
9268        }
9269        return false;
9270    }
9271
9272    /**
9273     * Enforces code policy for the package. This ensures that if an APK has
9274     * declared hasCode="true" in its manifest that the APK actually contains
9275     * code.
9276     *
9277     * @throws PackageManagerException If bytecode could not be found when it should exist
9278     */
9279    private static void assertCodePolicy(PackageParser.Package pkg)
9280            throws PackageManagerException {
9281        final boolean shouldHaveCode =
9282                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9283        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9284            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9285                    "Package " + pkg.baseCodePath + " code is missing");
9286        }
9287
9288        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9289            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9290                final boolean splitShouldHaveCode =
9291                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9292                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9293                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9294                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9295                }
9296            }
9297        }
9298    }
9299
9300    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9301            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9302                    throws PackageManagerException {
9303        if (DEBUG_PACKAGE_SCANNING) {
9304            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9305                Log.d(TAG, "Scanning package " + pkg.packageName);
9306        }
9307
9308        applyPolicy(pkg, policyFlags);
9309
9310        assertPackageIsValid(pkg, policyFlags, scanFlags);
9311
9312        // Initialize package source and resource directories
9313        final File scanFile = new File(pkg.codePath);
9314        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9315        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9316
9317        SharedUserSetting suid = null;
9318        PackageSetting pkgSetting = null;
9319
9320        // Getting the package setting may have a side-effect, so if we
9321        // are only checking if scan would succeed, stash a copy of the
9322        // old setting to restore at the end.
9323        PackageSetting nonMutatedPs = null;
9324
9325        // We keep references to the derived CPU Abis from settings in oder to reuse
9326        // them in the case where we're not upgrading or booting for the first time.
9327        String primaryCpuAbiFromSettings = null;
9328        String secondaryCpuAbiFromSettings = null;
9329
9330        // writer
9331        synchronized (mPackages) {
9332            if (pkg.mSharedUserId != null) {
9333                // SIDE EFFECTS; may potentially allocate a new shared user
9334                suid = mSettings.getSharedUserLPw(
9335                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9336                if (DEBUG_PACKAGE_SCANNING) {
9337                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9338                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9339                                + "): packages=" + suid.packages);
9340                }
9341            }
9342
9343            // Check if we are renaming from an original package name.
9344            PackageSetting origPackage = null;
9345            String realName = null;
9346            if (pkg.mOriginalPackages != null) {
9347                // This package may need to be renamed to a previously
9348                // installed name.  Let's check on that...
9349                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9350                if (pkg.mOriginalPackages.contains(renamed)) {
9351                    // This package had originally been installed as the
9352                    // original name, and we have already taken care of
9353                    // transitioning to the new one.  Just update the new
9354                    // one to continue using the old name.
9355                    realName = pkg.mRealPackage;
9356                    if (!pkg.packageName.equals(renamed)) {
9357                        // Callers into this function may have already taken
9358                        // care of renaming the package; only do it here if
9359                        // it is not already done.
9360                        pkg.setPackageName(renamed);
9361                    }
9362                } else {
9363                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9364                        if ((origPackage = mSettings.getPackageLPr(
9365                                pkg.mOriginalPackages.get(i))) != null) {
9366                            // We do have the package already installed under its
9367                            // original name...  should we use it?
9368                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9369                                // New package is not compatible with original.
9370                                origPackage = null;
9371                                continue;
9372                            } else if (origPackage.sharedUser != null) {
9373                                // Make sure uid is compatible between packages.
9374                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9375                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9376                                            + " to " + pkg.packageName + ": old uid "
9377                                            + origPackage.sharedUser.name
9378                                            + " differs from " + pkg.mSharedUserId);
9379                                    origPackage = null;
9380                                    continue;
9381                                }
9382                                // TODO: Add case when shared user id is added [b/28144775]
9383                            } else {
9384                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9385                                        + pkg.packageName + " to old name " + origPackage.name);
9386                            }
9387                            break;
9388                        }
9389                    }
9390                }
9391            }
9392
9393            if (mTransferedPackages.contains(pkg.packageName)) {
9394                Slog.w(TAG, "Package " + pkg.packageName
9395                        + " was transferred to another, but its .apk remains");
9396            }
9397
9398            // See comments in nonMutatedPs declaration
9399            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9400                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9401                if (foundPs != null) {
9402                    nonMutatedPs = new PackageSetting(foundPs);
9403                }
9404            }
9405
9406            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9407                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9408                if (foundPs != null) {
9409                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9410                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9411                }
9412            }
9413
9414            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9415            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9416                PackageManagerService.reportSettingsProblem(Log.WARN,
9417                        "Package " + pkg.packageName + " shared user changed from "
9418                                + (pkgSetting.sharedUser != null
9419                                        ? pkgSetting.sharedUser.name : "<nothing>")
9420                                + " to "
9421                                + (suid != null ? suid.name : "<nothing>")
9422                                + "; replacing with new");
9423                pkgSetting = null;
9424            }
9425            final PackageSetting oldPkgSetting =
9426                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9427            final PackageSetting disabledPkgSetting =
9428                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9429
9430            String[] usesStaticLibraries = null;
9431            if (pkg.usesStaticLibraries != null) {
9432                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9433                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9434            }
9435
9436            if (pkgSetting == null) {
9437                final String parentPackageName = (pkg.parentPackage != null)
9438                        ? pkg.parentPackage.packageName : null;
9439                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9440                // REMOVE SharedUserSetting from method; update in a separate call
9441                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9442                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9443                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9444                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9445                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9446                        true /*allowInstall*/, instantApp, parentPackageName,
9447                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9448                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9449                // SIDE EFFECTS; updates system state; move elsewhere
9450                if (origPackage != null) {
9451                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9452                }
9453                mSettings.addUserToSettingLPw(pkgSetting);
9454            } else {
9455                // REMOVE SharedUserSetting from method; update in a separate call.
9456                //
9457                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9458                // secondaryCpuAbi are not known at this point so we always update them
9459                // to null here, only to reset them at a later point.
9460                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9461                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9462                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9463                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9464                        UserManagerService.getInstance(), usesStaticLibraries,
9465                        pkg.usesStaticLibrariesVersions);
9466            }
9467            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9468            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9469
9470            // SIDE EFFECTS; modifies system state; move elsewhere
9471            if (pkgSetting.origPackage != null) {
9472                // If we are first transitioning from an original package,
9473                // fix up the new package's name now.  We need to do this after
9474                // looking up the package under its new name, so getPackageLP
9475                // can take care of fiddling things correctly.
9476                pkg.setPackageName(origPackage.name);
9477
9478                // File a report about this.
9479                String msg = "New package " + pkgSetting.realName
9480                        + " renamed to replace old package " + pkgSetting.name;
9481                reportSettingsProblem(Log.WARN, msg);
9482
9483                // Make a note of it.
9484                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9485                    mTransferedPackages.add(origPackage.name);
9486                }
9487
9488                // No longer need to retain this.
9489                pkgSetting.origPackage = null;
9490            }
9491
9492            // SIDE EFFECTS; modifies system state; move elsewhere
9493            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9494                // Make a note of it.
9495                mTransferedPackages.add(pkg.packageName);
9496            }
9497
9498            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9499                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9500            }
9501
9502            if ((scanFlags & SCAN_BOOTING) == 0
9503                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9504                // Check all shared libraries and map to their actual file path.
9505                // We only do this here for apps not on a system dir, because those
9506                // are the only ones that can fail an install due to this.  We
9507                // will take care of the system apps by updating all of their
9508                // library paths after the scan is done. Also during the initial
9509                // scan don't update any libs as we do this wholesale after all
9510                // apps are scanned to avoid dependency based scanning.
9511                updateSharedLibrariesLPr(pkg, null);
9512            }
9513
9514            if (mFoundPolicyFile) {
9515                SELinuxMMAC.assignSeInfoValue(pkg);
9516            }
9517            pkg.applicationInfo.uid = pkgSetting.appId;
9518            pkg.mExtras = pkgSetting;
9519
9520
9521            // Static shared libs have same package with different versions where
9522            // we internally use a synthetic package name to allow multiple versions
9523            // of the same package, therefore we need to compare signatures against
9524            // the package setting for the latest library version.
9525            PackageSetting signatureCheckPs = pkgSetting;
9526            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9527                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9528                if (libraryEntry != null) {
9529                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9530                }
9531            }
9532
9533            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9534                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9535                    // We just determined the app is signed correctly, so bring
9536                    // over the latest parsed certs.
9537                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9538                } else {
9539                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9540                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9541                                "Package " + pkg.packageName + " upgrade keys do not match the "
9542                                + "previously installed version");
9543                    } else {
9544                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9545                        String msg = "System package " + pkg.packageName
9546                                + " signature changed; retaining data.";
9547                        reportSettingsProblem(Log.WARN, msg);
9548                    }
9549                }
9550            } else {
9551                try {
9552                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9553                    verifySignaturesLP(signatureCheckPs, pkg);
9554                    // We just determined the app is signed correctly, so bring
9555                    // over the latest parsed certs.
9556                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9557                } catch (PackageManagerException e) {
9558                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9559                        throw e;
9560                    }
9561                    // The signature has changed, but this package is in the system
9562                    // image...  let's recover!
9563                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9564                    // However...  if this package is part of a shared user, but it
9565                    // doesn't match the signature of the shared user, let's fail.
9566                    // What this means is that you can't change the signatures
9567                    // associated with an overall shared user, which doesn't seem all
9568                    // that unreasonable.
9569                    if (signatureCheckPs.sharedUser != null) {
9570                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9571                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9572                            throw new PackageManagerException(
9573                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9574                                    "Signature mismatch for shared user: "
9575                                            + pkgSetting.sharedUser);
9576                        }
9577                    }
9578                    // File a report about this.
9579                    String msg = "System package " + pkg.packageName
9580                            + " signature changed; retaining data.";
9581                    reportSettingsProblem(Log.WARN, msg);
9582                }
9583            }
9584
9585            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9586                // This package wants to adopt ownership of permissions from
9587                // another package.
9588                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9589                    final String origName = pkg.mAdoptPermissions.get(i);
9590                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9591                    if (orig != null) {
9592                        if (verifyPackageUpdateLPr(orig, pkg)) {
9593                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9594                                    + pkg.packageName);
9595                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9596                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9597                        }
9598                    }
9599                }
9600            }
9601        }
9602
9603        pkg.applicationInfo.processName = fixProcessName(
9604                pkg.applicationInfo.packageName,
9605                pkg.applicationInfo.processName);
9606
9607        if (pkg != mPlatformPackage) {
9608            // Get all of our default paths setup
9609            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9610        }
9611
9612        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9613
9614        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9615            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9616                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9617                derivePackageAbi(
9618                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9619                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9620
9621                // Some system apps still use directory structure for native libraries
9622                // in which case we might end up not detecting abi solely based on apk
9623                // structure. Try to detect abi based on directory structure.
9624                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9625                        pkg.applicationInfo.primaryCpuAbi == null) {
9626                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9627                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9628                }
9629            } else {
9630                // This is not a first boot or an upgrade, don't bother deriving the
9631                // ABI during the scan. Instead, trust the value that was stored in the
9632                // package setting.
9633                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9634                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9635
9636                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9637
9638                if (DEBUG_ABI_SELECTION) {
9639                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9640                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9641                        pkg.applicationInfo.secondaryCpuAbi);
9642                }
9643            }
9644        } else {
9645            if ((scanFlags & SCAN_MOVE) != 0) {
9646                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9647                // but we already have this packages package info in the PackageSetting. We just
9648                // use that and derive the native library path based on the new codepath.
9649                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9650                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9651            }
9652
9653            // Set native library paths again. For moves, the path will be updated based on the
9654            // ABIs we've determined above. For non-moves, the path will be updated based on the
9655            // ABIs we determined during compilation, but the path will depend on the final
9656            // package path (after the rename away from the stage path).
9657            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9658        }
9659
9660        // This is a special case for the "system" package, where the ABI is
9661        // dictated by the zygote configuration (and init.rc). We should keep track
9662        // of this ABI so that we can deal with "normal" applications that run under
9663        // the same UID correctly.
9664        if (mPlatformPackage == pkg) {
9665            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9666                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9667        }
9668
9669        // If there's a mismatch between the abi-override in the package setting
9670        // and the abiOverride specified for the install. Warn about this because we
9671        // would've already compiled the app without taking the package setting into
9672        // account.
9673        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9674            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9675                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9676                        " for package " + pkg.packageName);
9677            }
9678        }
9679
9680        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9681        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9682        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9683
9684        // Copy the derived override back to the parsed package, so that we can
9685        // update the package settings accordingly.
9686        pkg.cpuAbiOverride = cpuAbiOverride;
9687
9688        if (DEBUG_ABI_SELECTION) {
9689            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9690                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9691                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9692        }
9693
9694        // Push the derived path down into PackageSettings so we know what to
9695        // clean up at uninstall time.
9696        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9697
9698        if (DEBUG_ABI_SELECTION) {
9699            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9700                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9701                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9702        }
9703
9704        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9705        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9706            // We don't do this here during boot because we can do it all
9707            // at once after scanning all existing packages.
9708            //
9709            // We also do this *before* we perform dexopt on this package, so that
9710            // we can avoid redundant dexopts, and also to make sure we've got the
9711            // code and package path correct.
9712            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9713        }
9714
9715        if (mFactoryTest && pkg.requestedPermissions.contains(
9716                android.Manifest.permission.FACTORY_TEST)) {
9717            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9718        }
9719
9720        if (isSystemApp(pkg)) {
9721            pkgSetting.isOrphaned = true;
9722        }
9723
9724        // Take care of first install / last update times.
9725        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9726        if (currentTime != 0) {
9727            if (pkgSetting.firstInstallTime == 0) {
9728                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9729            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9730                pkgSetting.lastUpdateTime = currentTime;
9731            }
9732        } else if (pkgSetting.firstInstallTime == 0) {
9733            // We need *something*.  Take time time stamp of the file.
9734            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9735        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9736            if (scanFileTime != pkgSetting.timeStamp) {
9737                // A package on the system image has changed; consider this
9738                // to be an update.
9739                pkgSetting.lastUpdateTime = scanFileTime;
9740            }
9741        }
9742        pkgSetting.setTimeStamp(scanFileTime);
9743
9744        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9745            if (nonMutatedPs != null) {
9746                synchronized (mPackages) {
9747                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9748                }
9749            }
9750        } else {
9751            final int userId = user == null ? 0 : user.getIdentifier();
9752            // Modify state for the given package setting
9753            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9754                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9755            if (pkgSetting.getInstantApp(userId)) {
9756                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9757            }
9758        }
9759        return pkg;
9760    }
9761
9762    /**
9763     * Applies policy to the parsed package based upon the given policy flags.
9764     * Ensures the package is in a good state.
9765     * <p>
9766     * Implementation detail: This method must NOT have any side effect. It would
9767     * ideally be static, but, it requires locks to read system state.
9768     */
9769    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9770        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9771            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9772            if (pkg.applicationInfo.isDirectBootAware()) {
9773                // we're direct boot aware; set for all components
9774                for (PackageParser.Service s : pkg.services) {
9775                    s.info.encryptionAware = s.info.directBootAware = true;
9776                }
9777                for (PackageParser.Provider p : pkg.providers) {
9778                    p.info.encryptionAware = p.info.directBootAware = true;
9779                }
9780                for (PackageParser.Activity a : pkg.activities) {
9781                    a.info.encryptionAware = a.info.directBootAware = true;
9782                }
9783                for (PackageParser.Activity r : pkg.receivers) {
9784                    r.info.encryptionAware = r.info.directBootAware = true;
9785                }
9786            }
9787        } else {
9788            // Only allow system apps to be flagged as core apps.
9789            pkg.coreApp = false;
9790            // clear flags not applicable to regular apps
9791            pkg.applicationInfo.privateFlags &=
9792                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9793            pkg.applicationInfo.privateFlags &=
9794                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9795        }
9796        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9797
9798        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9799            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9800        }
9801
9802        if (!isSystemApp(pkg)) {
9803            // Only system apps can use these features.
9804            pkg.mOriginalPackages = null;
9805            pkg.mRealPackage = null;
9806            pkg.mAdoptPermissions = null;
9807        }
9808    }
9809
9810    /**
9811     * Asserts the parsed package is valid according to the given policy. If the
9812     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9813     * <p>
9814     * Implementation detail: This method must NOT have any side effects. It would
9815     * ideally be static, but, it requires locks to read system state.
9816     *
9817     * @throws PackageManagerException If the package fails any of the validation checks
9818     */
9819    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9820            throws PackageManagerException {
9821        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9822            assertCodePolicy(pkg);
9823        }
9824
9825        if (pkg.applicationInfo.getCodePath() == null ||
9826                pkg.applicationInfo.getResourcePath() == null) {
9827            // Bail out. The resource and code paths haven't been set.
9828            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9829                    "Code and resource paths haven't been set correctly");
9830        }
9831
9832        // Make sure we're not adding any bogus keyset info
9833        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9834        ksms.assertScannedPackageValid(pkg);
9835
9836        synchronized (mPackages) {
9837            // The special "android" package can only be defined once
9838            if (pkg.packageName.equals("android")) {
9839                if (mAndroidApplication != null) {
9840                    Slog.w(TAG, "*************************************************");
9841                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9842                    Slog.w(TAG, " codePath=" + pkg.codePath);
9843                    Slog.w(TAG, "*************************************************");
9844                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9845                            "Core android package being redefined.  Skipping.");
9846                }
9847            }
9848
9849            // A package name must be unique; don't allow duplicates
9850            if (mPackages.containsKey(pkg.packageName)) {
9851                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9852                        "Application package " + pkg.packageName
9853                        + " already installed.  Skipping duplicate.");
9854            }
9855
9856            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9857                // Static libs have a synthetic package name containing the version
9858                // but we still want the base name to be unique.
9859                if (mPackages.containsKey(pkg.manifestPackageName)) {
9860                    throw new PackageManagerException(
9861                            "Duplicate static shared lib provider package");
9862                }
9863
9864                // Static shared libraries should have at least O target SDK
9865                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9866                    throw new PackageManagerException(
9867                            "Packages declaring static-shared libs must target O SDK or higher");
9868                }
9869
9870                // Package declaring static a shared lib cannot be instant apps
9871                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9872                    throw new PackageManagerException(
9873                            "Packages declaring static-shared libs cannot be instant apps");
9874                }
9875
9876                // Package declaring static a shared lib cannot be renamed since the package
9877                // name is synthetic and apps can't code around package manager internals.
9878                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9879                    throw new PackageManagerException(
9880                            "Packages declaring static-shared libs cannot be renamed");
9881                }
9882
9883                // Package declaring static a shared lib cannot declare child packages
9884                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9885                    throw new PackageManagerException(
9886                            "Packages declaring static-shared libs cannot have child packages");
9887                }
9888
9889                // Package declaring static a shared lib cannot declare dynamic libs
9890                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9891                    throw new PackageManagerException(
9892                            "Packages declaring static-shared libs cannot declare dynamic libs");
9893                }
9894
9895                // Package declaring static a shared lib cannot declare shared users
9896                if (pkg.mSharedUserId != null) {
9897                    throw new PackageManagerException(
9898                            "Packages declaring static-shared libs cannot declare shared users");
9899                }
9900
9901                // Static shared libs cannot declare activities
9902                if (!pkg.activities.isEmpty()) {
9903                    throw new PackageManagerException(
9904                            "Static shared libs cannot declare activities");
9905                }
9906
9907                // Static shared libs cannot declare services
9908                if (!pkg.services.isEmpty()) {
9909                    throw new PackageManagerException(
9910                            "Static shared libs cannot declare services");
9911                }
9912
9913                // Static shared libs cannot declare providers
9914                if (!pkg.providers.isEmpty()) {
9915                    throw new PackageManagerException(
9916                            "Static shared libs cannot declare content providers");
9917                }
9918
9919                // Static shared libs cannot declare receivers
9920                if (!pkg.receivers.isEmpty()) {
9921                    throw new PackageManagerException(
9922                            "Static shared libs cannot declare broadcast receivers");
9923                }
9924
9925                // Static shared libs cannot declare permission groups
9926                if (!pkg.permissionGroups.isEmpty()) {
9927                    throw new PackageManagerException(
9928                            "Static shared libs cannot declare permission groups");
9929                }
9930
9931                // Static shared libs cannot declare permissions
9932                if (!pkg.permissions.isEmpty()) {
9933                    throw new PackageManagerException(
9934                            "Static shared libs cannot declare permissions");
9935                }
9936
9937                // Static shared libs cannot declare protected broadcasts
9938                if (pkg.protectedBroadcasts != null) {
9939                    throw new PackageManagerException(
9940                            "Static shared libs cannot declare protected broadcasts");
9941                }
9942
9943                // Static shared libs cannot be overlay targets
9944                if (pkg.mOverlayTarget != null) {
9945                    throw new PackageManagerException(
9946                            "Static shared libs cannot be overlay targets");
9947                }
9948
9949                // The version codes must be ordered as lib versions
9950                int minVersionCode = Integer.MIN_VALUE;
9951                int maxVersionCode = Integer.MAX_VALUE;
9952
9953                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9954                        pkg.staticSharedLibName);
9955                if (versionedLib != null) {
9956                    final int versionCount = versionedLib.size();
9957                    for (int i = 0; i < versionCount; i++) {
9958                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9959                        // TODO: We will change version code to long, so in the new API it is long
9960                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9961                                .getVersionCode();
9962                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9963                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9964                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9965                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9966                        } else {
9967                            minVersionCode = maxVersionCode = libVersionCode;
9968                            break;
9969                        }
9970                    }
9971                }
9972                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9973                    throw new PackageManagerException("Static shared"
9974                            + " lib version codes must be ordered as lib versions");
9975                }
9976            }
9977
9978            // Only privileged apps and updated privileged apps can add child packages.
9979            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9980                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9981                    throw new PackageManagerException("Only privileged apps can add child "
9982                            + "packages. Ignoring package " + pkg.packageName);
9983                }
9984                final int childCount = pkg.childPackages.size();
9985                for (int i = 0; i < childCount; i++) {
9986                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9987                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9988                            childPkg.packageName)) {
9989                        throw new PackageManagerException("Can't override child of "
9990                                + "another disabled app. Ignoring package " + pkg.packageName);
9991                    }
9992                }
9993            }
9994
9995            // If we're only installing presumed-existing packages, require that the
9996            // scanned APK is both already known and at the path previously established
9997            // for it.  Previously unknown packages we pick up normally, but if we have an
9998            // a priori expectation about this package's install presence, enforce it.
9999            // With a singular exception for new system packages. When an OTA contains
10000            // a new system package, we allow the codepath to change from a system location
10001            // to the user-installed location. If we don't allow this change, any newer,
10002            // user-installed version of the application will be ignored.
10003            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10004                if (mExpectingBetter.containsKey(pkg.packageName)) {
10005                    logCriticalInfo(Log.WARN,
10006                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10007                } else {
10008                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10009                    if (known != null) {
10010                        if (DEBUG_PACKAGE_SCANNING) {
10011                            Log.d(TAG, "Examining " + pkg.codePath
10012                                    + " and requiring known paths " + known.codePathString
10013                                    + " & " + known.resourcePathString);
10014                        }
10015                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10016                                || !pkg.applicationInfo.getResourcePath().equals(
10017                                        known.resourcePathString)) {
10018                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10019                                    "Application package " + pkg.packageName
10020                                    + " found at " + pkg.applicationInfo.getCodePath()
10021                                    + " but expected at " + known.codePathString
10022                                    + "; ignoring.");
10023                        }
10024                    }
10025                }
10026            }
10027
10028            // Verify that this new package doesn't have any content providers
10029            // that conflict with existing packages.  Only do this if the
10030            // package isn't already installed, since we don't want to break
10031            // things that are installed.
10032            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10033                final int N = pkg.providers.size();
10034                int i;
10035                for (i=0; i<N; i++) {
10036                    PackageParser.Provider p = pkg.providers.get(i);
10037                    if (p.info.authority != null) {
10038                        String names[] = p.info.authority.split(";");
10039                        for (int j = 0; j < names.length; j++) {
10040                            if (mProvidersByAuthority.containsKey(names[j])) {
10041                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10042                                final String otherPackageName =
10043                                        ((other != null && other.getComponentName() != null) ?
10044                                                other.getComponentName().getPackageName() : "?");
10045                                throw new PackageManagerException(
10046                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10047                                        "Can't install because provider name " + names[j]
10048                                                + " (in package " + pkg.applicationInfo.packageName
10049                                                + ") is already used by " + otherPackageName);
10050                            }
10051                        }
10052                    }
10053                }
10054            }
10055        }
10056    }
10057
10058    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10059            int type, String declaringPackageName, int declaringVersionCode) {
10060        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10061        if (versionedLib == null) {
10062            versionedLib = new SparseArray<>();
10063            mSharedLibraries.put(name, versionedLib);
10064            if (type == SharedLibraryInfo.TYPE_STATIC) {
10065                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10066            }
10067        } else if (versionedLib.indexOfKey(version) >= 0) {
10068            return false;
10069        }
10070        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10071                version, type, declaringPackageName, declaringVersionCode);
10072        versionedLib.put(version, libEntry);
10073        return true;
10074    }
10075
10076    private boolean removeSharedLibraryLPw(String name, int version) {
10077        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10078        if (versionedLib == null) {
10079            return false;
10080        }
10081        final int libIdx = versionedLib.indexOfKey(version);
10082        if (libIdx < 0) {
10083            return false;
10084        }
10085        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10086        versionedLib.remove(version);
10087        if (versionedLib.size() <= 0) {
10088            mSharedLibraries.remove(name);
10089            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10090                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10091                        .getPackageName());
10092            }
10093        }
10094        return true;
10095    }
10096
10097    /**
10098     * Adds a scanned package to the system. When this method is finished, the package will
10099     * be available for query, resolution, etc...
10100     */
10101    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10102            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10103        final String pkgName = pkg.packageName;
10104        if (mCustomResolverComponentName != null &&
10105                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10106            setUpCustomResolverActivity(pkg);
10107        }
10108
10109        if (pkg.packageName.equals("android")) {
10110            synchronized (mPackages) {
10111                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10112                    // Set up information for our fall-back user intent resolution activity.
10113                    mPlatformPackage = pkg;
10114                    pkg.mVersionCode = mSdkVersion;
10115                    mAndroidApplication = pkg.applicationInfo;
10116                    if (!mResolverReplaced) {
10117                        mResolveActivity.applicationInfo = mAndroidApplication;
10118                        mResolveActivity.name = ResolverActivity.class.getName();
10119                        mResolveActivity.packageName = mAndroidApplication.packageName;
10120                        mResolveActivity.processName = "system:ui";
10121                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10122                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10123                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10124                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10125                        mResolveActivity.exported = true;
10126                        mResolveActivity.enabled = true;
10127                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10128                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10129                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10130                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10131                                | ActivityInfo.CONFIG_ORIENTATION
10132                                | ActivityInfo.CONFIG_KEYBOARD
10133                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10134                        mResolveInfo.activityInfo = mResolveActivity;
10135                        mResolveInfo.priority = 0;
10136                        mResolveInfo.preferredOrder = 0;
10137                        mResolveInfo.match = 0;
10138                        mResolveComponentName = new ComponentName(
10139                                mAndroidApplication.packageName, mResolveActivity.name);
10140                    }
10141                }
10142            }
10143        }
10144
10145        ArrayList<PackageParser.Package> clientLibPkgs = null;
10146        // writer
10147        synchronized (mPackages) {
10148            boolean hasStaticSharedLibs = false;
10149
10150            // Any app can add new static shared libraries
10151            if (pkg.staticSharedLibName != null) {
10152                // Static shared libs don't allow renaming as they have synthetic package
10153                // names to allow install of multiple versions, so use name from manifest.
10154                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10155                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10156                        pkg.manifestPackageName, pkg.mVersionCode)) {
10157                    hasStaticSharedLibs = true;
10158                } else {
10159                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10160                                + pkg.staticSharedLibName + " already exists; skipping");
10161                }
10162                // Static shared libs cannot be updated once installed since they
10163                // use synthetic package name which includes the version code, so
10164                // not need to update other packages's shared lib dependencies.
10165            }
10166
10167            if (!hasStaticSharedLibs
10168                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10169                // Only system apps can add new dynamic shared libraries.
10170                if (pkg.libraryNames != null) {
10171                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10172                        String name = pkg.libraryNames.get(i);
10173                        boolean allowed = false;
10174                        if (pkg.isUpdatedSystemApp()) {
10175                            // New library entries can only be added through the
10176                            // system image.  This is important to get rid of a lot
10177                            // of nasty edge cases: for example if we allowed a non-
10178                            // system update of the app to add a library, then uninstalling
10179                            // the update would make the library go away, and assumptions
10180                            // we made such as through app install filtering would now
10181                            // have allowed apps on the device which aren't compatible
10182                            // with it.  Better to just have the restriction here, be
10183                            // conservative, and create many fewer cases that can negatively
10184                            // impact the user experience.
10185                            final PackageSetting sysPs = mSettings
10186                                    .getDisabledSystemPkgLPr(pkg.packageName);
10187                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10188                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10189                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10190                                        allowed = true;
10191                                        break;
10192                                    }
10193                                }
10194                            }
10195                        } else {
10196                            allowed = true;
10197                        }
10198                        if (allowed) {
10199                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10200                                    SharedLibraryInfo.VERSION_UNDEFINED,
10201                                    SharedLibraryInfo.TYPE_DYNAMIC,
10202                                    pkg.packageName, pkg.mVersionCode)) {
10203                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10204                                        + name + " already exists; skipping");
10205                            }
10206                        } else {
10207                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10208                                    + name + " that is not declared on system image; skipping");
10209                        }
10210                    }
10211
10212                    if ((scanFlags & SCAN_BOOTING) == 0) {
10213                        // If we are not booting, we need to update any applications
10214                        // that are clients of our shared library.  If we are booting,
10215                        // this will all be done once the scan is complete.
10216                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10217                    }
10218                }
10219            }
10220        }
10221
10222        if ((scanFlags & SCAN_BOOTING) != 0) {
10223            // No apps can run during boot scan, so they don't need to be frozen
10224        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10225            // Caller asked to not kill app, so it's probably not frozen
10226        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10227            // Caller asked us to ignore frozen check for some reason; they
10228            // probably didn't know the package name
10229        } else {
10230            // We're doing major surgery on this package, so it better be frozen
10231            // right now to keep it from launching
10232            checkPackageFrozen(pkgName);
10233        }
10234
10235        // Also need to kill any apps that are dependent on the library.
10236        if (clientLibPkgs != null) {
10237            for (int i=0; i<clientLibPkgs.size(); i++) {
10238                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10239                killApplication(clientPkg.applicationInfo.packageName,
10240                        clientPkg.applicationInfo.uid, "update lib");
10241            }
10242        }
10243
10244        // writer
10245        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10246
10247        synchronized (mPackages) {
10248            // We don't expect installation to fail beyond this point
10249
10250            // Add the new setting to mSettings
10251            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10252            // Add the new setting to mPackages
10253            mPackages.put(pkg.applicationInfo.packageName, pkg);
10254            // Make sure we don't accidentally delete its data.
10255            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10256            while (iter.hasNext()) {
10257                PackageCleanItem item = iter.next();
10258                if (pkgName.equals(item.packageName)) {
10259                    iter.remove();
10260                }
10261            }
10262
10263            // Add the package's KeySets to the global KeySetManagerService
10264            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10265            ksms.addScannedPackageLPw(pkg);
10266
10267            int N = pkg.providers.size();
10268            StringBuilder r = null;
10269            int i;
10270            for (i=0; i<N; i++) {
10271                PackageParser.Provider p = pkg.providers.get(i);
10272                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10273                        p.info.processName);
10274                mProviders.addProvider(p);
10275                p.syncable = p.info.isSyncable;
10276                if (p.info.authority != null) {
10277                    String names[] = p.info.authority.split(";");
10278                    p.info.authority = null;
10279                    for (int j = 0; j < names.length; j++) {
10280                        if (j == 1 && p.syncable) {
10281                            // We only want the first authority for a provider to possibly be
10282                            // syncable, so if we already added this provider using a different
10283                            // authority clear the syncable flag. We copy the provider before
10284                            // changing it because the mProviders object contains a reference
10285                            // to a provider that we don't want to change.
10286                            // Only do this for the second authority since the resulting provider
10287                            // object can be the same for all future authorities for this provider.
10288                            p = new PackageParser.Provider(p);
10289                            p.syncable = false;
10290                        }
10291                        if (!mProvidersByAuthority.containsKey(names[j])) {
10292                            mProvidersByAuthority.put(names[j], p);
10293                            if (p.info.authority == null) {
10294                                p.info.authority = names[j];
10295                            } else {
10296                                p.info.authority = p.info.authority + ";" + names[j];
10297                            }
10298                            if (DEBUG_PACKAGE_SCANNING) {
10299                                if (chatty)
10300                                    Log.d(TAG, "Registered content provider: " + names[j]
10301                                            + ", className = " + p.info.name + ", isSyncable = "
10302                                            + p.info.isSyncable);
10303                            }
10304                        } else {
10305                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10306                            Slog.w(TAG, "Skipping provider name " + names[j] +
10307                                    " (in package " + pkg.applicationInfo.packageName +
10308                                    "): name already used by "
10309                                    + ((other != null && other.getComponentName() != null)
10310                                            ? other.getComponentName().getPackageName() : "?"));
10311                        }
10312                    }
10313                }
10314                if (chatty) {
10315                    if (r == null) {
10316                        r = new StringBuilder(256);
10317                    } else {
10318                        r.append(' ');
10319                    }
10320                    r.append(p.info.name);
10321                }
10322            }
10323            if (r != null) {
10324                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10325            }
10326
10327            N = pkg.services.size();
10328            r = null;
10329            for (i=0; i<N; i++) {
10330                PackageParser.Service s = pkg.services.get(i);
10331                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10332                        s.info.processName);
10333                mServices.addService(s);
10334                if (chatty) {
10335                    if (r == null) {
10336                        r = new StringBuilder(256);
10337                    } else {
10338                        r.append(' ');
10339                    }
10340                    r.append(s.info.name);
10341                }
10342            }
10343            if (r != null) {
10344                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10345            }
10346
10347            N = pkg.receivers.size();
10348            r = null;
10349            for (i=0; i<N; i++) {
10350                PackageParser.Activity a = pkg.receivers.get(i);
10351                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10352                        a.info.processName);
10353                mReceivers.addActivity(a, "receiver");
10354                if (chatty) {
10355                    if (r == null) {
10356                        r = new StringBuilder(256);
10357                    } else {
10358                        r.append(' ');
10359                    }
10360                    r.append(a.info.name);
10361                }
10362            }
10363            if (r != null) {
10364                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10365            }
10366
10367            N = pkg.activities.size();
10368            r = null;
10369            for (i=0; i<N; i++) {
10370                PackageParser.Activity a = pkg.activities.get(i);
10371                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10372                        a.info.processName);
10373                mActivities.addActivity(a, "activity");
10374                if (chatty) {
10375                    if (r == null) {
10376                        r = new StringBuilder(256);
10377                    } else {
10378                        r.append(' ');
10379                    }
10380                    r.append(a.info.name);
10381                }
10382            }
10383            if (r != null) {
10384                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10385            }
10386
10387            N = pkg.permissionGroups.size();
10388            r = null;
10389            for (i=0; i<N; i++) {
10390                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10391                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10392                final String curPackageName = cur == null ? null : cur.info.packageName;
10393                // Dont allow ephemeral apps to define new permission groups.
10394                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10395                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10396                            + pg.info.packageName
10397                            + " ignored: instant apps cannot define new permission groups.");
10398                    continue;
10399                }
10400                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10401                if (cur == null || isPackageUpdate) {
10402                    mPermissionGroups.put(pg.info.name, pg);
10403                    if (chatty) {
10404                        if (r == null) {
10405                            r = new StringBuilder(256);
10406                        } else {
10407                            r.append(' ');
10408                        }
10409                        if (isPackageUpdate) {
10410                            r.append("UPD:");
10411                        }
10412                        r.append(pg.info.name);
10413                    }
10414                } else {
10415                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10416                            + pg.info.packageName + " ignored: original from "
10417                            + cur.info.packageName);
10418                    if (chatty) {
10419                        if (r == null) {
10420                            r = new StringBuilder(256);
10421                        } else {
10422                            r.append(' ');
10423                        }
10424                        r.append("DUP:");
10425                        r.append(pg.info.name);
10426                    }
10427                }
10428            }
10429            if (r != null) {
10430                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10431            }
10432
10433            N = pkg.permissions.size();
10434            r = null;
10435            for (i=0; i<N; i++) {
10436                PackageParser.Permission p = pkg.permissions.get(i);
10437
10438                // Dont allow ephemeral apps to define new permissions.
10439                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10440                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10441                            + p.info.packageName
10442                            + " ignored: instant apps cannot define new permissions.");
10443                    continue;
10444                }
10445
10446                // Assume by default that we did not install this permission into the system.
10447                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10448
10449                // Now that permission groups have a special meaning, we ignore permission
10450                // groups for legacy apps to prevent unexpected behavior. In particular,
10451                // permissions for one app being granted to someone just becase they happen
10452                // to be in a group defined by another app (before this had no implications).
10453                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10454                    p.group = mPermissionGroups.get(p.info.group);
10455                    // Warn for a permission in an unknown group.
10456                    if (p.info.group != null && p.group == null) {
10457                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10458                                + p.info.packageName + " in an unknown group " + p.info.group);
10459                    }
10460                }
10461
10462                ArrayMap<String, BasePermission> permissionMap =
10463                        p.tree ? mSettings.mPermissionTrees
10464                                : mSettings.mPermissions;
10465                BasePermission bp = permissionMap.get(p.info.name);
10466
10467                // Allow system apps to redefine non-system permissions
10468                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10469                    final boolean currentOwnerIsSystem = (bp.perm != null
10470                            && isSystemApp(bp.perm.owner));
10471                    if (isSystemApp(p.owner)) {
10472                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10473                            // It's a built-in permission and no owner, take ownership now
10474                            bp.packageSetting = pkgSetting;
10475                            bp.perm = p;
10476                            bp.uid = pkg.applicationInfo.uid;
10477                            bp.sourcePackage = p.info.packageName;
10478                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10479                        } else if (!currentOwnerIsSystem) {
10480                            String msg = "New decl " + p.owner + " of permission  "
10481                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10482                            reportSettingsProblem(Log.WARN, msg);
10483                            bp = null;
10484                        }
10485                    }
10486                }
10487
10488                if (bp == null) {
10489                    bp = new BasePermission(p.info.name, p.info.packageName,
10490                            BasePermission.TYPE_NORMAL);
10491                    permissionMap.put(p.info.name, bp);
10492                }
10493
10494                if (bp.perm == null) {
10495                    if (bp.sourcePackage == null
10496                            || bp.sourcePackage.equals(p.info.packageName)) {
10497                        BasePermission tree = findPermissionTreeLP(p.info.name);
10498                        if (tree == null
10499                                || tree.sourcePackage.equals(p.info.packageName)) {
10500                            bp.packageSetting = pkgSetting;
10501                            bp.perm = p;
10502                            bp.uid = pkg.applicationInfo.uid;
10503                            bp.sourcePackage = p.info.packageName;
10504                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10505                            if (chatty) {
10506                                if (r == null) {
10507                                    r = new StringBuilder(256);
10508                                } else {
10509                                    r.append(' ');
10510                                }
10511                                r.append(p.info.name);
10512                            }
10513                        } else {
10514                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10515                                    + p.info.packageName + " ignored: base tree "
10516                                    + tree.name + " is from package "
10517                                    + tree.sourcePackage);
10518                        }
10519                    } else {
10520                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10521                                + p.info.packageName + " ignored: original from "
10522                                + bp.sourcePackage);
10523                    }
10524                } else if (chatty) {
10525                    if (r == null) {
10526                        r = new StringBuilder(256);
10527                    } else {
10528                        r.append(' ');
10529                    }
10530                    r.append("DUP:");
10531                    r.append(p.info.name);
10532                }
10533                if (bp.perm == p) {
10534                    bp.protectionLevel = p.info.protectionLevel;
10535                }
10536            }
10537
10538            if (r != null) {
10539                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10540            }
10541
10542            N = pkg.instrumentation.size();
10543            r = null;
10544            for (i=0; i<N; i++) {
10545                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10546                a.info.packageName = pkg.applicationInfo.packageName;
10547                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10548                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10549                a.info.splitNames = pkg.splitNames;
10550                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10551                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10552                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10553                a.info.dataDir = pkg.applicationInfo.dataDir;
10554                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10555                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10556                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10557                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10558                mInstrumentation.put(a.getComponentName(), a);
10559                if (chatty) {
10560                    if (r == null) {
10561                        r = new StringBuilder(256);
10562                    } else {
10563                        r.append(' ');
10564                    }
10565                    r.append(a.info.name);
10566                }
10567            }
10568            if (r != null) {
10569                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10570            }
10571
10572            if (pkg.protectedBroadcasts != null) {
10573                N = pkg.protectedBroadcasts.size();
10574                for (i=0; i<N; i++) {
10575                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10576                }
10577            }
10578        }
10579
10580        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10581    }
10582
10583    /**
10584     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10585     * is derived purely on the basis of the contents of {@code scanFile} and
10586     * {@code cpuAbiOverride}.
10587     *
10588     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10589     */
10590    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10591                                 String cpuAbiOverride, boolean extractLibs,
10592                                 File appLib32InstallDir)
10593            throws PackageManagerException {
10594        // Give ourselves some initial paths; we'll come back for another
10595        // pass once we've determined ABI below.
10596        setNativeLibraryPaths(pkg, appLib32InstallDir);
10597
10598        // We would never need to extract libs for forward-locked and external packages,
10599        // since the container service will do it for us. We shouldn't attempt to
10600        // extract libs from system app when it was not updated.
10601        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10602                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10603            extractLibs = false;
10604        }
10605
10606        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10607        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10608
10609        NativeLibraryHelper.Handle handle = null;
10610        try {
10611            handle = NativeLibraryHelper.Handle.create(pkg);
10612            // TODO(multiArch): This can be null for apps that didn't go through the
10613            // usual installation process. We can calculate it again, like we
10614            // do during install time.
10615            //
10616            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10617            // unnecessary.
10618            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10619
10620            // Null out the abis so that they can be recalculated.
10621            pkg.applicationInfo.primaryCpuAbi = null;
10622            pkg.applicationInfo.secondaryCpuAbi = null;
10623            if (isMultiArch(pkg.applicationInfo)) {
10624                // Warn if we've set an abiOverride for multi-lib packages..
10625                // By definition, we need to copy both 32 and 64 bit libraries for
10626                // such packages.
10627                if (pkg.cpuAbiOverride != null
10628                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10629                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10630                }
10631
10632                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10633                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10634                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10635                    if (extractLibs) {
10636                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10637                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10638                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10639                                useIsaSpecificSubdirs);
10640                    } else {
10641                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10642                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10643                    }
10644                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10645                }
10646
10647                maybeThrowExceptionForMultiArchCopy(
10648                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10649
10650                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10651                    if (extractLibs) {
10652                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10653                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10654                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10655                                useIsaSpecificSubdirs);
10656                    } else {
10657                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10658                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10659                    }
10660                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10661                }
10662
10663                maybeThrowExceptionForMultiArchCopy(
10664                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10665
10666                if (abi64 >= 0) {
10667                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10668                }
10669
10670                if (abi32 >= 0) {
10671                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10672                    if (abi64 >= 0) {
10673                        if (pkg.use32bitAbi) {
10674                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10675                            pkg.applicationInfo.primaryCpuAbi = abi;
10676                        } else {
10677                            pkg.applicationInfo.secondaryCpuAbi = abi;
10678                        }
10679                    } else {
10680                        pkg.applicationInfo.primaryCpuAbi = abi;
10681                    }
10682                }
10683
10684            } else {
10685                String[] abiList = (cpuAbiOverride != null) ?
10686                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10687
10688                // Enable gross and lame hacks for apps that are built with old
10689                // SDK tools. We must scan their APKs for renderscript bitcode and
10690                // not launch them if it's present. Don't bother checking on devices
10691                // that don't have 64 bit support.
10692                boolean needsRenderScriptOverride = false;
10693                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10694                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10695                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10696                    needsRenderScriptOverride = true;
10697                }
10698
10699                final int copyRet;
10700                if (extractLibs) {
10701                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10702                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10703                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10704                } else {
10705                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10706                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10707                }
10708                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10709
10710                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10711                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10712                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10713                }
10714
10715                if (copyRet >= 0) {
10716                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10717                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10718                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10719                } else if (needsRenderScriptOverride) {
10720                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10721                }
10722            }
10723        } catch (IOException ioe) {
10724            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10725        } finally {
10726            IoUtils.closeQuietly(handle);
10727        }
10728
10729        // Now that we've calculated the ABIs and determined if it's an internal app,
10730        // we will go ahead and populate the nativeLibraryPath.
10731        setNativeLibraryPaths(pkg, appLib32InstallDir);
10732    }
10733
10734    /**
10735     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10736     * i.e, so that all packages can be run inside a single process if required.
10737     *
10738     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10739     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10740     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10741     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10742     * updating a package that belongs to a shared user.
10743     *
10744     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10745     * adds unnecessary complexity.
10746     */
10747    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10748            PackageParser.Package scannedPackage) {
10749        String requiredInstructionSet = null;
10750        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10751            requiredInstructionSet = VMRuntime.getInstructionSet(
10752                     scannedPackage.applicationInfo.primaryCpuAbi);
10753        }
10754
10755        PackageSetting requirer = null;
10756        for (PackageSetting ps : packagesForUser) {
10757            // If packagesForUser contains scannedPackage, we skip it. This will happen
10758            // when scannedPackage is an update of an existing package. Without this check,
10759            // we will never be able to change the ABI of any package belonging to a shared
10760            // user, even if it's compatible with other packages.
10761            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10762                if (ps.primaryCpuAbiString == null) {
10763                    continue;
10764                }
10765
10766                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10767                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10768                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10769                    // this but there's not much we can do.
10770                    String errorMessage = "Instruction set mismatch, "
10771                            + ((requirer == null) ? "[caller]" : requirer)
10772                            + " requires " + requiredInstructionSet + " whereas " + ps
10773                            + " requires " + instructionSet;
10774                    Slog.w(TAG, errorMessage);
10775                }
10776
10777                if (requiredInstructionSet == null) {
10778                    requiredInstructionSet = instructionSet;
10779                    requirer = ps;
10780                }
10781            }
10782        }
10783
10784        if (requiredInstructionSet != null) {
10785            String adjustedAbi;
10786            if (requirer != null) {
10787                // requirer != null implies that either scannedPackage was null or that scannedPackage
10788                // did not require an ABI, in which case we have to adjust scannedPackage to match
10789                // the ABI of the set (which is the same as requirer's ABI)
10790                adjustedAbi = requirer.primaryCpuAbiString;
10791                if (scannedPackage != null) {
10792                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10793                }
10794            } else {
10795                // requirer == null implies that we're updating all ABIs in the set to
10796                // match scannedPackage.
10797                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10798            }
10799
10800            for (PackageSetting ps : packagesForUser) {
10801                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10802                    if (ps.primaryCpuAbiString != null) {
10803                        continue;
10804                    }
10805
10806                    ps.primaryCpuAbiString = adjustedAbi;
10807                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10808                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10809                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10810                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10811                                + " (requirer="
10812                                + (requirer != null ? requirer.pkg : "null")
10813                                + ", scannedPackage="
10814                                + (scannedPackage != null ? scannedPackage : "null")
10815                                + ")");
10816                        try {
10817                            mInstaller.rmdex(ps.codePathString,
10818                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10819                        } catch (InstallerException ignored) {
10820                        }
10821                    }
10822                }
10823            }
10824        }
10825    }
10826
10827    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10828        synchronized (mPackages) {
10829            mResolverReplaced = true;
10830            // Set up information for custom user intent resolution activity.
10831            mResolveActivity.applicationInfo = pkg.applicationInfo;
10832            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10833            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10834            mResolveActivity.processName = pkg.applicationInfo.packageName;
10835            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10836            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10837                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10838            mResolveActivity.theme = 0;
10839            mResolveActivity.exported = true;
10840            mResolveActivity.enabled = true;
10841            mResolveInfo.activityInfo = mResolveActivity;
10842            mResolveInfo.priority = 0;
10843            mResolveInfo.preferredOrder = 0;
10844            mResolveInfo.match = 0;
10845            mResolveComponentName = mCustomResolverComponentName;
10846            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10847                    mResolveComponentName);
10848        }
10849    }
10850
10851    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
10852        if (installerActivity == null) {
10853            if (DEBUG_EPHEMERAL) {
10854                Slog.d(TAG, "Clear ephemeral installer activity");
10855            }
10856            mInstantAppInstallerActivity = null;
10857            return;
10858        }
10859
10860        if (DEBUG_EPHEMERAL) {
10861            Slog.d(TAG, "Set ephemeral installer activity: "
10862                    + installerActivity.getComponentName());
10863        }
10864        // Set up information for ephemeral installer activity
10865        mInstantAppInstallerActivity = installerActivity;
10866        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10867                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10868        mInstantAppInstallerActivity.exported = true;
10869        mInstantAppInstallerActivity.enabled = true;
10870        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10871        mInstantAppInstallerInfo.priority = 0;
10872        mInstantAppInstallerInfo.preferredOrder = 1;
10873        mInstantAppInstallerInfo.isDefault = true;
10874        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10875                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10876    }
10877
10878    private static String calculateBundledApkRoot(final String codePathString) {
10879        final File codePath = new File(codePathString);
10880        final File codeRoot;
10881        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10882            codeRoot = Environment.getRootDirectory();
10883        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10884            codeRoot = Environment.getOemDirectory();
10885        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10886            codeRoot = Environment.getVendorDirectory();
10887        } else {
10888            // Unrecognized code path; take its top real segment as the apk root:
10889            // e.g. /something/app/blah.apk => /something
10890            try {
10891                File f = codePath.getCanonicalFile();
10892                File parent = f.getParentFile();    // non-null because codePath is a file
10893                File tmp;
10894                while ((tmp = parent.getParentFile()) != null) {
10895                    f = parent;
10896                    parent = tmp;
10897                }
10898                codeRoot = f;
10899                Slog.w(TAG, "Unrecognized code path "
10900                        + codePath + " - using " + codeRoot);
10901            } catch (IOException e) {
10902                // Can't canonicalize the code path -- shenanigans?
10903                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10904                return Environment.getRootDirectory().getPath();
10905            }
10906        }
10907        return codeRoot.getPath();
10908    }
10909
10910    /**
10911     * Derive and set the location of native libraries for the given package,
10912     * which varies depending on where and how the package was installed.
10913     */
10914    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10915        final ApplicationInfo info = pkg.applicationInfo;
10916        final String codePath = pkg.codePath;
10917        final File codeFile = new File(codePath);
10918        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10919        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10920
10921        info.nativeLibraryRootDir = null;
10922        info.nativeLibraryRootRequiresIsa = false;
10923        info.nativeLibraryDir = null;
10924        info.secondaryNativeLibraryDir = null;
10925
10926        if (isApkFile(codeFile)) {
10927            // Monolithic install
10928            if (bundledApp) {
10929                // If "/system/lib64/apkname" exists, assume that is the per-package
10930                // native library directory to use; otherwise use "/system/lib/apkname".
10931                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10932                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10933                        getPrimaryInstructionSet(info));
10934
10935                // This is a bundled system app so choose the path based on the ABI.
10936                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10937                // is just the default path.
10938                final String apkName = deriveCodePathName(codePath);
10939                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10940                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10941                        apkName).getAbsolutePath();
10942
10943                if (info.secondaryCpuAbi != null) {
10944                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10945                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10946                            secondaryLibDir, apkName).getAbsolutePath();
10947                }
10948            } else if (asecApp) {
10949                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10950                        .getAbsolutePath();
10951            } else {
10952                final String apkName = deriveCodePathName(codePath);
10953                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10954                        .getAbsolutePath();
10955            }
10956
10957            info.nativeLibraryRootRequiresIsa = false;
10958            info.nativeLibraryDir = info.nativeLibraryRootDir;
10959        } else {
10960            // Cluster install
10961            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10962            info.nativeLibraryRootRequiresIsa = true;
10963
10964            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10965                    getPrimaryInstructionSet(info)).getAbsolutePath();
10966
10967            if (info.secondaryCpuAbi != null) {
10968                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10969                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10970            }
10971        }
10972    }
10973
10974    /**
10975     * Calculate the abis and roots for a bundled app. These can uniquely
10976     * be determined from the contents of the system partition, i.e whether
10977     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10978     * of this information, and instead assume that the system was built
10979     * sensibly.
10980     */
10981    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10982                                           PackageSetting pkgSetting) {
10983        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10984
10985        // If "/system/lib64/apkname" exists, assume that is the per-package
10986        // native library directory to use; otherwise use "/system/lib/apkname".
10987        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10988        setBundledAppAbi(pkg, apkRoot, apkName);
10989        // pkgSetting might be null during rescan following uninstall of updates
10990        // to a bundled app, so accommodate that possibility.  The settings in
10991        // that case will be established later from the parsed package.
10992        //
10993        // If the settings aren't null, sync them up with what we've just derived.
10994        // note that apkRoot isn't stored in the package settings.
10995        if (pkgSetting != null) {
10996            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10997            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10998        }
10999    }
11000
11001    /**
11002     * Deduces the ABI of a bundled app and sets the relevant fields on the
11003     * parsed pkg object.
11004     *
11005     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11006     *        under which system libraries are installed.
11007     * @param apkName the name of the installed package.
11008     */
11009    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11010        final File codeFile = new File(pkg.codePath);
11011
11012        final boolean has64BitLibs;
11013        final boolean has32BitLibs;
11014        if (isApkFile(codeFile)) {
11015            // Monolithic install
11016            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11017            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11018        } else {
11019            // Cluster install
11020            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11021            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11022                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11023                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11024                has64BitLibs = (new File(rootDir, isa)).exists();
11025            } else {
11026                has64BitLibs = false;
11027            }
11028            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11029                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11030                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11031                has32BitLibs = (new File(rootDir, isa)).exists();
11032            } else {
11033                has32BitLibs = false;
11034            }
11035        }
11036
11037        if (has64BitLibs && !has32BitLibs) {
11038            // The package has 64 bit libs, but not 32 bit libs. Its primary
11039            // ABI should be 64 bit. We can safely assume here that the bundled
11040            // native libraries correspond to the most preferred ABI in the list.
11041
11042            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11043            pkg.applicationInfo.secondaryCpuAbi = null;
11044        } else if (has32BitLibs && !has64BitLibs) {
11045            // The package has 32 bit libs but not 64 bit libs. Its primary
11046            // ABI should be 32 bit.
11047
11048            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11049            pkg.applicationInfo.secondaryCpuAbi = null;
11050        } else if (has32BitLibs && has64BitLibs) {
11051            // The application has both 64 and 32 bit bundled libraries. We check
11052            // here that the app declares multiArch support, and warn if it doesn't.
11053            //
11054            // We will be lenient here and record both ABIs. The primary will be the
11055            // ABI that's higher on the list, i.e, a device that's configured to prefer
11056            // 64 bit apps will see a 64 bit primary ABI,
11057
11058            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11059                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11060            }
11061
11062            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11063                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11064                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11065            } else {
11066                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11067                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11068            }
11069        } else {
11070            pkg.applicationInfo.primaryCpuAbi = null;
11071            pkg.applicationInfo.secondaryCpuAbi = null;
11072        }
11073    }
11074
11075    private void killApplication(String pkgName, int appId, String reason) {
11076        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11077    }
11078
11079    private void killApplication(String pkgName, int appId, int userId, String reason) {
11080        // Request the ActivityManager to kill the process(only for existing packages)
11081        // so that we do not end up in a confused state while the user is still using the older
11082        // version of the application while the new one gets installed.
11083        final long token = Binder.clearCallingIdentity();
11084        try {
11085            IActivityManager am = ActivityManager.getService();
11086            if (am != null) {
11087                try {
11088                    am.killApplication(pkgName, appId, userId, reason);
11089                } catch (RemoteException e) {
11090                }
11091            }
11092        } finally {
11093            Binder.restoreCallingIdentity(token);
11094        }
11095    }
11096
11097    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11098        // Remove the parent package setting
11099        PackageSetting ps = (PackageSetting) pkg.mExtras;
11100        if (ps != null) {
11101            removePackageLI(ps, chatty);
11102        }
11103        // Remove the child package setting
11104        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11105        for (int i = 0; i < childCount; i++) {
11106            PackageParser.Package childPkg = pkg.childPackages.get(i);
11107            ps = (PackageSetting) childPkg.mExtras;
11108            if (ps != null) {
11109                removePackageLI(ps, chatty);
11110            }
11111        }
11112    }
11113
11114    void removePackageLI(PackageSetting ps, boolean chatty) {
11115        if (DEBUG_INSTALL) {
11116            if (chatty)
11117                Log.d(TAG, "Removing package " + ps.name);
11118        }
11119
11120        // writer
11121        synchronized (mPackages) {
11122            mPackages.remove(ps.name);
11123            final PackageParser.Package pkg = ps.pkg;
11124            if (pkg != null) {
11125                cleanPackageDataStructuresLILPw(pkg, chatty);
11126            }
11127        }
11128    }
11129
11130    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11131        if (DEBUG_INSTALL) {
11132            if (chatty)
11133                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11134        }
11135
11136        // writer
11137        synchronized (mPackages) {
11138            // Remove the parent package
11139            mPackages.remove(pkg.applicationInfo.packageName);
11140            cleanPackageDataStructuresLILPw(pkg, chatty);
11141
11142            // Remove the child packages
11143            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11144            for (int i = 0; i < childCount; i++) {
11145                PackageParser.Package childPkg = pkg.childPackages.get(i);
11146                mPackages.remove(childPkg.applicationInfo.packageName);
11147                cleanPackageDataStructuresLILPw(childPkg, chatty);
11148            }
11149        }
11150    }
11151
11152    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11153        int N = pkg.providers.size();
11154        StringBuilder r = null;
11155        int i;
11156        for (i=0; i<N; i++) {
11157            PackageParser.Provider p = pkg.providers.get(i);
11158            mProviders.removeProvider(p);
11159            if (p.info.authority == null) {
11160
11161                /* There was another ContentProvider with this authority when
11162                 * this app was installed so this authority is null,
11163                 * Ignore it as we don't have to unregister the provider.
11164                 */
11165                continue;
11166            }
11167            String names[] = p.info.authority.split(";");
11168            for (int j = 0; j < names.length; j++) {
11169                if (mProvidersByAuthority.get(names[j]) == p) {
11170                    mProvidersByAuthority.remove(names[j]);
11171                    if (DEBUG_REMOVE) {
11172                        if (chatty)
11173                            Log.d(TAG, "Unregistered content provider: " + names[j]
11174                                    + ", className = " + p.info.name + ", isSyncable = "
11175                                    + p.info.isSyncable);
11176                    }
11177                }
11178            }
11179            if (DEBUG_REMOVE && chatty) {
11180                if (r == null) {
11181                    r = new StringBuilder(256);
11182                } else {
11183                    r.append(' ');
11184                }
11185                r.append(p.info.name);
11186            }
11187        }
11188        if (r != null) {
11189            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11190        }
11191
11192        N = pkg.services.size();
11193        r = null;
11194        for (i=0; i<N; i++) {
11195            PackageParser.Service s = pkg.services.get(i);
11196            mServices.removeService(s);
11197            if (chatty) {
11198                if (r == null) {
11199                    r = new StringBuilder(256);
11200                } else {
11201                    r.append(' ');
11202                }
11203                r.append(s.info.name);
11204            }
11205        }
11206        if (r != null) {
11207            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11208        }
11209
11210        N = pkg.receivers.size();
11211        r = null;
11212        for (i=0; i<N; i++) {
11213            PackageParser.Activity a = pkg.receivers.get(i);
11214            mReceivers.removeActivity(a, "receiver");
11215            if (DEBUG_REMOVE && chatty) {
11216                if (r == null) {
11217                    r = new StringBuilder(256);
11218                } else {
11219                    r.append(' ');
11220                }
11221                r.append(a.info.name);
11222            }
11223        }
11224        if (r != null) {
11225            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11226        }
11227
11228        N = pkg.activities.size();
11229        r = null;
11230        for (i=0; i<N; i++) {
11231            PackageParser.Activity a = pkg.activities.get(i);
11232            mActivities.removeActivity(a, "activity");
11233            if (DEBUG_REMOVE && chatty) {
11234                if (r == null) {
11235                    r = new StringBuilder(256);
11236                } else {
11237                    r.append(' ');
11238                }
11239                r.append(a.info.name);
11240            }
11241        }
11242        if (r != null) {
11243            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11244        }
11245
11246        N = pkg.permissions.size();
11247        r = null;
11248        for (i=0; i<N; i++) {
11249            PackageParser.Permission p = pkg.permissions.get(i);
11250            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11251            if (bp == null) {
11252                bp = mSettings.mPermissionTrees.get(p.info.name);
11253            }
11254            if (bp != null && bp.perm == p) {
11255                bp.perm = null;
11256                if (DEBUG_REMOVE && chatty) {
11257                    if (r == null) {
11258                        r = new StringBuilder(256);
11259                    } else {
11260                        r.append(' ');
11261                    }
11262                    r.append(p.info.name);
11263                }
11264            }
11265            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11266                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11267                if (appOpPkgs != null) {
11268                    appOpPkgs.remove(pkg.packageName);
11269                }
11270            }
11271        }
11272        if (r != null) {
11273            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11274        }
11275
11276        N = pkg.requestedPermissions.size();
11277        r = null;
11278        for (i=0; i<N; i++) {
11279            String perm = pkg.requestedPermissions.get(i);
11280            BasePermission bp = mSettings.mPermissions.get(perm);
11281            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11282                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11283                if (appOpPkgs != null) {
11284                    appOpPkgs.remove(pkg.packageName);
11285                    if (appOpPkgs.isEmpty()) {
11286                        mAppOpPermissionPackages.remove(perm);
11287                    }
11288                }
11289            }
11290        }
11291        if (r != null) {
11292            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11293        }
11294
11295        N = pkg.instrumentation.size();
11296        r = null;
11297        for (i=0; i<N; i++) {
11298            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11299            mInstrumentation.remove(a.getComponentName());
11300            if (DEBUG_REMOVE && chatty) {
11301                if (r == null) {
11302                    r = new StringBuilder(256);
11303                } else {
11304                    r.append(' ');
11305                }
11306                r.append(a.info.name);
11307            }
11308        }
11309        if (r != null) {
11310            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11311        }
11312
11313        r = null;
11314        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11315            // Only system apps can hold shared libraries.
11316            if (pkg.libraryNames != null) {
11317                for (i = 0; i < pkg.libraryNames.size(); i++) {
11318                    String name = pkg.libraryNames.get(i);
11319                    if (removeSharedLibraryLPw(name, 0)) {
11320                        if (DEBUG_REMOVE && chatty) {
11321                            if (r == null) {
11322                                r = new StringBuilder(256);
11323                            } else {
11324                                r.append(' ');
11325                            }
11326                            r.append(name);
11327                        }
11328                    }
11329                }
11330            }
11331        }
11332
11333        r = null;
11334
11335        // Any package can hold static shared libraries.
11336        if (pkg.staticSharedLibName != null) {
11337            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11338                if (DEBUG_REMOVE && chatty) {
11339                    if (r == null) {
11340                        r = new StringBuilder(256);
11341                    } else {
11342                        r.append(' ');
11343                    }
11344                    r.append(pkg.staticSharedLibName);
11345                }
11346            }
11347        }
11348
11349        if (r != null) {
11350            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11351        }
11352    }
11353
11354    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11355        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11356            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11357                return true;
11358            }
11359        }
11360        return false;
11361    }
11362
11363    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11364    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11365    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11366
11367    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11368        // Update the parent permissions
11369        updatePermissionsLPw(pkg.packageName, pkg, flags);
11370        // Update the child permissions
11371        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11372        for (int i = 0; i < childCount; i++) {
11373            PackageParser.Package childPkg = pkg.childPackages.get(i);
11374            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11375        }
11376    }
11377
11378    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11379            int flags) {
11380        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11381        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11382    }
11383
11384    private void updatePermissionsLPw(String changingPkg,
11385            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11386        // Make sure there are no dangling permission trees.
11387        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11388        while (it.hasNext()) {
11389            final BasePermission bp = it.next();
11390            if (bp.packageSetting == null) {
11391                // We may not yet have parsed the package, so just see if
11392                // we still know about its settings.
11393                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11394            }
11395            if (bp.packageSetting == null) {
11396                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11397                        + " from package " + bp.sourcePackage);
11398                it.remove();
11399            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11400                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11401                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11402                            + " from package " + bp.sourcePackage);
11403                    flags |= UPDATE_PERMISSIONS_ALL;
11404                    it.remove();
11405                }
11406            }
11407        }
11408
11409        // Make sure all dynamic permissions have been assigned to a package,
11410        // and make sure there are no dangling permissions.
11411        it = mSettings.mPermissions.values().iterator();
11412        while (it.hasNext()) {
11413            final BasePermission bp = it.next();
11414            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11415                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11416                        + bp.name + " pkg=" + bp.sourcePackage
11417                        + " info=" + bp.pendingInfo);
11418                if (bp.packageSetting == null && bp.pendingInfo != null) {
11419                    final BasePermission tree = findPermissionTreeLP(bp.name);
11420                    if (tree != null && tree.perm != null) {
11421                        bp.packageSetting = tree.packageSetting;
11422                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11423                                new PermissionInfo(bp.pendingInfo));
11424                        bp.perm.info.packageName = tree.perm.info.packageName;
11425                        bp.perm.info.name = bp.name;
11426                        bp.uid = tree.uid;
11427                    }
11428                }
11429            }
11430            if (bp.packageSetting == null) {
11431                // We may not yet have parsed the package, so just see if
11432                // we still know about its settings.
11433                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11434            }
11435            if (bp.packageSetting == null) {
11436                Slog.w(TAG, "Removing dangling permission: " + bp.name
11437                        + " from package " + bp.sourcePackage);
11438                it.remove();
11439            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11440                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11441                    Slog.i(TAG, "Removing old permission: " + bp.name
11442                            + " from package " + bp.sourcePackage);
11443                    flags |= UPDATE_PERMISSIONS_ALL;
11444                    it.remove();
11445                }
11446            }
11447        }
11448
11449        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11450        // Now update the permissions for all packages, in particular
11451        // replace the granted permissions of the system packages.
11452        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11453            for (PackageParser.Package pkg : mPackages.values()) {
11454                if (pkg != pkgInfo) {
11455                    // Only replace for packages on requested volume
11456                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11457                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11458                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11459                    grantPermissionsLPw(pkg, replace, changingPkg);
11460                }
11461            }
11462        }
11463
11464        if (pkgInfo != null) {
11465            // Only replace for packages on requested volume
11466            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11467            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11468                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11469            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11470        }
11471        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11472    }
11473
11474    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11475            String packageOfInterest) {
11476        // IMPORTANT: There are two types of permissions: install and runtime.
11477        // Install time permissions are granted when the app is installed to
11478        // all device users and users added in the future. Runtime permissions
11479        // are granted at runtime explicitly to specific users. Normal and signature
11480        // protected permissions are install time permissions. Dangerous permissions
11481        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11482        // otherwise they are runtime permissions. This function does not manage
11483        // runtime permissions except for the case an app targeting Lollipop MR1
11484        // being upgraded to target a newer SDK, in which case dangerous permissions
11485        // are transformed from install time to runtime ones.
11486
11487        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11488        if (ps == null) {
11489            return;
11490        }
11491
11492        PermissionsState permissionsState = ps.getPermissionsState();
11493        PermissionsState origPermissions = permissionsState;
11494
11495        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11496
11497        boolean runtimePermissionsRevoked = false;
11498        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11499
11500        boolean changedInstallPermission = false;
11501
11502        if (replace) {
11503            ps.installPermissionsFixed = false;
11504            if (!ps.isSharedUser()) {
11505                origPermissions = new PermissionsState(permissionsState);
11506                permissionsState.reset();
11507            } else {
11508                // We need to know only about runtime permission changes since the
11509                // calling code always writes the install permissions state but
11510                // the runtime ones are written only if changed. The only cases of
11511                // changed runtime permissions here are promotion of an install to
11512                // runtime and revocation of a runtime from a shared user.
11513                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11514                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11515                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11516                    runtimePermissionsRevoked = true;
11517                }
11518            }
11519        }
11520
11521        permissionsState.setGlobalGids(mGlobalGids);
11522
11523        final int N = pkg.requestedPermissions.size();
11524        for (int i=0; i<N; i++) {
11525            final String name = pkg.requestedPermissions.get(i);
11526            final BasePermission bp = mSettings.mPermissions.get(name);
11527            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11528                    >= Build.VERSION_CODES.M;
11529
11530            if (DEBUG_INSTALL) {
11531                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11532            }
11533
11534            if (bp == null || bp.packageSetting == null) {
11535                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11536                    Slog.w(TAG, "Unknown permission " + name
11537                            + " in package " + pkg.packageName);
11538                }
11539                continue;
11540            }
11541
11542
11543            // Limit ephemeral apps to ephemeral allowed permissions.
11544            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11545                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11546                        + pkg.packageName);
11547                continue;
11548            }
11549
11550            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
11551                Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
11552                        + pkg.packageName);
11553                continue;
11554            }
11555
11556            final String perm = bp.name;
11557            boolean allowedSig = false;
11558            int grant = GRANT_DENIED;
11559
11560            // Keep track of app op permissions.
11561            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11562                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11563                if (pkgs == null) {
11564                    pkgs = new ArraySet<>();
11565                    mAppOpPermissionPackages.put(bp.name, pkgs);
11566                }
11567                pkgs.add(pkg.packageName);
11568            }
11569
11570            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11571            switch (level) {
11572                case PermissionInfo.PROTECTION_NORMAL: {
11573                    // For all apps normal permissions are install time ones.
11574                    grant = GRANT_INSTALL;
11575                } break;
11576
11577                case PermissionInfo.PROTECTION_DANGEROUS: {
11578                    // If a permission review is required for legacy apps we represent
11579                    // their permissions as always granted runtime ones since we need
11580                    // to keep the review required permission flag per user while an
11581                    // install permission's state is shared across all users.
11582                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11583                        // For legacy apps dangerous permissions are install time ones.
11584                        grant = GRANT_INSTALL;
11585                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11586                        // For legacy apps that became modern, install becomes runtime.
11587                        grant = GRANT_UPGRADE;
11588                    } else if (mPromoteSystemApps
11589                            && isSystemApp(ps)
11590                            && mExistingSystemPackages.contains(ps.name)) {
11591                        // For legacy system apps, install becomes runtime.
11592                        // We cannot check hasInstallPermission() for system apps since those
11593                        // permissions were granted implicitly and not persisted pre-M.
11594                        grant = GRANT_UPGRADE;
11595                    } else {
11596                        // For modern apps keep runtime permissions unchanged.
11597                        grant = GRANT_RUNTIME;
11598                    }
11599                } break;
11600
11601                case PermissionInfo.PROTECTION_SIGNATURE: {
11602                    // For all apps signature permissions are install time ones.
11603                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11604                    if (allowedSig) {
11605                        grant = GRANT_INSTALL;
11606                    }
11607                } break;
11608            }
11609
11610            if (DEBUG_INSTALL) {
11611                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11612            }
11613
11614            if (grant != GRANT_DENIED) {
11615                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11616                    // If this is an existing, non-system package, then
11617                    // we can't add any new permissions to it.
11618                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11619                        // Except...  if this is a permission that was added
11620                        // to the platform (note: need to only do this when
11621                        // updating the platform).
11622                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11623                            grant = GRANT_DENIED;
11624                        }
11625                    }
11626                }
11627
11628                switch (grant) {
11629                    case GRANT_INSTALL: {
11630                        // Revoke this as runtime permission to handle the case of
11631                        // a runtime permission being downgraded to an install one.
11632                        // Also in permission review mode we keep dangerous permissions
11633                        // for legacy apps
11634                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11635                            if (origPermissions.getRuntimePermissionState(
11636                                    bp.name, userId) != null) {
11637                                // Revoke the runtime permission and clear the flags.
11638                                origPermissions.revokeRuntimePermission(bp, userId);
11639                                origPermissions.updatePermissionFlags(bp, userId,
11640                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11641                                // If we revoked a permission permission, we have to write.
11642                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11643                                        changedRuntimePermissionUserIds, userId);
11644                            }
11645                        }
11646                        // Grant an install permission.
11647                        if (permissionsState.grantInstallPermission(bp) !=
11648                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11649                            changedInstallPermission = true;
11650                        }
11651                    } break;
11652
11653                    case GRANT_RUNTIME: {
11654                        // Grant previously granted runtime permissions.
11655                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11656                            PermissionState permissionState = origPermissions
11657                                    .getRuntimePermissionState(bp.name, userId);
11658                            int flags = permissionState != null
11659                                    ? permissionState.getFlags() : 0;
11660                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11661                                // Don't propagate the permission in a permission review mode if
11662                                // the former was revoked, i.e. marked to not propagate on upgrade.
11663                                // Note that in a permission review mode install permissions are
11664                                // represented as constantly granted runtime ones since we need to
11665                                // keep a per user state associated with the permission. Also the
11666                                // revoke on upgrade flag is no longer applicable and is reset.
11667                                final boolean revokeOnUpgrade = (flags & PackageManager
11668                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11669                                if (revokeOnUpgrade) {
11670                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11671                                    // Since we changed the flags, we have to write.
11672                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11673                                            changedRuntimePermissionUserIds, userId);
11674                                }
11675                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11676                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11677                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11678                                        // If we cannot put the permission as it was,
11679                                        // we have to write.
11680                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11681                                                changedRuntimePermissionUserIds, userId);
11682                                    }
11683                                }
11684
11685                                // If the app supports runtime permissions no need for a review.
11686                                if (mPermissionReviewRequired
11687                                        && appSupportsRuntimePermissions
11688                                        && (flags & PackageManager
11689                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11690                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11691                                    // Since we changed the flags, we have to write.
11692                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11693                                            changedRuntimePermissionUserIds, userId);
11694                                }
11695                            } else if (mPermissionReviewRequired
11696                                    && !appSupportsRuntimePermissions) {
11697                                // For legacy apps that need a permission review, every new
11698                                // runtime permission is granted but it is pending a review.
11699                                // We also need to review only platform defined runtime
11700                                // permissions as these are the only ones the platform knows
11701                                // how to disable the API to simulate revocation as legacy
11702                                // apps don't expect to run with revoked permissions.
11703                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11704                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11705                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11706                                        // We changed the flags, hence have to write.
11707                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11708                                                changedRuntimePermissionUserIds, userId);
11709                                    }
11710                                }
11711                                if (permissionsState.grantRuntimePermission(bp, userId)
11712                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11713                                    // We changed the permission, hence have to write.
11714                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11715                                            changedRuntimePermissionUserIds, userId);
11716                                }
11717                            }
11718                            // Propagate the permission flags.
11719                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11720                        }
11721                    } break;
11722
11723                    case GRANT_UPGRADE: {
11724                        // Grant runtime permissions for a previously held install permission.
11725                        PermissionState permissionState = origPermissions
11726                                .getInstallPermissionState(bp.name);
11727                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11728
11729                        if (origPermissions.revokeInstallPermission(bp)
11730                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11731                            // We will be transferring the permission flags, so clear them.
11732                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11733                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11734                            changedInstallPermission = true;
11735                        }
11736
11737                        // If the permission is not to be promoted to runtime we ignore it and
11738                        // also its other flags as they are not applicable to install permissions.
11739                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11740                            for (int userId : currentUserIds) {
11741                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11742                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11743                                    // Transfer the permission flags.
11744                                    permissionsState.updatePermissionFlags(bp, userId,
11745                                            flags, flags);
11746                                    // If we granted the permission, we have to write.
11747                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11748                                            changedRuntimePermissionUserIds, userId);
11749                                }
11750                            }
11751                        }
11752                    } break;
11753
11754                    default: {
11755                        if (packageOfInterest == null
11756                                || packageOfInterest.equals(pkg.packageName)) {
11757                            Slog.w(TAG, "Not granting permission " + perm
11758                                    + " to package " + pkg.packageName
11759                                    + " because it was previously installed without");
11760                        }
11761                    } break;
11762                }
11763            } else {
11764                if (permissionsState.revokeInstallPermission(bp) !=
11765                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11766                    // Also drop the permission flags.
11767                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11768                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11769                    changedInstallPermission = true;
11770                    Slog.i(TAG, "Un-granting permission " + perm
11771                            + " from package " + pkg.packageName
11772                            + " (protectionLevel=" + bp.protectionLevel
11773                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11774                            + ")");
11775                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11776                    // Don't print warning for app op permissions, since it is fine for them
11777                    // not to be granted, there is a UI for the user to decide.
11778                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11779                        Slog.w(TAG, "Not granting permission " + perm
11780                                + " to package " + pkg.packageName
11781                                + " (protectionLevel=" + bp.protectionLevel
11782                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11783                                + ")");
11784                    }
11785                }
11786            }
11787        }
11788
11789        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11790                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11791            // This is the first that we have heard about this package, so the
11792            // permissions we have now selected are fixed until explicitly
11793            // changed.
11794            ps.installPermissionsFixed = true;
11795        }
11796
11797        // Persist the runtime permissions state for users with changes. If permissions
11798        // were revoked because no app in the shared user declares them we have to
11799        // write synchronously to avoid losing runtime permissions state.
11800        for (int userId : changedRuntimePermissionUserIds) {
11801            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11802        }
11803    }
11804
11805    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11806        boolean allowed = false;
11807        final int NP = PackageParser.NEW_PERMISSIONS.length;
11808        for (int ip=0; ip<NP; ip++) {
11809            final PackageParser.NewPermissionInfo npi
11810                    = PackageParser.NEW_PERMISSIONS[ip];
11811            if (npi.name.equals(perm)
11812                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11813                allowed = true;
11814                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11815                        + pkg.packageName);
11816                break;
11817            }
11818        }
11819        return allowed;
11820    }
11821
11822    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11823            BasePermission bp, PermissionsState origPermissions) {
11824        boolean privilegedPermission = (bp.protectionLevel
11825                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11826        boolean privappPermissionsDisable =
11827                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11828        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11829        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11830        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11831                && !platformPackage && platformPermission) {
11832            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11833                    .getPrivAppPermissions(pkg.packageName);
11834            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11835            if (!whitelisted) {
11836                Slog.w(TAG, "Privileged permission " + perm + " for package "
11837                        + pkg.packageName + " - not in privapp-permissions whitelist");
11838                // Only report violations for apps on system image
11839                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11840                    if (mPrivappPermissionsViolations == null) {
11841                        mPrivappPermissionsViolations = new ArraySet<>();
11842                    }
11843                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11844                }
11845                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11846                    return false;
11847                }
11848            }
11849        }
11850        boolean allowed = (compareSignatures(
11851                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11852                        == PackageManager.SIGNATURE_MATCH)
11853                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11854                        == PackageManager.SIGNATURE_MATCH);
11855        if (!allowed && privilegedPermission) {
11856            if (isSystemApp(pkg)) {
11857                // For updated system applications, a system permission
11858                // is granted only if it had been defined by the original application.
11859                if (pkg.isUpdatedSystemApp()) {
11860                    final PackageSetting sysPs = mSettings
11861                            .getDisabledSystemPkgLPr(pkg.packageName);
11862                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11863                        // If the original was granted this permission, we take
11864                        // that grant decision as read and propagate it to the
11865                        // update.
11866                        if (sysPs.isPrivileged()) {
11867                            allowed = true;
11868                        }
11869                    } else {
11870                        // The system apk may have been updated with an older
11871                        // version of the one on the data partition, but which
11872                        // granted a new system permission that it didn't have
11873                        // before.  In this case we do want to allow the app to
11874                        // now get the new permission if the ancestral apk is
11875                        // privileged to get it.
11876                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11877                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11878                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11879                                    allowed = true;
11880                                    break;
11881                                }
11882                            }
11883                        }
11884                        // Also if a privileged parent package on the system image or any of
11885                        // its children requested a privileged permission, the updated child
11886                        // packages can also get the permission.
11887                        if (pkg.parentPackage != null) {
11888                            final PackageSetting disabledSysParentPs = mSettings
11889                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11890                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11891                                    && disabledSysParentPs.isPrivileged()) {
11892                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11893                                    allowed = true;
11894                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11895                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11896                                    for (int i = 0; i < count; i++) {
11897                                        PackageParser.Package disabledSysChildPkg =
11898                                                disabledSysParentPs.pkg.childPackages.get(i);
11899                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11900                                                perm)) {
11901                                            allowed = true;
11902                                            break;
11903                                        }
11904                                    }
11905                                }
11906                            }
11907                        }
11908                    }
11909                } else {
11910                    allowed = isPrivilegedApp(pkg);
11911                }
11912            }
11913        }
11914        if (!allowed) {
11915            if (!allowed && (bp.protectionLevel
11916                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11917                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11918                // If this was a previously normal/dangerous permission that got moved
11919                // to a system permission as part of the runtime permission redesign, then
11920                // we still want to blindly grant it to old apps.
11921                allowed = true;
11922            }
11923            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11924                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11925                // If this permission is to be granted to the system installer and
11926                // this app is an installer, then it gets the permission.
11927                allowed = true;
11928            }
11929            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11930                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11931                // If this permission is to be granted to the system verifier and
11932                // this app is a verifier, then it gets the permission.
11933                allowed = true;
11934            }
11935            if (!allowed && (bp.protectionLevel
11936                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11937                    && isSystemApp(pkg)) {
11938                // Any pre-installed system app is allowed to get this permission.
11939                allowed = true;
11940            }
11941            if (!allowed && (bp.protectionLevel
11942                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11943                // For development permissions, a development permission
11944                // is granted only if it was already granted.
11945                allowed = origPermissions.hasInstallPermission(perm);
11946            }
11947            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11948                    && pkg.packageName.equals(mSetupWizardPackage)) {
11949                // If this permission is to be granted to the system setup wizard and
11950                // this app is a setup wizard, then it gets the permission.
11951                allowed = true;
11952            }
11953        }
11954        return allowed;
11955    }
11956
11957    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11958        final int permCount = pkg.requestedPermissions.size();
11959        for (int j = 0; j < permCount; j++) {
11960            String requestedPermission = pkg.requestedPermissions.get(j);
11961            if (permission.equals(requestedPermission)) {
11962                return true;
11963            }
11964        }
11965        return false;
11966    }
11967
11968    final class ActivityIntentResolver
11969            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11970        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11971                boolean defaultOnly, int userId) {
11972            if (!sUserManager.exists(userId)) return null;
11973            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11974            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11975        }
11976
11977        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11978                int userId) {
11979            if (!sUserManager.exists(userId)) return null;
11980            mFlags = flags;
11981            return super.queryIntent(intent, resolvedType,
11982                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11983                    userId);
11984        }
11985
11986        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11987                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11988            if (!sUserManager.exists(userId)) return null;
11989            if (packageActivities == null) {
11990                return null;
11991            }
11992            mFlags = flags;
11993            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11994            final int N = packageActivities.size();
11995            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11996                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11997
11998            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11999            for (int i = 0; i < N; ++i) {
12000                intentFilters = packageActivities.get(i).intents;
12001                if (intentFilters != null && intentFilters.size() > 0) {
12002                    PackageParser.ActivityIntentInfo[] array =
12003                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12004                    intentFilters.toArray(array);
12005                    listCut.add(array);
12006                }
12007            }
12008            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12009        }
12010
12011        /**
12012         * Finds a privileged activity that matches the specified activity names.
12013         */
12014        private PackageParser.Activity findMatchingActivity(
12015                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12016            for (PackageParser.Activity sysActivity : activityList) {
12017                if (sysActivity.info.name.equals(activityInfo.name)) {
12018                    return sysActivity;
12019                }
12020                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12021                    return sysActivity;
12022                }
12023                if (sysActivity.info.targetActivity != null) {
12024                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12025                        return sysActivity;
12026                    }
12027                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12028                        return sysActivity;
12029                    }
12030                }
12031            }
12032            return null;
12033        }
12034
12035        public class IterGenerator<E> {
12036            public Iterator<E> generate(ActivityIntentInfo info) {
12037                return null;
12038            }
12039        }
12040
12041        public class ActionIterGenerator extends IterGenerator<String> {
12042            @Override
12043            public Iterator<String> generate(ActivityIntentInfo info) {
12044                return info.actionsIterator();
12045            }
12046        }
12047
12048        public class CategoriesIterGenerator extends IterGenerator<String> {
12049            @Override
12050            public Iterator<String> generate(ActivityIntentInfo info) {
12051                return info.categoriesIterator();
12052            }
12053        }
12054
12055        public class SchemesIterGenerator extends IterGenerator<String> {
12056            @Override
12057            public Iterator<String> generate(ActivityIntentInfo info) {
12058                return info.schemesIterator();
12059            }
12060        }
12061
12062        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12063            @Override
12064            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12065                return info.authoritiesIterator();
12066            }
12067        }
12068
12069        /**
12070         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12071         * MODIFIED. Do not pass in a list that should not be changed.
12072         */
12073        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12074                IterGenerator<T> generator, Iterator<T> searchIterator) {
12075            // loop through the set of actions; every one must be found in the intent filter
12076            while (searchIterator.hasNext()) {
12077                // we must have at least one filter in the list to consider a match
12078                if (intentList.size() == 0) {
12079                    break;
12080                }
12081
12082                final T searchAction = searchIterator.next();
12083
12084                // loop through the set of intent filters
12085                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12086                while (intentIter.hasNext()) {
12087                    final ActivityIntentInfo intentInfo = intentIter.next();
12088                    boolean selectionFound = false;
12089
12090                    // loop through the intent filter's selection criteria; at least one
12091                    // of them must match the searched criteria
12092                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12093                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12094                        final T intentSelection = intentSelectionIter.next();
12095                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12096                            selectionFound = true;
12097                            break;
12098                        }
12099                    }
12100
12101                    // the selection criteria wasn't found in this filter's set; this filter
12102                    // is not a potential match
12103                    if (!selectionFound) {
12104                        intentIter.remove();
12105                    }
12106                }
12107            }
12108        }
12109
12110        private boolean isProtectedAction(ActivityIntentInfo filter) {
12111            final Iterator<String> actionsIter = filter.actionsIterator();
12112            while (actionsIter != null && actionsIter.hasNext()) {
12113                final String filterAction = actionsIter.next();
12114                if (PROTECTED_ACTIONS.contains(filterAction)) {
12115                    return true;
12116                }
12117            }
12118            return false;
12119        }
12120
12121        /**
12122         * Adjusts the priority of the given intent filter according to policy.
12123         * <p>
12124         * <ul>
12125         * <li>The priority for non privileged applications is capped to '0'</li>
12126         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12127         * <li>The priority for unbundled updates to privileged applications is capped to the
12128         *      priority defined on the system partition</li>
12129         * </ul>
12130         * <p>
12131         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12132         * allowed to obtain any priority on any action.
12133         */
12134        private void adjustPriority(
12135                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12136            // nothing to do; priority is fine as-is
12137            if (intent.getPriority() <= 0) {
12138                return;
12139            }
12140
12141            final ActivityInfo activityInfo = intent.activity.info;
12142            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12143
12144            final boolean privilegedApp =
12145                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12146            if (!privilegedApp) {
12147                // non-privileged applications can never define a priority >0
12148                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12149                        + " package: " + applicationInfo.packageName
12150                        + " activity: " + intent.activity.className
12151                        + " origPrio: " + intent.getPriority());
12152                intent.setPriority(0);
12153                return;
12154            }
12155
12156            if (systemActivities == null) {
12157                // the system package is not disabled; we're parsing the system partition
12158                if (isProtectedAction(intent)) {
12159                    if (mDeferProtectedFilters) {
12160                        // We can't deal with these just yet. No component should ever obtain a
12161                        // >0 priority for a protected actions, with ONE exception -- the setup
12162                        // wizard. The setup wizard, however, cannot be known until we're able to
12163                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12164                        // until all intent filters have been processed. Chicken, meet egg.
12165                        // Let the filter temporarily have a high priority and rectify the
12166                        // priorities after all system packages have been scanned.
12167                        mProtectedFilters.add(intent);
12168                        if (DEBUG_FILTERS) {
12169                            Slog.i(TAG, "Protected action; save for later;"
12170                                    + " package: " + applicationInfo.packageName
12171                                    + " activity: " + intent.activity.className
12172                                    + " origPrio: " + intent.getPriority());
12173                        }
12174                        return;
12175                    } else {
12176                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12177                            Slog.i(TAG, "No setup wizard;"
12178                                + " All protected intents capped to priority 0");
12179                        }
12180                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12181                            if (DEBUG_FILTERS) {
12182                                Slog.i(TAG, "Found setup wizard;"
12183                                    + " allow priority " + intent.getPriority() + ";"
12184                                    + " package: " + intent.activity.info.packageName
12185                                    + " activity: " + intent.activity.className
12186                                    + " priority: " + intent.getPriority());
12187                            }
12188                            // setup wizard gets whatever it wants
12189                            return;
12190                        }
12191                        Slog.w(TAG, "Protected action; cap priority to 0;"
12192                                + " package: " + intent.activity.info.packageName
12193                                + " activity: " + intent.activity.className
12194                                + " origPrio: " + intent.getPriority());
12195                        intent.setPriority(0);
12196                        return;
12197                    }
12198                }
12199                // privileged apps on the system image get whatever priority they request
12200                return;
12201            }
12202
12203            // privileged app unbundled update ... try to find the same activity
12204            final PackageParser.Activity foundActivity =
12205                    findMatchingActivity(systemActivities, activityInfo);
12206            if (foundActivity == null) {
12207                // this is a new activity; it cannot obtain >0 priority
12208                if (DEBUG_FILTERS) {
12209                    Slog.i(TAG, "New activity; cap priority to 0;"
12210                            + " package: " + applicationInfo.packageName
12211                            + " activity: " + intent.activity.className
12212                            + " origPrio: " + intent.getPriority());
12213                }
12214                intent.setPriority(0);
12215                return;
12216            }
12217
12218            // found activity, now check for filter equivalence
12219
12220            // a shallow copy is enough; we modify the list, not its contents
12221            final List<ActivityIntentInfo> intentListCopy =
12222                    new ArrayList<>(foundActivity.intents);
12223            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12224
12225            // find matching action subsets
12226            final Iterator<String> actionsIterator = intent.actionsIterator();
12227            if (actionsIterator != null) {
12228                getIntentListSubset(
12229                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12230                if (intentListCopy.size() == 0) {
12231                    // no more intents to match; we're not equivalent
12232                    if (DEBUG_FILTERS) {
12233                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12234                                + " package: " + applicationInfo.packageName
12235                                + " activity: " + intent.activity.className
12236                                + " origPrio: " + intent.getPriority());
12237                    }
12238                    intent.setPriority(0);
12239                    return;
12240                }
12241            }
12242
12243            // find matching category subsets
12244            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12245            if (categoriesIterator != null) {
12246                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12247                        categoriesIterator);
12248                if (intentListCopy.size() == 0) {
12249                    // no more intents to match; we're not equivalent
12250                    if (DEBUG_FILTERS) {
12251                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12252                                + " package: " + applicationInfo.packageName
12253                                + " activity: " + intent.activity.className
12254                                + " origPrio: " + intent.getPriority());
12255                    }
12256                    intent.setPriority(0);
12257                    return;
12258                }
12259            }
12260
12261            // find matching schemes subsets
12262            final Iterator<String> schemesIterator = intent.schemesIterator();
12263            if (schemesIterator != null) {
12264                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12265                        schemesIterator);
12266                if (intentListCopy.size() == 0) {
12267                    // no more intents to match; we're not equivalent
12268                    if (DEBUG_FILTERS) {
12269                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12270                                + " package: " + applicationInfo.packageName
12271                                + " activity: " + intent.activity.className
12272                                + " origPrio: " + intent.getPriority());
12273                    }
12274                    intent.setPriority(0);
12275                    return;
12276                }
12277            }
12278
12279            // find matching authorities subsets
12280            final Iterator<IntentFilter.AuthorityEntry>
12281                    authoritiesIterator = intent.authoritiesIterator();
12282            if (authoritiesIterator != null) {
12283                getIntentListSubset(intentListCopy,
12284                        new AuthoritiesIterGenerator(),
12285                        authoritiesIterator);
12286                if (intentListCopy.size() == 0) {
12287                    // no more intents to match; we're not equivalent
12288                    if (DEBUG_FILTERS) {
12289                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12290                                + " package: " + applicationInfo.packageName
12291                                + " activity: " + intent.activity.className
12292                                + " origPrio: " + intent.getPriority());
12293                    }
12294                    intent.setPriority(0);
12295                    return;
12296                }
12297            }
12298
12299            // we found matching filter(s); app gets the max priority of all intents
12300            int cappedPriority = 0;
12301            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12302                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12303            }
12304            if (intent.getPriority() > cappedPriority) {
12305                if (DEBUG_FILTERS) {
12306                    Slog.i(TAG, "Found matching filter(s);"
12307                            + " cap priority to " + cappedPriority + ";"
12308                            + " package: " + applicationInfo.packageName
12309                            + " activity: " + intent.activity.className
12310                            + " origPrio: " + intent.getPriority());
12311                }
12312                intent.setPriority(cappedPriority);
12313                return;
12314            }
12315            // all this for nothing; the requested priority was <= what was on the system
12316        }
12317
12318        public final void addActivity(PackageParser.Activity a, String type) {
12319            mActivities.put(a.getComponentName(), a);
12320            if (DEBUG_SHOW_INFO)
12321                Log.v(
12322                TAG, "  " + type + " " +
12323                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12324            if (DEBUG_SHOW_INFO)
12325                Log.v(TAG, "    Class=" + a.info.name);
12326            final int NI = a.intents.size();
12327            for (int j=0; j<NI; j++) {
12328                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12329                if ("activity".equals(type)) {
12330                    final PackageSetting ps =
12331                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12332                    final List<PackageParser.Activity> systemActivities =
12333                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12334                    adjustPriority(systemActivities, intent);
12335                }
12336                if (DEBUG_SHOW_INFO) {
12337                    Log.v(TAG, "    IntentFilter:");
12338                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12339                }
12340                if (!intent.debugCheck()) {
12341                    Log.w(TAG, "==> For Activity " + a.info.name);
12342                }
12343                addFilter(intent);
12344            }
12345        }
12346
12347        public final void removeActivity(PackageParser.Activity a, String type) {
12348            mActivities.remove(a.getComponentName());
12349            if (DEBUG_SHOW_INFO) {
12350                Log.v(TAG, "  " + type + " "
12351                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12352                                : a.info.name) + ":");
12353                Log.v(TAG, "    Class=" + a.info.name);
12354            }
12355            final int NI = a.intents.size();
12356            for (int j=0; j<NI; j++) {
12357                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12358                if (DEBUG_SHOW_INFO) {
12359                    Log.v(TAG, "    IntentFilter:");
12360                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12361                }
12362                removeFilter(intent);
12363            }
12364        }
12365
12366        @Override
12367        protected boolean allowFilterResult(
12368                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12369            ActivityInfo filterAi = filter.activity.info;
12370            for (int i=dest.size()-1; i>=0; i--) {
12371                ActivityInfo destAi = dest.get(i).activityInfo;
12372                if (destAi.name == filterAi.name
12373                        && destAi.packageName == filterAi.packageName) {
12374                    return false;
12375                }
12376            }
12377            return true;
12378        }
12379
12380        @Override
12381        protected ActivityIntentInfo[] newArray(int size) {
12382            return new ActivityIntentInfo[size];
12383        }
12384
12385        @Override
12386        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12387            if (!sUserManager.exists(userId)) return true;
12388            PackageParser.Package p = filter.activity.owner;
12389            if (p != null) {
12390                PackageSetting ps = (PackageSetting)p.mExtras;
12391                if (ps != null) {
12392                    // System apps are never considered stopped for purposes of
12393                    // filtering, because there may be no way for the user to
12394                    // actually re-launch them.
12395                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12396                            && ps.getStopped(userId);
12397                }
12398            }
12399            return false;
12400        }
12401
12402        @Override
12403        protected boolean isPackageForFilter(String packageName,
12404                PackageParser.ActivityIntentInfo info) {
12405            return packageName.equals(info.activity.owner.packageName);
12406        }
12407
12408        @Override
12409        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12410                int match, int userId) {
12411            if (!sUserManager.exists(userId)) return null;
12412            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12413                return null;
12414            }
12415            final PackageParser.Activity activity = info.activity;
12416            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12417            if (ps == null) {
12418                return null;
12419            }
12420            final PackageUserState userState = ps.readUserState(userId);
12421            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
12422            if (ai == null) {
12423                return null;
12424            }
12425            final boolean matchVisibleToInstantApp =
12426                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12427            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12428            // throw out filters that aren't visible to ephemeral apps
12429            if (matchVisibleToInstantApp
12430                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12431                return null;
12432            }
12433            // throw out ephemeral filters if we're not explicitly requesting them
12434            if (!isInstantApp && userState.instantApp) {
12435                return null;
12436            }
12437            // throw out instant app filters if updates are available; will trigger
12438            // instant app resolution
12439            if (userState.instantApp && ps.isUpdateAvailable()) {
12440                return null;
12441            }
12442            final ResolveInfo res = new ResolveInfo();
12443            res.activityInfo = ai;
12444            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12445                res.filter = info;
12446            }
12447            if (info != null) {
12448                res.handleAllWebDataURI = info.handleAllWebDataURI();
12449            }
12450            res.priority = info.getPriority();
12451            res.preferredOrder = activity.owner.mPreferredOrder;
12452            //System.out.println("Result: " + res.activityInfo.className +
12453            //                   " = " + res.priority);
12454            res.match = match;
12455            res.isDefault = info.hasDefault;
12456            res.labelRes = info.labelRes;
12457            res.nonLocalizedLabel = info.nonLocalizedLabel;
12458            if (userNeedsBadging(userId)) {
12459                res.noResourceId = true;
12460            } else {
12461                res.icon = info.icon;
12462            }
12463            res.iconResourceId = info.icon;
12464            res.system = res.activityInfo.applicationInfo.isSystemApp();
12465            res.instantAppAvailable = userState.instantApp;
12466            return res;
12467        }
12468
12469        @Override
12470        protected void sortResults(List<ResolveInfo> results) {
12471            Collections.sort(results, mResolvePrioritySorter);
12472        }
12473
12474        @Override
12475        protected void dumpFilter(PrintWriter out, String prefix,
12476                PackageParser.ActivityIntentInfo filter) {
12477            out.print(prefix); out.print(
12478                    Integer.toHexString(System.identityHashCode(filter.activity)));
12479                    out.print(' ');
12480                    filter.activity.printComponentShortName(out);
12481                    out.print(" filter ");
12482                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12483        }
12484
12485        @Override
12486        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12487            return filter.activity;
12488        }
12489
12490        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12491            PackageParser.Activity activity = (PackageParser.Activity)label;
12492            out.print(prefix); out.print(
12493                    Integer.toHexString(System.identityHashCode(activity)));
12494                    out.print(' ');
12495                    activity.printComponentShortName(out);
12496            if (count > 1) {
12497                out.print(" ("); out.print(count); out.print(" filters)");
12498            }
12499            out.println();
12500        }
12501
12502        // Keys are String (activity class name), values are Activity.
12503        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12504                = new ArrayMap<ComponentName, PackageParser.Activity>();
12505        private int mFlags;
12506    }
12507
12508    private final class ServiceIntentResolver
12509            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12510        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12511                boolean defaultOnly, int userId) {
12512            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12513            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12514        }
12515
12516        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12517                int userId) {
12518            if (!sUserManager.exists(userId)) return null;
12519            mFlags = flags;
12520            return super.queryIntent(intent, resolvedType,
12521                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12522                    userId);
12523        }
12524
12525        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12526                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12527            if (!sUserManager.exists(userId)) return null;
12528            if (packageServices == null) {
12529                return null;
12530            }
12531            mFlags = flags;
12532            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12533            final int N = packageServices.size();
12534            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12535                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12536
12537            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12538            for (int i = 0; i < N; ++i) {
12539                intentFilters = packageServices.get(i).intents;
12540                if (intentFilters != null && intentFilters.size() > 0) {
12541                    PackageParser.ServiceIntentInfo[] array =
12542                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12543                    intentFilters.toArray(array);
12544                    listCut.add(array);
12545                }
12546            }
12547            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12548        }
12549
12550        public final void addService(PackageParser.Service s) {
12551            mServices.put(s.getComponentName(), s);
12552            if (DEBUG_SHOW_INFO) {
12553                Log.v(TAG, "  "
12554                        + (s.info.nonLocalizedLabel != null
12555                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12556                Log.v(TAG, "    Class=" + s.info.name);
12557            }
12558            final int NI = s.intents.size();
12559            int j;
12560            for (j=0; j<NI; j++) {
12561                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12562                if (DEBUG_SHOW_INFO) {
12563                    Log.v(TAG, "    IntentFilter:");
12564                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12565                }
12566                if (!intent.debugCheck()) {
12567                    Log.w(TAG, "==> For Service " + s.info.name);
12568                }
12569                addFilter(intent);
12570            }
12571        }
12572
12573        public final void removeService(PackageParser.Service s) {
12574            mServices.remove(s.getComponentName());
12575            if (DEBUG_SHOW_INFO) {
12576                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12577                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12578                Log.v(TAG, "    Class=" + s.info.name);
12579            }
12580            final int NI = s.intents.size();
12581            int j;
12582            for (j=0; j<NI; j++) {
12583                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12584                if (DEBUG_SHOW_INFO) {
12585                    Log.v(TAG, "    IntentFilter:");
12586                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12587                }
12588                removeFilter(intent);
12589            }
12590        }
12591
12592        @Override
12593        protected boolean allowFilterResult(
12594                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12595            ServiceInfo filterSi = filter.service.info;
12596            for (int i=dest.size()-1; i>=0; i--) {
12597                ServiceInfo destAi = dest.get(i).serviceInfo;
12598                if (destAi.name == filterSi.name
12599                        && destAi.packageName == filterSi.packageName) {
12600                    return false;
12601                }
12602            }
12603            return true;
12604        }
12605
12606        @Override
12607        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12608            return new PackageParser.ServiceIntentInfo[size];
12609        }
12610
12611        @Override
12612        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12613            if (!sUserManager.exists(userId)) return true;
12614            PackageParser.Package p = filter.service.owner;
12615            if (p != null) {
12616                PackageSetting ps = (PackageSetting)p.mExtras;
12617                if (ps != null) {
12618                    // System apps are never considered stopped for purposes of
12619                    // filtering, because there may be no way for the user to
12620                    // actually re-launch them.
12621                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12622                            && ps.getStopped(userId);
12623                }
12624            }
12625            return false;
12626        }
12627
12628        @Override
12629        protected boolean isPackageForFilter(String packageName,
12630                PackageParser.ServiceIntentInfo info) {
12631            return packageName.equals(info.service.owner.packageName);
12632        }
12633
12634        @Override
12635        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12636                int match, int userId) {
12637            if (!sUserManager.exists(userId)) return null;
12638            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12639            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12640                return null;
12641            }
12642            final PackageParser.Service service = info.service;
12643            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12644            if (ps == null) {
12645                return null;
12646            }
12647            final PackageUserState userState = ps.readUserState(userId);
12648            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12649                    userState, userId);
12650            if (si == null) {
12651                return null;
12652            }
12653            final boolean matchVisibleToInstantApp =
12654                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12655            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12656            // throw out filters that aren't visible to ephemeral apps
12657            if (matchVisibleToInstantApp
12658                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12659                return null;
12660            }
12661            // throw out ephemeral filters if we're not explicitly requesting them
12662            if (!isInstantApp && userState.instantApp) {
12663                return null;
12664            }
12665            // throw out instant app filters if updates are available; will trigger
12666            // instant app resolution
12667            if (userState.instantApp && ps.isUpdateAvailable()) {
12668                return null;
12669            }
12670            final ResolveInfo res = new ResolveInfo();
12671            res.serviceInfo = si;
12672            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12673                res.filter = filter;
12674            }
12675            res.priority = info.getPriority();
12676            res.preferredOrder = service.owner.mPreferredOrder;
12677            res.match = match;
12678            res.isDefault = info.hasDefault;
12679            res.labelRes = info.labelRes;
12680            res.nonLocalizedLabel = info.nonLocalizedLabel;
12681            res.icon = info.icon;
12682            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12683            return res;
12684        }
12685
12686        @Override
12687        protected void sortResults(List<ResolveInfo> results) {
12688            Collections.sort(results, mResolvePrioritySorter);
12689        }
12690
12691        @Override
12692        protected void dumpFilter(PrintWriter out, String prefix,
12693                PackageParser.ServiceIntentInfo filter) {
12694            out.print(prefix); out.print(
12695                    Integer.toHexString(System.identityHashCode(filter.service)));
12696                    out.print(' ');
12697                    filter.service.printComponentShortName(out);
12698                    out.print(" filter ");
12699                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12700        }
12701
12702        @Override
12703        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12704            return filter.service;
12705        }
12706
12707        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12708            PackageParser.Service service = (PackageParser.Service)label;
12709            out.print(prefix); out.print(
12710                    Integer.toHexString(System.identityHashCode(service)));
12711                    out.print(' ');
12712                    service.printComponentShortName(out);
12713            if (count > 1) {
12714                out.print(" ("); out.print(count); out.print(" filters)");
12715            }
12716            out.println();
12717        }
12718
12719//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12720//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12721//            final List<ResolveInfo> retList = Lists.newArrayList();
12722//            while (i.hasNext()) {
12723//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12724//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12725//                    retList.add(resolveInfo);
12726//                }
12727//            }
12728//            return retList;
12729//        }
12730
12731        // Keys are String (activity class name), values are Activity.
12732        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12733                = new ArrayMap<ComponentName, PackageParser.Service>();
12734        private int mFlags;
12735    }
12736
12737    private final class ProviderIntentResolver
12738            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12739        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12740                boolean defaultOnly, int userId) {
12741            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12742            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12743        }
12744
12745        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12746                int userId) {
12747            if (!sUserManager.exists(userId))
12748                return null;
12749            mFlags = flags;
12750            return super.queryIntent(intent, resolvedType,
12751                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12752                    userId);
12753        }
12754
12755        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12756                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12757            if (!sUserManager.exists(userId))
12758                return null;
12759            if (packageProviders == null) {
12760                return null;
12761            }
12762            mFlags = flags;
12763            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12764            final int N = packageProviders.size();
12765            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12766                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12767
12768            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12769            for (int i = 0; i < N; ++i) {
12770                intentFilters = packageProviders.get(i).intents;
12771                if (intentFilters != null && intentFilters.size() > 0) {
12772                    PackageParser.ProviderIntentInfo[] array =
12773                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12774                    intentFilters.toArray(array);
12775                    listCut.add(array);
12776                }
12777            }
12778            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12779        }
12780
12781        public final void addProvider(PackageParser.Provider p) {
12782            if (mProviders.containsKey(p.getComponentName())) {
12783                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12784                return;
12785            }
12786
12787            mProviders.put(p.getComponentName(), p);
12788            if (DEBUG_SHOW_INFO) {
12789                Log.v(TAG, "  "
12790                        + (p.info.nonLocalizedLabel != null
12791                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12792                Log.v(TAG, "    Class=" + p.info.name);
12793            }
12794            final int NI = p.intents.size();
12795            int j;
12796            for (j = 0; j < NI; j++) {
12797                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12798                if (DEBUG_SHOW_INFO) {
12799                    Log.v(TAG, "    IntentFilter:");
12800                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12801                }
12802                if (!intent.debugCheck()) {
12803                    Log.w(TAG, "==> For Provider " + p.info.name);
12804                }
12805                addFilter(intent);
12806            }
12807        }
12808
12809        public final void removeProvider(PackageParser.Provider p) {
12810            mProviders.remove(p.getComponentName());
12811            if (DEBUG_SHOW_INFO) {
12812                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12813                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12814                Log.v(TAG, "    Class=" + p.info.name);
12815            }
12816            final int NI = p.intents.size();
12817            int j;
12818            for (j = 0; j < NI; j++) {
12819                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12820                if (DEBUG_SHOW_INFO) {
12821                    Log.v(TAG, "    IntentFilter:");
12822                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12823                }
12824                removeFilter(intent);
12825            }
12826        }
12827
12828        @Override
12829        protected boolean allowFilterResult(
12830                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12831            ProviderInfo filterPi = filter.provider.info;
12832            for (int i = dest.size() - 1; i >= 0; i--) {
12833                ProviderInfo destPi = dest.get(i).providerInfo;
12834                if (destPi.name == filterPi.name
12835                        && destPi.packageName == filterPi.packageName) {
12836                    return false;
12837                }
12838            }
12839            return true;
12840        }
12841
12842        @Override
12843        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12844            return new PackageParser.ProviderIntentInfo[size];
12845        }
12846
12847        @Override
12848        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12849            if (!sUserManager.exists(userId))
12850                return true;
12851            PackageParser.Package p = filter.provider.owner;
12852            if (p != null) {
12853                PackageSetting ps = (PackageSetting) p.mExtras;
12854                if (ps != null) {
12855                    // System apps are never considered stopped for purposes of
12856                    // filtering, because there may be no way for the user to
12857                    // actually re-launch them.
12858                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12859                            && ps.getStopped(userId);
12860                }
12861            }
12862            return false;
12863        }
12864
12865        @Override
12866        protected boolean isPackageForFilter(String packageName,
12867                PackageParser.ProviderIntentInfo info) {
12868            return packageName.equals(info.provider.owner.packageName);
12869        }
12870
12871        @Override
12872        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12873                int match, int userId) {
12874            if (!sUserManager.exists(userId))
12875                return null;
12876            final PackageParser.ProviderIntentInfo info = filter;
12877            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12878                return null;
12879            }
12880            final PackageParser.Provider provider = info.provider;
12881            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12882            if (ps == null) {
12883                return null;
12884            }
12885            final PackageUserState userState = ps.readUserState(userId);
12886            final boolean matchVisibleToInstantApp =
12887                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12888            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12889            // throw out filters that aren't visible to instant applications
12890            if (matchVisibleToInstantApp
12891                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12892                return null;
12893            }
12894            // throw out instant application filters if we're not explicitly requesting them
12895            if (!isInstantApp && userState.instantApp) {
12896                return null;
12897            }
12898            // throw out instant application filters if updates are available; will trigger
12899            // instant application resolution
12900            if (userState.instantApp && ps.isUpdateAvailable()) {
12901                return null;
12902            }
12903            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12904                    userState, userId);
12905            if (pi == null) {
12906                return null;
12907            }
12908            final ResolveInfo res = new ResolveInfo();
12909            res.providerInfo = pi;
12910            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12911                res.filter = filter;
12912            }
12913            res.priority = info.getPriority();
12914            res.preferredOrder = provider.owner.mPreferredOrder;
12915            res.match = match;
12916            res.isDefault = info.hasDefault;
12917            res.labelRes = info.labelRes;
12918            res.nonLocalizedLabel = info.nonLocalizedLabel;
12919            res.icon = info.icon;
12920            res.system = res.providerInfo.applicationInfo.isSystemApp();
12921            return res;
12922        }
12923
12924        @Override
12925        protected void sortResults(List<ResolveInfo> results) {
12926            Collections.sort(results, mResolvePrioritySorter);
12927        }
12928
12929        @Override
12930        protected void dumpFilter(PrintWriter out, String prefix,
12931                PackageParser.ProviderIntentInfo filter) {
12932            out.print(prefix);
12933            out.print(
12934                    Integer.toHexString(System.identityHashCode(filter.provider)));
12935            out.print(' ');
12936            filter.provider.printComponentShortName(out);
12937            out.print(" filter ");
12938            out.println(Integer.toHexString(System.identityHashCode(filter)));
12939        }
12940
12941        @Override
12942        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12943            return filter.provider;
12944        }
12945
12946        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12947            PackageParser.Provider provider = (PackageParser.Provider)label;
12948            out.print(prefix); out.print(
12949                    Integer.toHexString(System.identityHashCode(provider)));
12950                    out.print(' ');
12951                    provider.printComponentShortName(out);
12952            if (count > 1) {
12953                out.print(" ("); out.print(count); out.print(" filters)");
12954            }
12955            out.println();
12956        }
12957
12958        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12959                = new ArrayMap<ComponentName, PackageParser.Provider>();
12960        private int mFlags;
12961    }
12962
12963    static final class EphemeralIntentResolver
12964            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12965        /**
12966         * The result that has the highest defined order. Ordering applies on a
12967         * per-package basis. Mapping is from package name to Pair of order and
12968         * EphemeralResolveInfo.
12969         * <p>
12970         * NOTE: This is implemented as a field variable for convenience and efficiency.
12971         * By having a field variable, we're able to track filter ordering as soon as
12972         * a non-zero order is defined. Otherwise, multiple loops across the result set
12973         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12974         * this needs to be contained entirely within {@link #filterResults}.
12975         */
12976        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12977
12978        @Override
12979        protected AuxiliaryResolveInfo[] newArray(int size) {
12980            return new AuxiliaryResolveInfo[size];
12981        }
12982
12983        @Override
12984        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12985            return true;
12986        }
12987
12988        @Override
12989        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12990                int userId) {
12991            if (!sUserManager.exists(userId)) {
12992                return null;
12993            }
12994            final String packageName = responseObj.resolveInfo.getPackageName();
12995            final Integer order = responseObj.getOrder();
12996            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12997                    mOrderResult.get(packageName);
12998            // ordering is enabled and this item's order isn't high enough
12999            if (lastOrderResult != null && lastOrderResult.first >= order) {
13000                return null;
13001            }
13002            final InstantAppResolveInfo res = responseObj.resolveInfo;
13003            if (order > 0) {
13004                // non-zero order, enable ordering
13005                mOrderResult.put(packageName, new Pair<>(order, res));
13006            }
13007            return responseObj;
13008        }
13009
13010        @Override
13011        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13012            // only do work if ordering is enabled [most of the time it won't be]
13013            if (mOrderResult.size() == 0) {
13014                return;
13015            }
13016            int resultSize = results.size();
13017            for (int i = 0; i < resultSize; i++) {
13018                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13019                final String packageName = info.getPackageName();
13020                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13021                if (savedInfo == null) {
13022                    // package doesn't having ordering
13023                    continue;
13024                }
13025                if (savedInfo.second == info) {
13026                    // circled back to the highest ordered item; remove from order list
13027                    mOrderResult.remove(savedInfo);
13028                    if (mOrderResult.size() == 0) {
13029                        // no more ordered items
13030                        break;
13031                    }
13032                    continue;
13033                }
13034                // item has a worse order, remove it from the result list
13035                results.remove(i);
13036                resultSize--;
13037                i--;
13038            }
13039        }
13040    }
13041
13042    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13043            new Comparator<ResolveInfo>() {
13044        public int compare(ResolveInfo r1, ResolveInfo r2) {
13045            int v1 = r1.priority;
13046            int v2 = r2.priority;
13047            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13048            if (v1 != v2) {
13049                return (v1 > v2) ? -1 : 1;
13050            }
13051            v1 = r1.preferredOrder;
13052            v2 = r2.preferredOrder;
13053            if (v1 != v2) {
13054                return (v1 > v2) ? -1 : 1;
13055            }
13056            if (r1.isDefault != r2.isDefault) {
13057                return r1.isDefault ? -1 : 1;
13058            }
13059            v1 = r1.match;
13060            v2 = r2.match;
13061            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13062            if (v1 != v2) {
13063                return (v1 > v2) ? -1 : 1;
13064            }
13065            if (r1.system != r2.system) {
13066                return r1.system ? -1 : 1;
13067            }
13068            if (r1.activityInfo != null) {
13069                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13070            }
13071            if (r1.serviceInfo != null) {
13072                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13073            }
13074            if (r1.providerInfo != null) {
13075                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13076            }
13077            return 0;
13078        }
13079    };
13080
13081    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13082            new Comparator<ProviderInfo>() {
13083        public int compare(ProviderInfo p1, ProviderInfo p2) {
13084            final int v1 = p1.initOrder;
13085            final int v2 = p2.initOrder;
13086            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13087        }
13088    };
13089
13090    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13091            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13092            final int[] userIds) {
13093        mHandler.post(new Runnable() {
13094            @Override
13095            public void run() {
13096                try {
13097                    final IActivityManager am = ActivityManager.getService();
13098                    if (am == null) return;
13099                    final int[] resolvedUserIds;
13100                    if (userIds == null) {
13101                        resolvedUserIds = am.getRunningUserIds();
13102                    } else {
13103                        resolvedUserIds = userIds;
13104                    }
13105                    for (int id : resolvedUserIds) {
13106                        final Intent intent = new Intent(action,
13107                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13108                        if (extras != null) {
13109                            intent.putExtras(extras);
13110                        }
13111                        if (targetPkg != null) {
13112                            intent.setPackage(targetPkg);
13113                        }
13114                        // Modify the UID when posting to other users
13115                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13116                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13117                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13118                            intent.putExtra(Intent.EXTRA_UID, uid);
13119                        }
13120                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13121                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13122                        if (DEBUG_BROADCASTS) {
13123                            RuntimeException here = new RuntimeException("here");
13124                            here.fillInStackTrace();
13125                            Slog.d(TAG, "Sending to user " + id + ": "
13126                                    + intent.toShortString(false, true, false, false)
13127                                    + " " + intent.getExtras(), here);
13128                        }
13129                        am.broadcastIntent(null, intent, null, finishedReceiver,
13130                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13131                                null, finishedReceiver != null, false, id);
13132                    }
13133                } catch (RemoteException ex) {
13134                }
13135            }
13136        });
13137    }
13138
13139    /**
13140     * Check if the external storage media is available. This is true if there
13141     * is a mounted external storage medium or if the external storage is
13142     * emulated.
13143     */
13144    private boolean isExternalMediaAvailable() {
13145        return mMediaMounted || Environment.isExternalStorageEmulated();
13146    }
13147
13148    @Override
13149    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13150        // writer
13151        synchronized (mPackages) {
13152            if (!isExternalMediaAvailable()) {
13153                // If the external storage is no longer mounted at this point,
13154                // the caller may not have been able to delete all of this
13155                // packages files and can not delete any more.  Bail.
13156                return null;
13157            }
13158            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13159            if (lastPackage != null) {
13160                pkgs.remove(lastPackage);
13161            }
13162            if (pkgs.size() > 0) {
13163                return pkgs.get(0);
13164            }
13165        }
13166        return null;
13167    }
13168
13169    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13170        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13171                userId, andCode ? 1 : 0, packageName);
13172        if (mSystemReady) {
13173            msg.sendToTarget();
13174        } else {
13175            if (mPostSystemReadyMessages == null) {
13176                mPostSystemReadyMessages = new ArrayList<>();
13177            }
13178            mPostSystemReadyMessages.add(msg);
13179        }
13180    }
13181
13182    void startCleaningPackages() {
13183        // reader
13184        if (!isExternalMediaAvailable()) {
13185            return;
13186        }
13187        synchronized (mPackages) {
13188            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13189                return;
13190            }
13191        }
13192        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13193        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13194        IActivityManager am = ActivityManager.getService();
13195        if (am != null) {
13196            int dcsUid = -1;
13197            synchronized (mPackages) {
13198                if (!mDefaultContainerWhitelisted) {
13199                    mDefaultContainerWhitelisted = true;
13200                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13201                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13202                }
13203            }
13204            try {
13205                if (dcsUid > 0) {
13206                    am.backgroundWhitelistUid(dcsUid);
13207                }
13208                am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(),
13209                        UserHandle.USER_SYSTEM);
13210            } catch (RemoteException e) {
13211            }
13212        }
13213    }
13214
13215    @Override
13216    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13217            int installFlags, String installerPackageName, int userId) {
13218        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13219
13220        final int callingUid = Binder.getCallingUid();
13221        enforceCrossUserPermission(callingUid, userId,
13222                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13223
13224        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13225            try {
13226                if (observer != null) {
13227                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13228                }
13229            } catch (RemoteException re) {
13230            }
13231            return;
13232        }
13233
13234        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13235            installFlags |= PackageManager.INSTALL_FROM_ADB;
13236
13237        } else {
13238            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13239            // about installerPackageName.
13240
13241            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13242            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13243        }
13244
13245        UserHandle user;
13246        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13247            user = UserHandle.ALL;
13248        } else {
13249            user = new UserHandle(userId);
13250        }
13251
13252        // Only system components can circumvent runtime permissions when installing.
13253        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13254                && mContext.checkCallingOrSelfPermission(Manifest.permission
13255                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13256            throw new SecurityException("You need the "
13257                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13258                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13259        }
13260
13261        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13262                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13263            throw new IllegalArgumentException(
13264                    "New installs into ASEC containers no longer supported");
13265        }
13266
13267        final File originFile = new File(originPath);
13268        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13269
13270        final Message msg = mHandler.obtainMessage(INIT_COPY);
13271        final VerificationInfo verificationInfo = new VerificationInfo(
13272                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13273        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13274                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13275                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13276                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13277        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13278        msg.obj = params;
13279
13280        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13281                System.identityHashCode(msg.obj));
13282        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13283                System.identityHashCode(msg.obj));
13284
13285        mHandler.sendMessage(msg);
13286    }
13287
13288
13289    /**
13290     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13291     * it is acting on behalf on an enterprise or the user).
13292     *
13293     * Note that the ordering of the conditionals in this method is important. The checks we perform
13294     * are as follows, in this order:
13295     *
13296     * 1) If the install is being performed by a system app, we can trust the app to have set the
13297     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13298     *    what it is.
13299     * 2) If the install is being performed by a device or profile owner app, the install reason
13300     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13301     *    set the install reason correctly. If the app targets an older SDK version where install
13302     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13303     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13304     * 3) In all other cases, the install is being performed by a regular app that is neither part
13305     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13306     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13307     *    set to enterprise policy and if so, change it to unknown instead.
13308     */
13309    private int fixUpInstallReason(String installerPackageName, int installerUid,
13310            int installReason) {
13311        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13312                == PERMISSION_GRANTED) {
13313            // If the install is being performed by a system app, we trust that app to have set the
13314            // install reason correctly.
13315            return installReason;
13316        }
13317
13318        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13319            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13320        if (dpm != null) {
13321            ComponentName owner = null;
13322            try {
13323                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13324                if (owner == null) {
13325                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13326                }
13327            } catch (RemoteException e) {
13328            }
13329            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13330                // If the install is being performed by a device or profile owner, the install
13331                // reason should be enterprise policy.
13332                return PackageManager.INSTALL_REASON_POLICY;
13333            }
13334        }
13335
13336        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13337            // If the install is being performed by a regular app (i.e. neither system app nor
13338            // device or profile owner), we have no reason to believe that the app is acting on
13339            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13340            // change it to unknown instead.
13341            return PackageManager.INSTALL_REASON_UNKNOWN;
13342        }
13343
13344        // If the install is being performed by a regular app and the install reason was set to any
13345        // value but enterprise policy, leave the install reason unchanged.
13346        return installReason;
13347    }
13348
13349    void installStage(String packageName, File stagedDir, String stagedCid,
13350            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13351            String installerPackageName, int installerUid, UserHandle user,
13352            Certificate[][] certificates) {
13353        if (DEBUG_EPHEMERAL) {
13354            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13355                Slog.d(TAG, "Ephemeral install of " + packageName);
13356            }
13357        }
13358        final VerificationInfo verificationInfo = new VerificationInfo(
13359                sessionParams.originatingUri, sessionParams.referrerUri,
13360                sessionParams.originatingUid, installerUid);
13361
13362        final OriginInfo origin;
13363        if (stagedDir != null) {
13364            origin = OriginInfo.fromStagedFile(stagedDir);
13365        } else {
13366            origin = OriginInfo.fromStagedContainer(stagedCid);
13367        }
13368
13369        final Message msg = mHandler.obtainMessage(INIT_COPY);
13370        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13371                sessionParams.installReason);
13372        final InstallParams params = new InstallParams(origin, null, observer,
13373                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13374                verificationInfo, user, sessionParams.abiOverride,
13375                sessionParams.grantedRuntimePermissions, certificates, installReason);
13376        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13377        msg.obj = params;
13378
13379        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13380                System.identityHashCode(msg.obj));
13381        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13382                System.identityHashCode(msg.obj));
13383
13384        mHandler.sendMessage(msg);
13385    }
13386
13387    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13388            int userId) {
13389        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13390        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13391    }
13392
13393    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13394            int appId, int... userIds) {
13395        if (ArrayUtils.isEmpty(userIds)) {
13396            return;
13397        }
13398        Bundle extras = new Bundle(1);
13399        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13400        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13401
13402        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_ADDED, packageName,
13403                extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, userIds);
13404        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13405                extras, 0, null, null, userIds);
13406        if (isSystem) {
13407            mHandler.post(() -> {
13408                        for (int userId : userIds) {
13409                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13410                        }
13411                    }
13412            );
13413        }
13414    }
13415
13416    /**
13417     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13418     * automatically without needing an explicit launch.
13419     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13420     */
13421    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13422        // If user is not running, the app didn't miss any broadcast
13423        if (!mUserManagerInternal.isUserRunning(userId)) {
13424            return;
13425        }
13426        final IActivityManager am = ActivityManager.getService();
13427        try {
13428            // Deliver LOCKED_BOOT_COMPLETED first
13429            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13430                    .setPackage(packageName);
13431            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13432            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13433                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13434
13435            // Deliver BOOT_COMPLETED only if user is unlocked
13436            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13437                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13438                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13439                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13440            }
13441        } catch (RemoteException e) {
13442            throw e.rethrowFromSystemServer();
13443        }
13444    }
13445
13446    @Override
13447    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13448            int userId) {
13449        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13450        PackageSetting pkgSetting;
13451        final int uid = Binder.getCallingUid();
13452        enforceCrossUserPermission(uid, userId,
13453                true /* requireFullPermission */, true /* checkShell */,
13454                "setApplicationHiddenSetting for user " + userId);
13455
13456        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13457            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13458            return false;
13459        }
13460
13461        long callingId = Binder.clearCallingIdentity();
13462        try {
13463            boolean sendAdded = false;
13464            boolean sendRemoved = false;
13465            // writer
13466            synchronized (mPackages) {
13467                pkgSetting = mSettings.mPackages.get(packageName);
13468                if (pkgSetting == null) {
13469                    return false;
13470                }
13471                // Do not allow "android" is being disabled
13472                if ("android".equals(packageName)) {
13473                    Slog.w(TAG, "Cannot hide package: android");
13474                    return false;
13475                }
13476                // Cannot hide static shared libs as they are considered
13477                // a part of the using app (emulating static linking). Also
13478                // static libs are installed always on internal storage.
13479                PackageParser.Package pkg = mPackages.get(packageName);
13480                if (pkg != null && pkg.staticSharedLibName != null) {
13481                    Slog.w(TAG, "Cannot hide package: " + packageName
13482                            + " providing static shared library: "
13483                            + pkg.staticSharedLibName);
13484                    return false;
13485                }
13486                // Only allow protected packages to hide themselves.
13487                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13488                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13489                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13490                    return false;
13491                }
13492
13493                if (pkgSetting.getHidden(userId) != hidden) {
13494                    pkgSetting.setHidden(hidden, userId);
13495                    mSettings.writePackageRestrictionsLPr(userId);
13496                    if (hidden) {
13497                        sendRemoved = true;
13498                    } else {
13499                        sendAdded = true;
13500                    }
13501                }
13502            }
13503            if (sendAdded) {
13504                sendPackageAddedForUser(packageName, pkgSetting, userId);
13505                return true;
13506            }
13507            if (sendRemoved) {
13508                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13509                        "hiding pkg");
13510                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13511                return true;
13512            }
13513        } finally {
13514            Binder.restoreCallingIdentity(callingId);
13515        }
13516        return false;
13517    }
13518
13519    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13520            int userId) {
13521        final PackageRemovedInfo info = new PackageRemovedInfo();
13522        info.removedPackage = packageName;
13523        info.removedUsers = new int[] {userId};
13524        info.broadcastUsers = new int[] {userId};
13525        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13526        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13527    }
13528
13529    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13530        if (pkgList.length > 0) {
13531            Bundle extras = new Bundle(1);
13532            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13533
13534            sendPackageBroadcast(
13535                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13536                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13537                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13538                    new int[] {userId});
13539        }
13540    }
13541
13542    /**
13543     * Returns true if application is not found or there was an error. Otherwise it returns
13544     * the hidden state of the package for the given user.
13545     */
13546    @Override
13547    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13548        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13549        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13550                true /* requireFullPermission */, false /* checkShell */,
13551                "getApplicationHidden for user " + userId);
13552        PackageSetting pkgSetting;
13553        long callingId = Binder.clearCallingIdentity();
13554        try {
13555            // writer
13556            synchronized (mPackages) {
13557                pkgSetting = mSettings.mPackages.get(packageName);
13558                if (pkgSetting == null) {
13559                    return true;
13560                }
13561                return pkgSetting.getHidden(userId);
13562            }
13563        } finally {
13564            Binder.restoreCallingIdentity(callingId);
13565        }
13566    }
13567
13568    /**
13569     * @hide
13570     */
13571    @Override
13572    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13573            int installReason) {
13574        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13575                null);
13576        PackageSetting pkgSetting;
13577        final int uid = Binder.getCallingUid();
13578        enforceCrossUserPermission(uid, userId,
13579                true /* requireFullPermission */, true /* checkShell */,
13580                "installExistingPackage for user " + userId);
13581        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13582            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13583        }
13584
13585        long callingId = Binder.clearCallingIdentity();
13586        try {
13587            boolean installed = false;
13588            final boolean instantApp =
13589                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13590            final boolean fullApp =
13591                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13592
13593            // writer
13594            synchronized (mPackages) {
13595                pkgSetting = mSettings.mPackages.get(packageName);
13596                if (pkgSetting == null) {
13597                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13598                }
13599                if (!pkgSetting.getInstalled(userId)) {
13600                    pkgSetting.setInstalled(true, userId);
13601                    pkgSetting.setHidden(false, userId);
13602                    pkgSetting.setInstallReason(installReason, userId);
13603                    mSettings.writePackageRestrictionsLPr(userId);
13604                    mSettings.writeKernelMappingLPr(pkgSetting);
13605                    installed = true;
13606                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13607                    // upgrade app from instant to full; we don't allow app downgrade
13608                    installed = true;
13609                }
13610                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13611            }
13612
13613            if (installed) {
13614                if (pkgSetting.pkg != null) {
13615                    synchronized (mInstallLock) {
13616                        // We don't need to freeze for a brand new install
13617                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13618                    }
13619                }
13620                sendPackageAddedForUser(packageName, pkgSetting, userId);
13621                synchronized (mPackages) {
13622                    updateSequenceNumberLP(packageName, new int[]{ userId });
13623                }
13624            }
13625        } finally {
13626            Binder.restoreCallingIdentity(callingId);
13627        }
13628
13629        return PackageManager.INSTALL_SUCCEEDED;
13630    }
13631
13632    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13633            boolean instantApp, boolean fullApp) {
13634        // no state specified; do nothing
13635        if (!instantApp && !fullApp) {
13636            return;
13637        }
13638        if (userId != UserHandle.USER_ALL) {
13639            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13640                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13641            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13642                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13643            }
13644        } else {
13645            for (int currentUserId : sUserManager.getUserIds()) {
13646                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13647                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13648                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13649                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13650                }
13651            }
13652        }
13653    }
13654
13655    boolean isUserRestricted(int userId, String restrictionKey) {
13656        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13657        if (restrictions.getBoolean(restrictionKey, false)) {
13658            Log.w(TAG, "User is restricted: " + restrictionKey);
13659            return true;
13660        }
13661        return false;
13662    }
13663
13664    @Override
13665    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13666            int userId) {
13667        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13668        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13669                true /* requireFullPermission */, true /* checkShell */,
13670                "setPackagesSuspended for user " + userId);
13671
13672        if (ArrayUtils.isEmpty(packageNames)) {
13673            return packageNames;
13674        }
13675
13676        // List of package names for whom the suspended state has changed.
13677        List<String> changedPackages = new ArrayList<>(packageNames.length);
13678        // List of package names for whom the suspended state is not set as requested in this
13679        // method.
13680        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13681        long callingId = Binder.clearCallingIdentity();
13682        try {
13683            for (int i = 0; i < packageNames.length; i++) {
13684                String packageName = packageNames[i];
13685                boolean changed = false;
13686                final int appId;
13687                synchronized (mPackages) {
13688                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13689                    if (pkgSetting == null) {
13690                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13691                                + "\". Skipping suspending/un-suspending.");
13692                        unactionedPackages.add(packageName);
13693                        continue;
13694                    }
13695                    appId = pkgSetting.appId;
13696                    if (pkgSetting.getSuspended(userId) != suspended) {
13697                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13698                            unactionedPackages.add(packageName);
13699                            continue;
13700                        }
13701                        pkgSetting.setSuspended(suspended, userId);
13702                        mSettings.writePackageRestrictionsLPr(userId);
13703                        changed = true;
13704                        changedPackages.add(packageName);
13705                    }
13706                }
13707
13708                if (changed && suspended) {
13709                    killApplication(packageName, UserHandle.getUid(userId, appId),
13710                            "suspending package");
13711                }
13712            }
13713        } finally {
13714            Binder.restoreCallingIdentity(callingId);
13715        }
13716
13717        if (!changedPackages.isEmpty()) {
13718            sendPackagesSuspendedForUser(changedPackages.toArray(
13719                    new String[changedPackages.size()]), userId, suspended);
13720        }
13721
13722        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13723    }
13724
13725    @Override
13726    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13727        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13728                true /* requireFullPermission */, false /* checkShell */,
13729                "isPackageSuspendedForUser for user " + userId);
13730        synchronized (mPackages) {
13731            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13732            if (pkgSetting == null) {
13733                throw new IllegalArgumentException("Unknown target package: " + packageName);
13734            }
13735            return pkgSetting.getSuspended(userId);
13736        }
13737    }
13738
13739    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13740        if (isPackageDeviceAdmin(packageName, userId)) {
13741            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13742                    + "\": has an active device admin");
13743            return false;
13744        }
13745
13746        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13747        if (packageName.equals(activeLauncherPackageName)) {
13748            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13749                    + "\": contains the active launcher");
13750            return false;
13751        }
13752
13753        if (packageName.equals(mRequiredInstallerPackage)) {
13754            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13755                    + "\": required for package installation");
13756            return false;
13757        }
13758
13759        if (packageName.equals(mRequiredUninstallerPackage)) {
13760            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13761                    + "\": required for package uninstallation");
13762            return false;
13763        }
13764
13765        if (packageName.equals(mRequiredVerifierPackage)) {
13766            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13767                    + "\": required for package verification");
13768            return false;
13769        }
13770
13771        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13772            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13773                    + "\": is the default dialer");
13774            return false;
13775        }
13776
13777        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13778            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13779                    + "\": protected package");
13780            return false;
13781        }
13782
13783        // Cannot suspend static shared libs as they are considered
13784        // a part of the using app (emulating static linking). Also
13785        // static libs are installed always on internal storage.
13786        PackageParser.Package pkg = mPackages.get(packageName);
13787        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13788            Slog.w(TAG, "Cannot suspend package: " + packageName
13789                    + " providing static shared library: "
13790                    + pkg.staticSharedLibName);
13791            return false;
13792        }
13793
13794        return true;
13795    }
13796
13797    private String getActiveLauncherPackageName(int userId) {
13798        Intent intent = new Intent(Intent.ACTION_MAIN);
13799        intent.addCategory(Intent.CATEGORY_HOME);
13800        ResolveInfo resolveInfo = resolveIntent(
13801                intent,
13802                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13803                PackageManager.MATCH_DEFAULT_ONLY,
13804                userId);
13805
13806        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13807    }
13808
13809    private String getDefaultDialerPackageName(int userId) {
13810        synchronized (mPackages) {
13811            return mSettings.getDefaultDialerPackageNameLPw(userId);
13812        }
13813    }
13814
13815    @Override
13816    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13817        mContext.enforceCallingOrSelfPermission(
13818                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13819                "Only package verification agents can verify applications");
13820
13821        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13822        final PackageVerificationResponse response = new PackageVerificationResponse(
13823                verificationCode, Binder.getCallingUid());
13824        msg.arg1 = id;
13825        msg.obj = response;
13826        mHandler.sendMessage(msg);
13827    }
13828
13829    @Override
13830    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13831            long millisecondsToDelay) {
13832        mContext.enforceCallingOrSelfPermission(
13833                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13834                "Only package verification agents can extend verification timeouts");
13835
13836        final PackageVerificationState state = mPendingVerification.get(id);
13837        final PackageVerificationResponse response = new PackageVerificationResponse(
13838                verificationCodeAtTimeout, Binder.getCallingUid());
13839
13840        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13841            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13842        }
13843        if (millisecondsToDelay < 0) {
13844            millisecondsToDelay = 0;
13845        }
13846        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13847                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13848            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13849        }
13850
13851        if ((state != null) && !state.timeoutExtended()) {
13852            state.extendTimeout();
13853
13854            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13855            msg.arg1 = id;
13856            msg.obj = response;
13857            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13858        }
13859    }
13860
13861    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13862            int verificationCode, UserHandle user) {
13863        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13864        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13865        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13866        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13867        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13868
13869        mContext.sendBroadcastAsUser(intent, user,
13870                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13871    }
13872
13873    private ComponentName matchComponentForVerifier(String packageName,
13874            List<ResolveInfo> receivers) {
13875        ActivityInfo targetReceiver = null;
13876
13877        final int NR = receivers.size();
13878        for (int i = 0; i < NR; i++) {
13879            final ResolveInfo info = receivers.get(i);
13880            if (info.activityInfo == null) {
13881                continue;
13882            }
13883
13884            if (packageName.equals(info.activityInfo.packageName)) {
13885                targetReceiver = info.activityInfo;
13886                break;
13887            }
13888        }
13889
13890        if (targetReceiver == null) {
13891            return null;
13892        }
13893
13894        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13895    }
13896
13897    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13898            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13899        if (pkgInfo.verifiers.length == 0) {
13900            return null;
13901        }
13902
13903        final int N = pkgInfo.verifiers.length;
13904        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13905        for (int i = 0; i < N; i++) {
13906            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13907
13908            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13909                    receivers);
13910            if (comp == null) {
13911                continue;
13912            }
13913
13914            final int verifierUid = getUidForVerifier(verifierInfo);
13915            if (verifierUid == -1) {
13916                continue;
13917            }
13918
13919            if (DEBUG_VERIFY) {
13920                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13921                        + " with the correct signature");
13922            }
13923            sufficientVerifiers.add(comp);
13924            verificationState.addSufficientVerifier(verifierUid);
13925        }
13926
13927        return sufficientVerifiers;
13928    }
13929
13930    private int getUidForVerifier(VerifierInfo verifierInfo) {
13931        synchronized (mPackages) {
13932            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13933            if (pkg == null) {
13934                return -1;
13935            } else if (pkg.mSignatures.length != 1) {
13936                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13937                        + " has more than one signature; ignoring");
13938                return -1;
13939            }
13940
13941            /*
13942             * If the public key of the package's signature does not match
13943             * our expected public key, then this is a different package and
13944             * we should skip.
13945             */
13946
13947            final byte[] expectedPublicKey;
13948            try {
13949                final Signature verifierSig = pkg.mSignatures[0];
13950                final PublicKey publicKey = verifierSig.getPublicKey();
13951                expectedPublicKey = publicKey.getEncoded();
13952            } catch (CertificateException e) {
13953                return -1;
13954            }
13955
13956            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13957
13958            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13959                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13960                        + " does not have the expected public key; ignoring");
13961                return -1;
13962            }
13963
13964            return pkg.applicationInfo.uid;
13965        }
13966    }
13967
13968    @Override
13969    public void finishPackageInstall(int token, boolean didLaunch) {
13970        enforceSystemOrRoot("Only the system is allowed to finish installs");
13971
13972        if (DEBUG_INSTALL) {
13973            Slog.v(TAG, "BM finishing package install for " + token);
13974        }
13975        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13976
13977        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13978        mHandler.sendMessage(msg);
13979    }
13980
13981    /**
13982     * Get the verification agent timeout.
13983     *
13984     * @return verification timeout in milliseconds
13985     */
13986    private long getVerificationTimeout() {
13987        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13988                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13989                DEFAULT_VERIFICATION_TIMEOUT);
13990    }
13991
13992    /**
13993     * Get the default verification agent response code.
13994     *
13995     * @return default verification response code
13996     */
13997    private int getDefaultVerificationResponse() {
13998        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13999                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14000                DEFAULT_VERIFICATION_RESPONSE);
14001    }
14002
14003    /**
14004     * Check whether or not package verification has been enabled.
14005     *
14006     * @return true if verification should be performed
14007     */
14008    private boolean isVerificationEnabled(int userId, int installFlags) {
14009        if (!DEFAULT_VERIFY_ENABLE) {
14010            return false;
14011        }
14012
14013        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14014
14015        // Check if installing from ADB
14016        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14017            // Do not run verification in a test harness environment
14018            if (ActivityManager.isRunningInTestHarness()) {
14019                return false;
14020            }
14021            if (ensureVerifyAppsEnabled) {
14022                return true;
14023            }
14024            // Check if the developer does not want package verification for ADB installs
14025            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14026                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14027                return false;
14028            }
14029        }
14030
14031        if (ensureVerifyAppsEnabled) {
14032            return true;
14033        }
14034
14035        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14036                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14037    }
14038
14039    @Override
14040    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14041            throws RemoteException {
14042        mContext.enforceCallingOrSelfPermission(
14043                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14044                "Only intentfilter verification agents can verify applications");
14045
14046        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14047        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14048                Binder.getCallingUid(), verificationCode, failedDomains);
14049        msg.arg1 = id;
14050        msg.obj = response;
14051        mHandler.sendMessage(msg);
14052    }
14053
14054    @Override
14055    public int getIntentVerificationStatus(String packageName, int userId) {
14056        synchronized (mPackages) {
14057            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14058        }
14059    }
14060
14061    @Override
14062    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14063        mContext.enforceCallingOrSelfPermission(
14064                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14065
14066        boolean result = false;
14067        synchronized (mPackages) {
14068            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14069        }
14070        if (result) {
14071            scheduleWritePackageRestrictionsLocked(userId);
14072        }
14073        return result;
14074    }
14075
14076    @Override
14077    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14078            String packageName) {
14079        synchronized (mPackages) {
14080            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14081        }
14082    }
14083
14084    @Override
14085    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14086        if (TextUtils.isEmpty(packageName)) {
14087            return ParceledListSlice.emptyList();
14088        }
14089        synchronized (mPackages) {
14090            PackageParser.Package pkg = mPackages.get(packageName);
14091            if (pkg == null || pkg.activities == null) {
14092                return ParceledListSlice.emptyList();
14093            }
14094            final int count = pkg.activities.size();
14095            ArrayList<IntentFilter> result = new ArrayList<>();
14096            for (int n=0; n<count; n++) {
14097                PackageParser.Activity activity = pkg.activities.get(n);
14098                if (activity.intents != null && activity.intents.size() > 0) {
14099                    result.addAll(activity.intents);
14100                }
14101            }
14102            return new ParceledListSlice<>(result);
14103        }
14104    }
14105
14106    @Override
14107    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14108        mContext.enforceCallingOrSelfPermission(
14109                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14110
14111        synchronized (mPackages) {
14112            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14113            if (packageName != null) {
14114                result |= updateIntentVerificationStatus(packageName,
14115                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
14116                        userId);
14117                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
14118                        packageName, userId);
14119            }
14120            return result;
14121        }
14122    }
14123
14124    @Override
14125    public String getDefaultBrowserPackageName(int userId) {
14126        synchronized (mPackages) {
14127            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14128        }
14129    }
14130
14131    /**
14132     * Get the "allow unknown sources" setting.
14133     *
14134     * @return the current "allow unknown sources" setting
14135     */
14136    private int getUnknownSourcesSettings() {
14137        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14138                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14139                -1);
14140    }
14141
14142    @Override
14143    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14144        final int uid = Binder.getCallingUid();
14145        // writer
14146        synchronized (mPackages) {
14147            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14148            if (targetPackageSetting == null) {
14149                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14150            }
14151
14152            PackageSetting installerPackageSetting;
14153            if (installerPackageName != null) {
14154                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14155                if (installerPackageSetting == null) {
14156                    throw new IllegalArgumentException("Unknown installer package: "
14157                            + installerPackageName);
14158                }
14159            } else {
14160                installerPackageSetting = null;
14161            }
14162
14163            Signature[] callerSignature;
14164            Object obj = mSettings.getUserIdLPr(uid);
14165            if (obj != null) {
14166                if (obj instanceof SharedUserSetting) {
14167                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14168                } else if (obj instanceof PackageSetting) {
14169                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14170                } else {
14171                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14172                }
14173            } else {
14174                throw new SecurityException("Unknown calling UID: " + uid);
14175            }
14176
14177            // Verify: can't set installerPackageName to a package that is
14178            // not signed with the same cert as the caller.
14179            if (installerPackageSetting != null) {
14180                if (compareSignatures(callerSignature,
14181                        installerPackageSetting.signatures.mSignatures)
14182                        != PackageManager.SIGNATURE_MATCH) {
14183                    throw new SecurityException(
14184                            "Caller does not have same cert as new installer package "
14185                            + installerPackageName);
14186                }
14187            }
14188
14189            // Verify: if target already has an installer package, it must
14190            // be signed with the same cert as the caller.
14191            if (targetPackageSetting.installerPackageName != null) {
14192                PackageSetting setting = mSettings.mPackages.get(
14193                        targetPackageSetting.installerPackageName);
14194                // If the currently set package isn't valid, then it's always
14195                // okay to change it.
14196                if (setting != null) {
14197                    if (compareSignatures(callerSignature,
14198                            setting.signatures.mSignatures)
14199                            != PackageManager.SIGNATURE_MATCH) {
14200                        throw new SecurityException(
14201                                "Caller does not have same cert as old installer package "
14202                                + targetPackageSetting.installerPackageName);
14203                    }
14204                }
14205            }
14206
14207            // Okay!
14208            targetPackageSetting.installerPackageName = installerPackageName;
14209            if (installerPackageName != null) {
14210                mSettings.mInstallerPackages.add(installerPackageName);
14211            }
14212            scheduleWriteSettingsLocked();
14213        }
14214    }
14215
14216    @Override
14217    public void setApplicationCategoryHint(String packageName, int categoryHint,
14218            String callerPackageName) {
14219        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14220                callerPackageName);
14221        synchronized (mPackages) {
14222            PackageSetting ps = mSettings.mPackages.get(packageName);
14223            if (ps == null) {
14224                throw new IllegalArgumentException("Unknown target package " + packageName);
14225            }
14226
14227            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14228                throw new IllegalArgumentException("Calling package " + callerPackageName
14229                        + " is not installer for " + packageName);
14230            }
14231
14232            if (ps.categoryHint != categoryHint) {
14233                ps.categoryHint = categoryHint;
14234                scheduleWriteSettingsLocked();
14235            }
14236        }
14237    }
14238
14239    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14240        // Queue up an async operation since the package installation may take a little while.
14241        mHandler.post(new Runnable() {
14242            public void run() {
14243                mHandler.removeCallbacks(this);
14244                 // Result object to be returned
14245                PackageInstalledInfo res = new PackageInstalledInfo();
14246                res.setReturnCode(currentStatus);
14247                res.uid = -1;
14248                res.pkg = null;
14249                res.removedInfo = null;
14250                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14251                    args.doPreInstall(res.returnCode);
14252                    synchronized (mInstallLock) {
14253                        installPackageTracedLI(args, res);
14254                    }
14255                    args.doPostInstall(res.returnCode, res.uid);
14256                }
14257
14258                // A restore should be performed at this point if (a) the install
14259                // succeeded, (b) the operation is not an update, and (c) the new
14260                // package has not opted out of backup participation.
14261                final boolean update = res.removedInfo != null
14262                        && res.removedInfo.removedPackage != null;
14263                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14264                boolean doRestore = !update
14265                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14266
14267                // Set up the post-install work request bookkeeping.  This will be used
14268                // and cleaned up by the post-install event handling regardless of whether
14269                // there's a restore pass performed.  Token values are >= 1.
14270                int token;
14271                if (mNextInstallToken < 0) mNextInstallToken = 1;
14272                token = mNextInstallToken++;
14273
14274                PostInstallData data = new PostInstallData(args, res);
14275                mRunningInstalls.put(token, data);
14276                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14277
14278                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14279                    // Pass responsibility to the Backup Manager.  It will perform a
14280                    // restore if appropriate, then pass responsibility back to the
14281                    // Package Manager to run the post-install observer callbacks
14282                    // and broadcasts.
14283                    IBackupManager bm = IBackupManager.Stub.asInterface(
14284                            ServiceManager.getService(Context.BACKUP_SERVICE));
14285                    if (bm != null) {
14286                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14287                                + " to BM for possible restore");
14288                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14289                        try {
14290                            // TODO: http://b/22388012
14291                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14292                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14293                            } else {
14294                                doRestore = false;
14295                            }
14296                        } catch (RemoteException e) {
14297                            // can't happen; the backup manager is local
14298                        } catch (Exception e) {
14299                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14300                            doRestore = false;
14301                        }
14302                    } else {
14303                        Slog.e(TAG, "Backup Manager not found!");
14304                        doRestore = false;
14305                    }
14306                }
14307
14308                if (!doRestore) {
14309                    // No restore possible, or the Backup Manager was mysteriously not
14310                    // available -- just fire the post-install work request directly.
14311                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14312
14313                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14314
14315                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14316                    mHandler.sendMessage(msg);
14317                }
14318            }
14319        });
14320    }
14321
14322    /**
14323     * Callback from PackageSettings whenever an app is first transitioned out of the
14324     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14325     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14326     * here whether the app is the target of an ongoing install, and only send the
14327     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14328     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14329     * handling.
14330     */
14331    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14332        // Serialize this with the rest of the install-process message chain.  In the
14333        // restore-at-install case, this Runnable will necessarily run before the
14334        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14335        // are coherent.  In the non-restore case, the app has already completed install
14336        // and been launched through some other means, so it is not in a problematic
14337        // state for observers to see the FIRST_LAUNCH signal.
14338        mHandler.post(new Runnable() {
14339            @Override
14340            public void run() {
14341                for (int i = 0; i < mRunningInstalls.size(); i++) {
14342                    final PostInstallData data = mRunningInstalls.valueAt(i);
14343                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14344                        continue;
14345                    }
14346                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14347                        // right package; but is it for the right user?
14348                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14349                            if (userId == data.res.newUsers[uIndex]) {
14350                                if (DEBUG_BACKUP) {
14351                                    Slog.i(TAG, "Package " + pkgName
14352                                            + " being restored so deferring FIRST_LAUNCH");
14353                                }
14354                                return;
14355                            }
14356                        }
14357                    }
14358                }
14359                // didn't find it, so not being restored
14360                if (DEBUG_BACKUP) {
14361                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14362                }
14363                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14364            }
14365        });
14366    }
14367
14368    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14369        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14370                installerPkg, null, userIds);
14371    }
14372
14373    private abstract class HandlerParams {
14374        private static final int MAX_RETRIES = 4;
14375
14376        /**
14377         * Number of times startCopy() has been attempted and had a non-fatal
14378         * error.
14379         */
14380        private int mRetries = 0;
14381
14382        /** User handle for the user requesting the information or installation. */
14383        private final UserHandle mUser;
14384        String traceMethod;
14385        int traceCookie;
14386
14387        HandlerParams(UserHandle user) {
14388            mUser = user;
14389        }
14390
14391        UserHandle getUser() {
14392            return mUser;
14393        }
14394
14395        HandlerParams setTraceMethod(String traceMethod) {
14396            this.traceMethod = traceMethod;
14397            return this;
14398        }
14399
14400        HandlerParams setTraceCookie(int traceCookie) {
14401            this.traceCookie = traceCookie;
14402            return this;
14403        }
14404
14405        final boolean startCopy() {
14406            boolean res;
14407            try {
14408                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14409
14410                if (++mRetries > MAX_RETRIES) {
14411                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14412                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14413                    handleServiceError();
14414                    return false;
14415                } else {
14416                    handleStartCopy();
14417                    res = true;
14418                }
14419            } catch (RemoteException e) {
14420                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14421                mHandler.sendEmptyMessage(MCS_RECONNECT);
14422                res = false;
14423            }
14424            handleReturnCode();
14425            return res;
14426        }
14427
14428        final void serviceError() {
14429            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14430            handleServiceError();
14431            handleReturnCode();
14432        }
14433
14434        abstract void handleStartCopy() throws RemoteException;
14435        abstract void handleServiceError();
14436        abstract void handleReturnCode();
14437    }
14438
14439    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14440        for (File path : paths) {
14441            try {
14442                mcs.clearDirectory(path.getAbsolutePath());
14443            } catch (RemoteException e) {
14444            }
14445        }
14446    }
14447
14448    static class OriginInfo {
14449        /**
14450         * Location where install is coming from, before it has been
14451         * copied/renamed into place. This could be a single monolithic APK
14452         * file, or a cluster directory. This location may be untrusted.
14453         */
14454        final File file;
14455        final String cid;
14456
14457        /**
14458         * Flag indicating that {@link #file} or {@link #cid} has already been
14459         * staged, meaning downstream users don't need to defensively copy the
14460         * contents.
14461         */
14462        final boolean staged;
14463
14464        /**
14465         * Flag indicating that {@link #file} or {@link #cid} is an already
14466         * installed app that is being moved.
14467         */
14468        final boolean existing;
14469
14470        final String resolvedPath;
14471        final File resolvedFile;
14472
14473        static OriginInfo fromNothing() {
14474            return new OriginInfo(null, null, false, false);
14475        }
14476
14477        static OriginInfo fromUntrustedFile(File file) {
14478            return new OriginInfo(file, null, false, false);
14479        }
14480
14481        static OriginInfo fromExistingFile(File file) {
14482            return new OriginInfo(file, null, false, true);
14483        }
14484
14485        static OriginInfo fromStagedFile(File file) {
14486            return new OriginInfo(file, null, true, false);
14487        }
14488
14489        static OriginInfo fromStagedContainer(String cid) {
14490            return new OriginInfo(null, cid, true, false);
14491        }
14492
14493        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14494            this.file = file;
14495            this.cid = cid;
14496            this.staged = staged;
14497            this.existing = existing;
14498
14499            if (cid != null) {
14500                resolvedPath = PackageHelper.getSdDir(cid);
14501                resolvedFile = new File(resolvedPath);
14502            } else if (file != null) {
14503                resolvedPath = file.getAbsolutePath();
14504                resolvedFile = file;
14505            } else {
14506                resolvedPath = null;
14507                resolvedFile = null;
14508            }
14509        }
14510    }
14511
14512    static class MoveInfo {
14513        final int moveId;
14514        final String fromUuid;
14515        final String toUuid;
14516        final String packageName;
14517        final String dataAppName;
14518        final int appId;
14519        final String seinfo;
14520        final int targetSdkVersion;
14521
14522        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14523                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14524            this.moveId = moveId;
14525            this.fromUuid = fromUuid;
14526            this.toUuid = toUuid;
14527            this.packageName = packageName;
14528            this.dataAppName = dataAppName;
14529            this.appId = appId;
14530            this.seinfo = seinfo;
14531            this.targetSdkVersion = targetSdkVersion;
14532        }
14533    }
14534
14535    static class VerificationInfo {
14536        /** A constant used to indicate that a uid value is not present. */
14537        public static final int NO_UID = -1;
14538
14539        /** URI referencing where the package was downloaded from. */
14540        final Uri originatingUri;
14541
14542        /** HTTP referrer URI associated with the originatingURI. */
14543        final Uri referrer;
14544
14545        /** UID of the application that the install request originated from. */
14546        final int originatingUid;
14547
14548        /** UID of application requesting the install */
14549        final int installerUid;
14550
14551        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14552            this.originatingUri = originatingUri;
14553            this.referrer = referrer;
14554            this.originatingUid = originatingUid;
14555            this.installerUid = installerUid;
14556        }
14557    }
14558
14559    class InstallParams extends HandlerParams {
14560        final OriginInfo origin;
14561        final MoveInfo move;
14562        final IPackageInstallObserver2 observer;
14563        int installFlags;
14564        final String installerPackageName;
14565        final String volumeUuid;
14566        private InstallArgs mArgs;
14567        private int mRet;
14568        final String packageAbiOverride;
14569        final String[] grantedRuntimePermissions;
14570        final VerificationInfo verificationInfo;
14571        final Certificate[][] certificates;
14572        final int installReason;
14573
14574        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14575                int installFlags, String installerPackageName, String volumeUuid,
14576                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14577                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14578            super(user);
14579            this.origin = origin;
14580            this.move = move;
14581            this.observer = observer;
14582            this.installFlags = installFlags;
14583            this.installerPackageName = installerPackageName;
14584            this.volumeUuid = volumeUuid;
14585            this.verificationInfo = verificationInfo;
14586            this.packageAbiOverride = packageAbiOverride;
14587            this.grantedRuntimePermissions = grantedPermissions;
14588            this.certificates = certificates;
14589            this.installReason = installReason;
14590        }
14591
14592        @Override
14593        public String toString() {
14594            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14595                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14596        }
14597
14598        private int installLocationPolicy(PackageInfoLite pkgLite) {
14599            String packageName = pkgLite.packageName;
14600            int installLocation = pkgLite.installLocation;
14601            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14602            // reader
14603            synchronized (mPackages) {
14604                // Currently installed package which the new package is attempting to replace or
14605                // null if no such package is installed.
14606                PackageParser.Package installedPkg = mPackages.get(packageName);
14607                // Package which currently owns the data which the new package will own if installed.
14608                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14609                // will be null whereas dataOwnerPkg will contain information about the package
14610                // which was uninstalled while keeping its data.
14611                PackageParser.Package dataOwnerPkg = installedPkg;
14612                if (dataOwnerPkg  == null) {
14613                    PackageSetting ps = mSettings.mPackages.get(packageName);
14614                    if (ps != null) {
14615                        dataOwnerPkg = ps.pkg;
14616                    }
14617                }
14618
14619                if (dataOwnerPkg != null) {
14620                    // If installed, the package will get access to data left on the device by its
14621                    // predecessor. As a security measure, this is permited only if this is not a
14622                    // version downgrade or if the predecessor package is marked as debuggable and
14623                    // a downgrade is explicitly requested.
14624                    //
14625                    // On debuggable platform builds, downgrades are permitted even for
14626                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14627                    // not offer security guarantees and thus it's OK to disable some security
14628                    // mechanisms to make debugging/testing easier on those builds. However, even on
14629                    // debuggable builds downgrades of packages are permitted only if requested via
14630                    // installFlags. This is because we aim to keep the behavior of debuggable
14631                    // platform builds as close as possible to the behavior of non-debuggable
14632                    // platform builds.
14633                    final boolean downgradeRequested =
14634                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14635                    final boolean packageDebuggable =
14636                                (dataOwnerPkg.applicationInfo.flags
14637                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14638                    final boolean downgradePermitted =
14639                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14640                    if (!downgradePermitted) {
14641                        try {
14642                            checkDowngrade(dataOwnerPkg, pkgLite);
14643                        } catch (PackageManagerException e) {
14644                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14645                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14646                        }
14647                    }
14648                }
14649
14650                if (installedPkg != null) {
14651                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14652                        // Check for updated system application.
14653                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14654                            if (onSd) {
14655                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14656                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14657                            }
14658                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14659                        } else {
14660                            if (onSd) {
14661                                // Install flag overrides everything.
14662                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14663                            }
14664                            // If current upgrade specifies particular preference
14665                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14666                                // Application explicitly specified internal.
14667                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14668                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14669                                // App explictly prefers external. Let policy decide
14670                            } else {
14671                                // Prefer previous location
14672                                if (isExternal(installedPkg)) {
14673                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14674                                }
14675                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14676                            }
14677                        }
14678                    } else {
14679                        // Invalid install. Return error code
14680                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14681                    }
14682                }
14683            }
14684            // All the special cases have been taken care of.
14685            // Return result based on recommended install location.
14686            if (onSd) {
14687                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14688            }
14689            return pkgLite.recommendedInstallLocation;
14690        }
14691
14692        /*
14693         * Invoke remote method to get package information and install
14694         * location values. Override install location based on default
14695         * policy if needed and then create install arguments based
14696         * on the install location.
14697         */
14698        public void handleStartCopy() throws RemoteException {
14699            int ret = PackageManager.INSTALL_SUCCEEDED;
14700
14701            // If we're already staged, we've firmly committed to an install location
14702            if (origin.staged) {
14703                if (origin.file != null) {
14704                    installFlags |= PackageManager.INSTALL_INTERNAL;
14705                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14706                } else if (origin.cid != null) {
14707                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14708                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14709                } else {
14710                    throw new IllegalStateException("Invalid stage location");
14711                }
14712            }
14713
14714            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14715            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14716            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14717            PackageInfoLite pkgLite = null;
14718
14719            if (onInt && onSd) {
14720                // Check if both bits are set.
14721                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14722                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14723            } else if (onSd && ephemeral) {
14724                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14725                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14726            } else {
14727                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14728                        packageAbiOverride);
14729
14730                if (DEBUG_EPHEMERAL && ephemeral) {
14731                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14732                }
14733
14734                /*
14735                 * If we have too little free space, try to free cache
14736                 * before giving up.
14737                 */
14738                if (!origin.staged && pkgLite.recommendedInstallLocation
14739                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14740                    // TODO: focus freeing disk space on the target device
14741                    final StorageManager storage = StorageManager.from(mContext);
14742                    final long lowThreshold = storage.getStorageLowBytes(
14743                            Environment.getDataDirectory());
14744
14745                    final long sizeBytes = mContainerService.calculateInstalledSize(
14746                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14747
14748                    try {
14749                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14750                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14751                                installFlags, packageAbiOverride);
14752                    } catch (InstallerException e) {
14753                        Slog.w(TAG, "Failed to free cache", e);
14754                    }
14755
14756                    /*
14757                     * The cache free must have deleted the file we
14758                     * downloaded to install.
14759                     *
14760                     * TODO: fix the "freeCache" call to not delete
14761                     *       the file we care about.
14762                     */
14763                    if (pkgLite.recommendedInstallLocation
14764                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14765                        pkgLite.recommendedInstallLocation
14766                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14767                    }
14768                }
14769            }
14770
14771            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14772                int loc = pkgLite.recommendedInstallLocation;
14773                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14774                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14775                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14776                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14777                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14778                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14779                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14780                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14781                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14782                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14783                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14784                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14785                } else {
14786                    // Override with defaults if needed.
14787                    loc = installLocationPolicy(pkgLite);
14788                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14789                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14790                    } else if (!onSd && !onInt) {
14791                        // Override install location with flags
14792                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14793                            // Set the flag to install on external media.
14794                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14795                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14796                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14797                            if (DEBUG_EPHEMERAL) {
14798                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14799                            }
14800                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14801                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14802                                    |PackageManager.INSTALL_INTERNAL);
14803                        } else {
14804                            // Make sure the flag for installing on external
14805                            // media is unset
14806                            installFlags |= PackageManager.INSTALL_INTERNAL;
14807                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14808                        }
14809                    }
14810                }
14811            }
14812
14813            final InstallArgs args = createInstallArgs(this);
14814            mArgs = args;
14815
14816            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14817                // TODO: http://b/22976637
14818                // Apps installed for "all" users use the device owner to verify the app
14819                UserHandle verifierUser = getUser();
14820                if (verifierUser == UserHandle.ALL) {
14821                    verifierUser = UserHandle.SYSTEM;
14822                }
14823
14824                /*
14825                 * Determine if we have any installed package verifiers. If we
14826                 * do, then we'll defer to them to verify the packages.
14827                 */
14828                final int requiredUid = mRequiredVerifierPackage == null ? -1
14829                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14830                                verifierUser.getIdentifier());
14831                if (!origin.existing && requiredUid != -1
14832                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14833                    final Intent verification = new Intent(
14834                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14835                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14836                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14837                            PACKAGE_MIME_TYPE);
14838                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14839
14840                    // Query all live verifiers based on current user state
14841                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14842                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14843
14844                    if (DEBUG_VERIFY) {
14845                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14846                                + verification.toString() + " with " + pkgLite.verifiers.length
14847                                + " optional verifiers");
14848                    }
14849
14850                    final int verificationId = mPendingVerificationToken++;
14851
14852                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14853
14854                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14855                            installerPackageName);
14856
14857                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14858                            installFlags);
14859
14860                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14861                            pkgLite.packageName);
14862
14863                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14864                            pkgLite.versionCode);
14865
14866                    if (verificationInfo != null) {
14867                        if (verificationInfo.originatingUri != null) {
14868                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14869                                    verificationInfo.originatingUri);
14870                        }
14871                        if (verificationInfo.referrer != null) {
14872                            verification.putExtra(Intent.EXTRA_REFERRER,
14873                                    verificationInfo.referrer);
14874                        }
14875                        if (verificationInfo.originatingUid >= 0) {
14876                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14877                                    verificationInfo.originatingUid);
14878                        }
14879                        if (verificationInfo.installerUid >= 0) {
14880                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14881                                    verificationInfo.installerUid);
14882                        }
14883                    }
14884
14885                    final PackageVerificationState verificationState = new PackageVerificationState(
14886                            requiredUid, args);
14887
14888                    mPendingVerification.append(verificationId, verificationState);
14889
14890                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14891                            receivers, verificationState);
14892
14893                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14894                    final long idleDuration = getVerificationTimeout();
14895
14896                    /*
14897                     * If any sufficient verifiers were listed in the package
14898                     * manifest, attempt to ask them.
14899                     */
14900                    if (sufficientVerifiers != null) {
14901                        final int N = sufficientVerifiers.size();
14902                        if (N == 0) {
14903                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14904                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14905                        } else {
14906                            for (int i = 0; i < N; i++) {
14907                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14908                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14909                                        verifierComponent.getPackageName(), idleDuration,
14910                                        verifierUser.getIdentifier(), false, "package verifier");
14911
14912                                final Intent sufficientIntent = new Intent(verification);
14913                                sufficientIntent.setComponent(verifierComponent);
14914                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14915                            }
14916                        }
14917                    }
14918
14919                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14920                            mRequiredVerifierPackage, receivers);
14921                    if (ret == PackageManager.INSTALL_SUCCEEDED
14922                            && mRequiredVerifierPackage != null) {
14923                        Trace.asyncTraceBegin(
14924                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14925                        /*
14926                         * Send the intent to the required verification agent,
14927                         * but only start the verification timeout after the
14928                         * target BroadcastReceivers have run.
14929                         */
14930                        verification.setComponent(requiredVerifierComponent);
14931                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14932                                mRequiredVerifierPackage, idleDuration,
14933                                verifierUser.getIdentifier(), false, "package verifier");
14934                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14935                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14936                                new BroadcastReceiver() {
14937                                    @Override
14938                                    public void onReceive(Context context, Intent intent) {
14939                                        final Message msg = mHandler
14940                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14941                                        msg.arg1 = verificationId;
14942                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14943                                    }
14944                                }, null, 0, null, null);
14945
14946                        /*
14947                         * We don't want the copy to proceed until verification
14948                         * succeeds, so null out this field.
14949                         */
14950                        mArgs = null;
14951                    }
14952                } else {
14953                    /*
14954                     * No package verification is enabled, so immediately start
14955                     * the remote call to initiate copy using temporary file.
14956                     */
14957                    ret = args.copyApk(mContainerService, true);
14958                }
14959            }
14960
14961            mRet = ret;
14962        }
14963
14964        @Override
14965        void handleReturnCode() {
14966            // If mArgs is null, then MCS couldn't be reached. When it
14967            // reconnects, it will try again to install. At that point, this
14968            // will succeed.
14969            if (mArgs != null) {
14970                processPendingInstall(mArgs, mRet);
14971            }
14972        }
14973
14974        @Override
14975        void handleServiceError() {
14976            mArgs = createInstallArgs(this);
14977            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14978        }
14979
14980        public boolean isForwardLocked() {
14981            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14982        }
14983    }
14984
14985    /**
14986     * Used during creation of InstallArgs
14987     *
14988     * @param installFlags package installation flags
14989     * @return true if should be installed on external storage
14990     */
14991    private static boolean installOnExternalAsec(int installFlags) {
14992        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14993            return false;
14994        }
14995        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14996            return true;
14997        }
14998        return false;
14999    }
15000
15001    /**
15002     * Used during creation of InstallArgs
15003     *
15004     * @param installFlags package installation flags
15005     * @return true if should be installed as forward locked
15006     */
15007    private static boolean installForwardLocked(int installFlags) {
15008        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15009    }
15010
15011    private InstallArgs createInstallArgs(InstallParams params) {
15012        if (params.move != null) {
15013            return new MoveInstallArgs(params);
15014        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15015            return new AsecInstallArgs(params);
15016        } else {
15017            return new FileInstallArgs(params);
15018        }
15019    }
15020
15021    /**
15022     * Create args that describe an existing installed package. Typically used
15023     * when cleaning up old installs, or used as a move source.
15024     */
15025    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15026            String resourcePath, String[] instructionSets) {
15027        final boolean isInAsec;
15028        if (installOnExternalAsec(installFlags)) {
15029            /* Apps on SD card are always in ASEC containers. */
15030            isInAsec = true;
15031        } else if (installForwardLocked(installFlags)
15032                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15033            /*
15034             * Forward-locked apps are only in ASEC containers if they're the
15035             * new style
15036             */
15037            isInAsec = true;
15038        } else {
15039            isInAsec = false;
15040        }
15041
15042        if (isInAsec) {
15043            return new AsecInstallArgs(codePath, instructionSets,
15044                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15045        } else {
15046            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15047        }
15048    }
15049
15050    static abstract class InstallArgs {
15051        /** @see InstallParams#origin */
15052        final OriginInfo origin;
15053        /** @see InstallParams#move */
15054        final MoveInfo move;
15055
15056        final IPackageInstallObserver2 observer;
15057        // Always refers to PackageManager flags only
15058        final int installFlags;
15059        final String installerPackageName;
15060        final String volumeUuid;
15061        final UserHandle user;
15062        final String abiOverride;
15063        final String[] installGrantPermissions;
15064        /** If non-null, drop an async trace when the install completes */
15065        final String traceMethod;
15066        final int traceCookie;
15067        final Certificate[][] certificates;
15068        final int installReason;
15069
15070        // The list of instruction sets supported by this app. This is currently
15071        // only used during the rmdex() phase to clean up resources. We can get rid of this
15072        // if we move dex files under the common app path.
15073        /* nullable */ String[] instructionSets;
15074
15075        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15076                int installFlags, String installerPackageName, String volumeUuid,
15077                UserHandle user, String[] instructionSets,
15078                String abiOverride, String[] installGrantPermissions,
15079                String traceMethod, int traceCookie, Certificate[][] certificates,
15080                int installReason) {
15081            this.origin = origin;
15082            this.move = move;
15083            this.installFlags = installFlags;
15084            this.observer = observer;
15085            this.installerPackageName = installerPackageName;
15086            this.volumeUuid = volumeUuid;
15087            this.user = user;
15088            this.instructionSets = instructionSets;
15089            this.abiOverride = abiOverride;
15090            this.installGrantPermissions = installGrantPermissions;
15091            this.traceMethod = traceMethod;
15092            this.traceCookie = traceCookie;
15093            this.certificates = certificates;
15094            this.installReason = installReason;
15095        }
15096
15097        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15098        abstract int doPreInstall(int status);
15099
15100        /**
15101         * Rename package into final resting place. All paths on the given
15102         * scanned package should be updated to reflect the rename.
15103         */
15104        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15105        abstract int doPostInstall(int status, int uid);
15106
15107        /** @see PackageSettingBase#codePathString */
15108        abstract String getCodePath();
15109        /** @see PackageSettingBase#resourcePathString */
15110        abstract String getResourcePath();
15111
15112        // Need installer lock especially for dex file removal.
15113        abstract void cleanUpResourcesLI();
15114        abstract boolean doPostDeleteLI(boolean delete);
15115
15116        /**
15117         * Called before the source arguments are copied. This is used mostly
15118         * for MoveParams when it needs to read the source file to put it in the
15119         * destination.
15120         */
15121        int doPreCopy() {
15122            return PackageManager.INSTALL_SUCCEEDED;
15123        }
15124
15125        /**
15126         * Called after the source arguments are copied. This is used mostly for
15127         * MoveParams when it needs to read the source file to put it in the
15128         * destination.
15129         */
15130        int doPostCopy(int uid) {
15131            return PackageManager.INSTALL_SUCCEEDED;
15132        }
15133
15134        protected boolean isFwdLocked() {
15135            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15136        }
15137
15138        protected boolean isExternalAsec() {
15139            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15140        }
15141
15142        protected boolean isEphemeral() {
15143            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15144        }
15145
15146        UserHandle getUser() {
15147            return user;
15148        }
15149    }
15150
15151    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15152        if (!allCodePaths.isEmpty()) {
15153            if (instructionSets == null) {
15154                throw new IllegalStateException("instructionSet == null");
15155            }
15156            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15157            for (String codePath : allCodePaths) {
15158                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15159                    try {
15160                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15161                    } catch (InstallerException ignored) {
15162                    }
15163                }
15164            }
15165        }
15166    }
15167
15168    /**
15169     * Logic to handle installation of non-ASEC applications, including copying
15170     * and renaming logic.
15171     */
15172    class FileInstallArgs extends InstallArgs {
15173        private File codeFile;
15174        private File resourceFile;
15175
15176        // Example topology:
15177        // /data/app/com.example/base.apk
15178        // /data/app/com.example/split_foo.apk
15179        // /data/app/com.example/lib/arm/libfoo.so
15180        // /data/app/com.example/lib/arm64/libfoo.so
15181        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15182
15183        /** New install */
15184        FileInstallArgs(InstallParams params) {
15185            super(params.origin, params.move, params.observer, params.installFlags,
15186                    params.installerPackageName, params.volumeUuid,
15187                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15188                    params.grantedRuntimePermissions,
15189                    params.traceMethod, params.traceCookie, params.certificates,
15190                    params.installReason);
15191            if (isFwdLocked()) {
15192                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15193            }
15194        }
15195
15196        /** Existing install */
15197        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15198            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15199                    null, null, null, 0, null /*certificates*/,
15200                    PackageManager.INSTALL_REASON_UNKNOWN);
15201            this.codeFile = (codePath != null) ? new File(codePath) : null;
15202            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15203        }
15204
15205        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15206            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15207            try {
15208                return doCopyApk(imcs, temp);
15209            } finally {
15210                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15211            }
15212        }
15213
15214        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15215            if (origin.staged) {
15216                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15217                codeFile = origin.file;
15218                resourceFile = origin.file;
15219                return PackageManager.INSTALL_SUCCEEDED;
15220            }
15221
15222            try {
15223                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15224                final File tempDir =
15225                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15226                codeFile = tempDir;
15227                resourceFile = tempDir;
15228            } catch (IOException e) {
15229                Slog.w(TAG, "Failed to create copy file: " + e);
15230                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15231            }
15232
15233            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15234                @Override
15235                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15236                    if (!FileUtils.isValidExtFilename(name)) {
15237                        throw new IllegalArgumentException("Invalid filename: " + name);
15238                    }
15239                    try {
15240                        final File file = new File(codeFile, name);
15241                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15242                                O_RDWR | O_CREAT, 0644);
15243                        Os.chmod(file.getAbsolutePath(), 0644);
15244                        return new ParcelFileDescriptor(fd);
15245                    } catch (ErrnoException e) {
15246                        throw new RemoteException("Failed to open: " + e.getMessage());
15247                    }
15248                }
15249            };
15250
15251            int ret = PackageManager.INSTALL_SUCCEEDED;
15252            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15253            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15254                Slog.e(TAG, "Failed to copy package");
15255                return ret;
15256            }
15257
15258            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15259            NativeLibraryHelper.Handle handle = null;
15260            try {
15261                handle = NativeLibraryHelper.Handle.create(codeFile);
15262                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15263                        abiOverride);
15264            } catch (IOException e) {
15265                Slog.e(TAG, "Copying native libraries failed", e);
15266                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15267            } finally {
15268                IoUtils.closeQuietly(handle);
15269            }
15270
15271            return ret;
15272        }
15273
15274        int doPreInstall(int status) {
15275            if (status != PackageManager.INSTALL_SUCCEEDED) {
15276                cleanUp();
15277            }
15278            return status;
15279        }
15280
15281        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15282            if (status != PackageManager.INSTALL_SUCCEEDED) {
15283                cleanUp();
15284                return false;
15285            }
15286
15287            final File targetDir = codeFile.getParentFile();
15288            final File beforeCodeFile = codeFile;
15289            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15290
15291            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15292            try {
15293                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15294            } catch (ErrnoException e) {
15295                Slog.w(TAG, "Failed to rename", e);
15296                return false;
15297            }
15298
15299            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15300                Slog.w(TAG, "Failed to restorecon");
15301                return false;
15302            }
15303
15304            // Reflect the rename internally
15305            codeFile = afterCodeFile;
15306            resourceFile = afterCodeFile;
15307
15308            // Reflect the rename in scanned details
15309            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15310            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15311                    afterCodeFile, pkg.baseCodePath));
15312            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15313                    afterCodeFile, pkg.splitCodePaths));
15314
15315            // Reflect the rename in app info
15316            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15317            pkg.setApplicationInfoCodePath(pkg.codePath);
15318            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15319            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15320            pkg.setApplicationInfoResourcePath(pkg.codePath);
15321            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15322            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15323
15324            return true;
15325        }
15326
15327        int doPostInstall(int status, int uid) {
15328            if (status != PackageManager.INSTALL_SUCCEEDED) {
15329                cleanUp();
15330            }
15331            return status;
15332        }
15333
15334        @Override
15335        String getCodePath() {
15336            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15337        }
15338
15339        @Override
15340        String getResourcePath() {
15341            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15342        }
15343
15344        private boolean cleanUp() {
15345            if (codeFile == null || !codeFile.exists()) {
15346                return false;
15347            }
15348
15349            removeCodePathLI(codeFile);
15350
15351            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15352                resourceFile.delete();
15353            }
15354
15355            return true;
15356        }
15357
15358        void cleanUpResourcesLI() {
15359            // Try enumerating all code paths before deleting
15360            List<String> allCodePaths = Collections.EMPTY_LIST;
15361            if (codeFile != null && codeFile.exists()) {
15362                try {
15363                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15364                    allCodePaths = pkg.getAllCodePaths();
15365                } catch (PackageParserException e) {
15366                    // Ignored; we tried our best
15367                }
15368            }
15369
15370            cleanUp();
15371            removeDexFiles(allCodePaths, instructionSets);
15372        }
15373
15374        boolean doPostDeleteLI(boolean delete) {
15375            // XXX err, shouldn't we respect the delete flag?
15376            cleanUpResourcesLI();
15377            return true;
15378        }
15379    }
15380
15381    private boolean isAsecExternal(String cid) {
15382        final String asecPath = PackageHelper.getSdFilesystem(cid);
15383        return !asecPath.startsWith(mAsecInternalPath);
15384    }
15385
15386    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15387            PackageManagerException {
15388        if (copyRet < 0) {
15389            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15390                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15391                throw new PackageManagerException(copyRet, message);
15392            }
15393        }
15394    }
15395
15396    /**
15397     * Extract the StorageManagerService "container ID" from the full code path of an
15398     * .apk.
15399     */
15400    static String cidFromCodePath(String fullCodePath) {
15401        int eidx = fullCodePath.lastIndexOf("/");
15402        String subStr1 = fullCodePath.substring(0, eidx);
15403        int sidx = subStr1.lastIndexOf("/");
15404        return subStr1.substring(sidx+1, eidx);
15405    }
15406
15407    /**
15408     * Logic to handle installation of ASEC applications, including copying and
15409     * renaming logic.
15410     */
15411    class AsecInstallArgs extends InstallArgs {
15412        static final String RES_FILE_NAME = "pkg.apk";
15413        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15414
15415        String cid;
15416        String packagePath;
15417        String resourcePath;
15418
15419        /** New install */
15420        AsecInstallArgs(InstallParams params) {
15421            super(params.origin, params.move, params.observer, params.installFlags,
15422                    params.installerPackageName, params.volumeUuid,
15423                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15424                    params.grantedRuntimePermissions,
15425                    params.traceMethod, params.traceCookie, params.certificates,
15426                    params.installReason);
15427        }
15428
15429        /** Existing install */
15430        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15431                        boolean isExternal, boolean isForwardLocked) {
15432            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15433                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15434                    instructionSets, null, null, null, 0, null /*certificates*/,
15435                    PackageManager.INSTALL_REASON_UNKNOWN);
15436            // Hackily pretend we're still looking at a full code path
15437            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15438                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15439            }
15440
15441            // Extract cid from fullCodePath
15442            int eidx = fullCodePath.lastIndexOf("/");
15443            String subStr1 = fullCodePath.substring(0, eidx);
15444            int sidx = subStr1.lastIndexOf("/");
15445            cid = subStr1.substring(sidx+1, eidx);
15446            setMountPath(subStr1);
15447        }
15448
15449        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15450            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15451                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15452                    instructionSets, null, null, null, 0, null /*certificates*/,
15453                    PackageManager.INSTALL_REASON_UNKNOWN);
15454            this.cid = cid;
15455            setMountPath(PackageHelper.getSdDir(cid));
15456        }
15457
15458        void createCopyFile() {
15459            cid = mInstallerService.allocateExternalStageCidLegacy();
15460        }
15461
15462        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15463            if (origin.staged && origin.cid != null) {
15464                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15465                cid = origin.cid;
15466                setMountPath(PackageHelper.getSdDir(cid));
15467                return PackageManager.INSTALL_SUCCEEDED;
15468            }
15469
15470            if (temp) {
15471                createCopyFile();
15472            } else {
15473                /*
15474                 * Pre-emptively destroy the container since it's destroyed if
15475                 * copying fails due to it existing anyway.
15476                 */
15477                PackageHelper.destroySdDir(cid);
15478            }
15479
15480            final String newMountPath = imcs.copyPackageToContainer(
15481                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15482                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15483
15484            if (newMountPath != null) {
15485                setMountPath(newMountPath);
15486                return PackageManager.INSTALL_SUCCEEDED;
15487            } else {
15488                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15489            }
15490        }
15491
15492        @Override
15493        String getCodePath() {
15494            return packagePath;
15495        }
15496
15497        @Override
15498        String getResourcePath() {
15499            return resourcePath;
15500        }
15501
15502        int doPreInstall(int status) {
15503            if (status != PackageManager.INSTALL_SUCCEEDED) {
15504                // Destroy container
15505                PackageHelper.destroySdDir(cid);
15506            } else {
15507                boolean mounted = PackageHelper.isContainerMounted(cid);
15508                if (!mounted) {
15509                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15510                            Process.SYSTEM_UID);
15511                    if (newMountPath != null) {
15512                        setMountPath(newMountPath);
15513                    } else {
15514                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15515                    }
15516                }
15517            }
15518            return status;
15519        }
15520
15521        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15522            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15523            String newMountPath = null;
15524            if (PackageHelper.isContainerMounted(cid)) {
15525                // Unmount the container
15526                if (!PackageHelper.unMountSdDir(cid)) {
15527                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15528                    return false;
15529                }
15530            }
15531            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15532                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15533                        " which might be stale. Will try to clean up.");
15534                // Clean up the stale container and proceed to recreate.
15535                if (!PackageHelper.destroySdDir(newCacheId)) {
15536                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15537                    return false;
15538                }
15539                // Successfully cleaned up stale container. Try to rename again.
15540                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15541                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15542                            + " inspite of cleaning it up.");
15543                    return false;
15544                }
15545            }
15546            if (!PackageHelper.isContainerMounted(newCacheId)) {
15547                Slog.w(TAG, "Mounting container " + newCacheId);
15548                newMountPath = PackageHelper.mountSdDir(newCacheId,
15549                        getEncryptKey(), Process.SYSTEM_UID);
15550            } else {
15551                newMountPath = PackageHelper.getSdDir(newCacheId);
15552            }
15553            if (newMountPath == null) {
15554                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15555                return false;
15556            }
15557            Log.i(TAG, "Succesfully renamed " + cid +
15558                    " to " + newCacheId +
15559                    " at new path: " + newMountPath);
15560            cid = newCacheId;
15561
15562            final File beforeCodeFile = new File(packagePath);
15563            setMountPath(newMountPath);
15564            final File afterCodeFile = new File(packagePath);
15565
15566            // Reflect the rename in scanned details
15567            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15568            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15569                    afterCodeFile, pkg.baseCodePath));
15570            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15571                    afterCodeFile, pkg.splitCodePaths));
15572
15573            // Reflect the rename in app info
15574            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15575            pkg.setApplicationInfoCodePath(pkg.codePath);
15576            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15577            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15578            pkg.setApplicationInfoResourcePath(pkg.codePath);
15579            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15580            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15581
15582            return true;
15583        }
15584
15585        private void setMountPath(String mountPath) {
15586            final File mountFile = new File(mountPath);
15587
15588            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15589            if (monolithicFile.exists()) {
15590                packagePath = monolithicFile.getAbsolutePath();
15591                if (isFwdLocked()) {
15592                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15593                } else {
15594                    resourcePath = packagePath;
15595                }
15596            } else {
15597                packagePath = mountFile.getAbsolutePath();
15598                resourcePath = packagePath;
15599            }
15600        }
15601
15602        int doPostInstall(int status, int uid) {
15603            if (status != PackageManager.INSTALL_SUCCEEDED) {
15604                cleanUp();
15605            } else {
15606                final int groupOwner;
15607                final String protectedFile;
15608                if (isFwdLocked()) {
15609                    groupOwner = UserHandle.getSharedAppGid(uid);
15610                    protectedFile = RES_FILE_NAME;
15611                } else {
15612                    groupOwner = -1;
15613                    protectedFile = null;
15614                }
15615
15616                if (uid < Process.FIRST_APPLICATION_UID
15617                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15618                    Slog.e(TAG, "Failed to finalize " + cid);
15619                    PackageHelper.destroySdDir(cid);
15620                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15621                }
15622
15623                boolean mounted = PackageHelper.isContainerMounted(cid);
15624                if (!mounted) {
15625                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15626                }
15627            }
15628            return status;
15629        }
15630
15631        private void cleanUp() {
15632            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15633
15634            // Destroy secure container
15635            PackageHelper.destroySdDir(cid);
15636        }
15637
15638        private List<String> getAllCodePaths() {
15639            final File codeFile = new File(getCodePath());
15640            if (codeFile != null && codeFile.exists()) {
15641                try {
15642                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15643                    return pkg.getAllCodePaths();
15644                } catch (PackageParserException e) {
15645                    // Ignored; we tried our best
15646                }
15647            }
15648            return Collections.EMPTY_LIST;
15649        }
15650
15651        void cleanUpResourcesLI() {
15652            // Enumerate all code paths before deleting
15653            cleanUpResourcesLI(getAllCodePaths());
15654        }
15655
15656        private void cleanUpResourcesLI(List<String> allCodePaths) {
15657            cleanUp();
15658            removeDexFiles(allCodePaths, instructionSets);
15659        }
15660
15661        String getPackageName() {
15662            return getAsecPackageName(cid);
15663        }
15664
15665        boolean doPostDeleteLI(boolean delete) {
15666            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15667            final List<String> allCodePaths = getAllCodePaths();
15668            boolean mounted = PackageHelper.isContainerMounted(cid);
15669            if (mounted) {
15670                // Unmount first
15671                if (PackageHelper.unMountSdDir(cid)) {
15672                    mounted = false;
15673                }
15674            }
15675            if (!mounted && delete) {
15676                cleanUpResourcesLI(allCodePaths);
15677            }
15678            return !mounted;
15679        }
15680
15681        @Override
15682        int doPreCopy() {
15683            if (isFwdLocked()) {
15684                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15685                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15686                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15687                }
15688            }
15689
15690            return PackageManager.INSTALL_SUCCEEDED;
15691        }
15692
15693        @Override
15694        int doPostCopy(int uid) {
15695            if (isFwdLocked()) {
15696                if (uid < Process.FIRST_APPLICATION_UID
15697                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15698                                RES_FILE_NAME)) {
15699                    Slog.e(TAG, "Failed to finalize " + cid);
15700                    PackageHelper.destroySdDir(cid);
15701                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15702                }
15703            }
15704
15705            return PackageManager.INSTALL_SUCCEEDED;
15706        }
15707    }
15708
15709    /**
15710     * Logic to handle movement of existing installed applications.
15711     */
15712    class MoveInstallArgs extends InstallArgs {
15713        private File codeFile;
15714        private File resourceFile;
15715
15716        /** New install */
15717        MoveInstallArgs(InstallParams params) {
15718            super(params.origin, params.move, params.observer, params.installFlags,
15719                    params.installerPackageName, params.volumeUuid,
15720                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15721                    params.grantedRuntimePermissions,
15722                    params.traceMethod, params.traceCookie, params.certificates,
15723                    params.installReason);
15724        }
15725
15726        int copyApk(IMediaContainerService imcs, boolean temp) {
15727            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15728                    + move.fromUuid + " to " + move.toUuid);
15729            synchronized (mInstaller) {
15730                try {
15731                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15732                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15733                } catch (InstallerException e) {
15734                    Slog.w(TAG, "Failed to move app", e);
15735                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15736                }
15737            }
15738
15739            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15740            resourceFile = codeFile;
15741            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15742
15743            return PackageManager.INSTALL_SUCCEEDED;
15744        }
15745
15746        int doPreInstall(int status) {
15747            if (status != PackageManager.INSTALL_SUCCEEDED) {
15748                cleanUp(move.toUuid);
15749            }
15750            return status;
15751        }
15752
15753        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15754            if (status != PackageManager.INSTALL_SUCCEEDED) {
15755                cleanUp(move.toUuid);
15756                return false;
15757            }
15758
15759            // Reflect the move in app info
15760            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15761            pkg.setApplicationInfoCodePath(pkg.codePath);
15762            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15763            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15764            pkg.setApplicationInfoResourcePath(pkg.codePath);
15765            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15766            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15767
15768            return true;
15769        }
15770
15771        int doPostInstall(int status, int uid) {
15772            if (status == PackageManager.INSTALL_SUCCEEDED) {
15773                cleanUp(move.fromUuid);
15774            } else {
15775                cleanUp(move.toUuid);
15776            }
15777            return status;
15778        }
15779
15780        @Override
15781        String getCodePath() {
15782            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15783        }
15784
15785        @Override
15786        String getResourcePath() {
15787            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15788        }
15789
15790        private boolean cleanUp(String volumeUuid) {
15791            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15792                    move.dataAppName);
15793            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15794            final int[] userIds = sUserManager.getUserIds();
15795            synchronized (mInstallLock) {
15796                // Clean up both app data and code
15797                // All package moves are frozen until finished
15798                for (int userId : userIds) {
15799                    try {
15800                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15801                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15802                    } catch (InstallerException e) {
15803                        Slog.w(TAG, String.valueOf(e));
15804                    }
15805                }
15806                removeCodePathLI(codeFile);
15807            }
15808            return true;
15809        }
15810
15811        void cleanUpResourcesLI() {
15812            throw new UnsupportedOperationException();
15813        }
15814
15815        boolean doPostDeleteLI(boolean delete) {
15816            throw new UnsupportedOperationException();
15817        }
15818    }
15819
15820    static String getAsecPackageName(String packageCid) {
15821        int idx = packageCid.lastIndexOf("-");
15822        if (idx == -1) {
15823            return packageCid;
15824        }
15825        return packageCid.substring(0, idx);
15826    }
15827
15828    // Utility method used to create code paths based on package name and available index.
15829    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15830        String idxStr = "";
15831        int idx = 1;
15832        // Fall back to default value of idx=1 if prefix is not
15833        // part of oldCodePath
15834        if (oldCodePath != null) {
15835            String subStr = oldCodePath;
15836            // Drop the suffix right away
15837            if (suffix != null && subStr.endsWith(suffix)) {
15838                subStr = subStr.substring(0, subStr.length() - suffix.length());
15839            }
15840            // If oldCodePath already contains prefix find out the
15841            // ending index to either increment or decrement.
15842            int sidx = subStr.lastIndexOf(prefix);
15843            if (sidx != -1) {
15844                subStr = subStr.substring(sidx + prefix.length());
15845                if (subStr != null) {
15846                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15847                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15848                    }
15849                    try {
15850                        idx = Integer.parseInt(subStr);
15851                        if (idx <= 1) {
15852                            idx++;
15853                        } else {
15854                            idx--;
15855                        }
15856                    } catch(NumberFormatException e) {
15857                    }
15858                }
15859            }
15860        }
15861        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15862        return prefix + idxStr;
15863    }
15864
15865    private File getNextCodePath(File targetDir, String packageName) {
15866        File result;
15867        SecureRandom random = new SecureRandom();
15868        byte[] bytes = new byte[16];
15869        do {
15870            random.nextBytes(bytes);
15871            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15872            result = new File(targetDir, packageName + "-" + suffix);
15873        } while (result.exists());
15874        return result;
15875    }
15876
15877    // Utility method that returns the relative package path with respect
15878    // to the installation directory. Like say for /data/data/com.test-1.apk
15879    // string com.test-1 is returned.
15880    static String deriveCodePathName(String codePath) {
15881        if (codePath == null) {
15882            return null;
15883        }
15884        final File codeFile = new File(codePath);
15885        final String name = codeFile.getName();
15886        if (codeFile.isDirectory()) {
15887            return name;
15888        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15889            final int lastDot = name.lastIndexOf('.');
15890            return name.substring(0, lastDot);
15891        } else {
15892            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15893            return null;
15894        }
15895    }
15896
15897    static class PackageInstalledInfo {
15898        String name;
15899        int uid;
15900        // The set of users that originally had this package installed.
15901        int[] origUsers;
15902        // The set of users that now have this package installed.
15903        int[] newUsers;
15904        PackageParser.Package pkg;
15905        int returnCode;
15906        String returnMsg;
15907        PackageRemovedInfo removedInfo;
15908        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15909
15910        public void setError(int code, String msg) {
15911            setReturnCode(code);
15912            setReturnMessage(msg);
15913            Slog.w(TAG, msg);
15914        }
15915
15916        public void setError(String msg, PackageParserException e) {
15917            setReturnCode(e.error);
15918            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15919            Slog.w(TAG, msg, e);
15920        }
15921
15922        public void setError(String msg, PackageManagerException e) {
15923            returnCode = e.error;
15924            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15925            Slog.w(TAG, msg, e);
15926        }
15927
15928        public void setReturnCode(int returnCode) {
15929            this.returnCode = returnCode;
15930            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15931            for (int i = 0; i < childCount; i++) {
15932                addedChildPackages.valueAt(i).returnCode = returnCode;
15933            }
15934        }
15935
15936        private void setReturnMessage(String returnMsg) {
15937            this.returnMsg = returnMsg;
15938            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15939            for (int i = 0; i < childCount; i++) {
15940                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15941            }
15942        }
15943
15944        // In some error cases we want to convey more info back to the observer
15945        String origPackage;
15946        String origPermission;
15947    }
15948
15949    /*
15950     * Install a non-existing package.
15951     */
15952    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15953            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15954            PackageInstalledInfo res, int installReason) {
15955        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15956
15957        // Remember this for later, in case we need to rollback this install
15958        String pkgName = pkg.packageName;
15959
15960        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15961
15962        synchronized(mPackages) {
15963            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15964            if (renamedPackage != null) {
15965                // A package with the same name is already installed, though
15966                // it has been renamed to an older name.  The package we
15967                // are trying to install should be installed as an update to
15968                // the existing one, but that has not been requested, so bail.
15969                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15970                        + " without first uninstalling package running as "
15971                        + renamedPackage);
15972                return;
15973            }
15974            if (mPackages.containsKey(pkgName)) {
15975                // Don't allow installation over an existing package with the same name.
15976                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15977                        + " without first uninstalling.");
15978                return;
15979            }
15980        }
15981
15982        try {
15983            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15984                    System.currentTimeMillis(), user);
15985
15986            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15987
15988            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15989                prepareAppDataAfterInstallLIF(newPackage);
15990
15991            } else {
15992                // Remove package from internal structures, but keep around any
15993                // data that might have already existed
15994                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15995                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15996            }
15997        } catch (PackageManagerException e) {
15998            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15999        }
16000
16001        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16002    }
16003
16004    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16005        // Can't rotate keys during boot or if sharedUser.
16006        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16007                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16008            return false;
16009        }
16010        // app is using upgradeKeySets; make sure all are valid
16011        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16012        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16013        for (int i = 0; i < upgradeKeySets.length; i++) {
16014            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16015                Slog.wtf(TAG, "Package "
16016                         + (oldPs.name != null ? oldPs.name : "<null>")
16017                         + " contains upgrade-key-set reference to unknown key-set: "
16018                         + upgradeKeySets[i]
16019                         + " reverting to signatures check.");
16020                return false;
16021            }
16022        }
16023        return true;
16024    }
16025
16026    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16027        // Upgrade keysets are being used.  Determine if new package has a superset of the
16028        // required keys.
16029        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16030        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16031        for (int i = 0; i < upgradeKeySets.length; i++) {
16032            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16033            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16034                return true;
16035            }
16036        }
16037        return false;
16038    }
16039
16040    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16041        try (DigestInputStream digestStream =
16042                new DigestInputStream(new FileInputStream(file), digest)) {
16043            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16044        }
16045    }
16046
16047    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16048            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16049            int installReason) {
16050        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16051
16052        final PackageParser.Package oldPackage;
16053        final String pkgName = pkg.packageName;
16054        final int[] allUsers;
16055        final int[] installedUsers;
16056
16057        synchronized(mPackages) {
16058            oldPackage = mPackages.get(pkgName);
16059            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16060
16061            // don't allow upgrade to target a release SDK from a pre-release SDK
16062            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16063                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16064            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16065                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16066            if (oldTargetsPreRelease
16067                    && !newTargetsPreRelease
16068                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16069                Slog.w(TAG, "Can't install package targeting released sdk");
16070                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16071                return;
16072            }
16073
16074            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16075
16076            // verify signatures are valid
16077            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16078                if (!checkUpgradeKeySetLP(ps, pkg)) {
16079                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16080                            "New package not signed by keys specified by upgrade-keysets: "
16081                                    + pkgName);
16082                    return;
16083                }
16084            } else {
16085                // default to original signature matching
16086                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16087                        != PackageManager.SIGNATURE_MATCH) {
16088                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16089                            "New package has a different signature: " + pkgName);
16090                    return;
16091                }
16092            }
16093
16094            // don't allow a system upgrade unless the upgrade hash matches
16095            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16096                byte[] digestBytes = null;
16097                try {
16098                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16099                    updateDigest(digest, new File(pkg.baseCodePath));
16100                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16101                        for (String path : pkg.splitCodePaths) {
16102                            updateDigest(digest, new File(path));
16103                        }
16104                    }
16105                    digestBytes = digest.digest();
16106                } catch (NoSuchAlgorithmException | IOException e) {
16107                    res.setError(INSTALL_FAILED_INVALID_APK,
16108                            "Could not compute hash: " + pkgName);
16109                    return;
16110                }
16111                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16112                    res.setError(INSTALL_FAILED_INVALID_APK,
16113                            "New package fails restrict-update check: " + pkgName);
16114                    return;
16115                }
16116                // retain upgrade restriction
16117                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16118            }
16119
16120            // Check for shared user id changes
16121            String invalidPackageName =
16122                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16123            if (invalidPackageName != null) {
16124                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16125                        "Package " + invalidPackageName + " tried to change user "
16126                                + oldPackage.mSharedUserId);
16127                return;
16128            }
16129
16130            // In case of rollback, remember per-user/profile install state
16131            allUsers = sUserManager.getUserIds();
16132            installedUsers = ps.queryInstalledUsers(allUsers, true);
16133
16134            // don't allow an upgrade from full to ephemeral
16135            if (isInstantApp) {
16136                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16137                    for (int currentUser : allUsers) {
16138                        if (!ps.getInstantApp(currentUser)) {
16139                            // can't downgrade from full to instant
16140                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16141                                    + " for user: " + currentUser);
16142                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16143                            return;
16144                        }
16145                    }
16146                } else if (!ps.getInstantApp(user.getIdentifier())) {
16147                    // can't downgrade from full to instant
16148                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16149                            + " for user: " + user.getIdentifier());
16150                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16151                    return;
16152                }
16153            }
16154        }
16155
16156        // Update what is removed
16157        res.removedInfo = new PackageRemovedInfo();
16158        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16159        res.removedInfo.removedPackage = oldPackage.packageName;
16160        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16161        res.removedInfo.isUpdate = true;
16162        res.removedInfo.origUsers = installedUsers;
16163        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
16164        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16165        for (int i = 0; i < installedUsers.length; i++) {
16166            final int userId = installedUsers[i];
16167            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16168        }
16169
16170        final int childCount = (oldPackage.childPackages != null)
16171                ? oldPackage.childPackages.size() : 0;
16172        for (int i = 0; i < childCount; i++) {
16173            boolean childPackageUpdated = false;
16174            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16175            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16176            if (res.addedChildPackages != null) {
16177                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16178                if (childRes != null) {
16179                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16180                    childRes.removedInfo.removedPackage = childPkg.packageName;
16181                    childRes.removedInfo.isUpdate = true;
16182                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16183                    childPackageUpdated = true;
16184                }
16185            }
16186            if (!childPackageUpdated) {
16187                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
16188                childRemovedRes.removedPackage = childPkg.packageName;
16189                childRemovedRes.isUpdate = false;
16190                childRemovedRes.dataRemoved = true;
16191                synchronized (mPackages) {
16192                    if (childPs != null) {
16193                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16194                    }
16195                }
16196                if (res.removedInfo.removedChildPackages == null) {
16197                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16198                }
16199                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16200            }
16201        }
16202
16203        boolean sysPkg = (isSystemApp(oldPackage));
16204        if (sysPkg) {
16205            // Set the system/privileged flags as needed
16206            final boolean privileged =
16207                    (oldPackage.applicationInfo.privateFlags
16208                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16209            final int systemPolicyFlags = policyFlags
16210                    | PackageParser.PARSE_IS_SYSTEM
16211                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16212
16213            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16214                    user, allUsers, installerPackageName, res, installReason);
16215        } else {
16216            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16217                    user, allUsers, installerPackageName, res, installReason);
16218        }
16219    }
16220
16221    public List<String> getPreviousCodePaths(String packageName) {
16222        final PackageSetting ps = mSettings.mPackages.get(packageName);
16223        final List<String> result = new ArrayList<String>();
16224        if (ps != null && ps.oldCodePaths != null) {
16225            result.addAll(ps.oldCodePaths);
16226        }
16227        return result;
16228    }
16229
16230    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16231            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16232            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16233            int installReason) {
16234        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16235                + deletedPackage);
16236
16237        String pkgName = deletedPackage.packageName;
16238        boolean deletedPkg = true;
16239        boolean addedPkg = false;
16240        boolean updatedSettings = false;
16241        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16242        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16243                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16244
16245        final long origUpdateTime = (pkg.mExtras != null)
16246                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16247
16248        // First delete the existing package while retaining the data directory
16249        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16250                res.removedInfo, true, pkg)) {
16251            // If the existing package wasn't successfully deleted
16252            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16253            deletedPkg = false;
16254        } else {
16255            // Successfully deleted the old package; proceed with replace.
16256
16257            // If deleted package lived in a container, give users a chance to
16258            // relinquish resources before killing.
16259            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16260                if (DEBUG_INSTALL) {
16261                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16262                }
16263                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16264                final ArrayList<String> pkgList = new ArrayList<String>(1);
16265                pkgList.add(deletedPackage.applicationInfo.packageName);
16266                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16267            }
16268
16269            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16270                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16271            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16272
16273            try {
16274                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16275                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16276                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16277                        installReason);
16278
16279                // Update the in-memory copy of the previous code paths.
16280                PackageSetting ps = mSettings.mPackages.get(pkgName);
16281                if (!killApp) {
16282                    if (ps.oldCodePaths == null) {
16283                        ps.oldCodePaths = new ArraySet<>();
16284                    }
16285                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16286                    if (deletedPackage.splitCodePaths != null) {
16287                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16288                    }
16289                } else {
16290                    ps.oldCodePaths = null;
16291                }
16292                if (ps.childPackageNames != null) {
16293                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16294                        final String childPkgName = ps.childPackageNames.get(i);
16295                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16296                        childPs.oldCodePaths = ps.oldCodePaths;
16297                    }
16298                }
16299                // set instant app status, but, only if it's explicitly specified
16300                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16301                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16302                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16303                prepareAppDataAfterInstallLIF(newPackage);
16304                addedPkg = true;
16305                mDexManager.notifyPackageUpdated(newPackage.packageName,
16306                        newPackage.baseCodePath, newPackage.splitCodePaths);
16307            } catch (PackageManagerException e) {
16308                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16309            }
16310        }
16311
16312        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16313            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16314
16315            // Revert all internal state mutations and added folders for the failed install
16316            if (addedPkg) {
16317                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16318                        res.removedInfo, true, null);
16319            }
16320
16321            // Restore the old package
16322            if (deletedPkg) {
16323                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16324                File restoreFile = new File(deletedPackage.codePath);
16325                // Parse old package
16326                boolean oldExternal = isExternal(deletedPackage);
16327                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16328                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16329                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16330                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16331                try {
16332                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16333                            null);
16334                } catch (PackageManagerException e) {
16335                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16336                            + e.getMessage());
16337                    return;
16338                }
16339
16340                synchronized (mPackages) {
16341                    // Ensure the installer package name up to date
16342                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16343
16344                    // Update permissions for restored package
16345                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16346
16347                    mSettings.writeLPr();
16348                }
16349
16350                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16351            }
16352        } else {
16353            synchronized (mPackages) {
16354                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16355                if (ps != null) {
16356                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16357                    if (res.removedInfo.removedChildPackages != null) {
16358                        final int childCount = res.removedInfo.removedChildPackages.size();
16359                        // Iterate in reverse as we may modify the collection
16360                        for (int i = childCount - 1; i >= 0; i--) {
16361                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16362                            if (res.addedChildPackages.containsKey(childPackageName)) {
16363                                res.removedInfo.removedChildPackages.removeAt(i);
16364                            } else {
16365                                PackageRemovedInfo childInfo = res.removedInfo
16366                                        .removedChildPackages.valueAt(i);
16367                                childInfo.removedForAllUsers = mPackages.get(
16368                                        childInfo.removedPackage) == null;
16369                            }
16370                        }
16371                    }
16372                }
16373            }
16374        }
16375    }
16376
16377    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16378            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16379            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16380            int installReason) {
16381        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16382                + ", old=" + deletedPackage);
16383
16384        final boolean disabledSystem;
16385
16386        // Remove existing system package
16387        removePackageLI(deletedPackage, true);
16388
16389        synchronized (mPackages) {
16390            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16391        }
16392        if (!disabledSystem) {
16393            // We didn't need to disable the .apk as a current system package,
16394            // which means we are replacing another update that is already
16395            // installed.  We need to make sure to delete the older one's .apk.
16396            res.removedInfo.args = createInstallArgsForExisting(0,
16397                    deletedPackage.applicationInfo.getCodePath(),
16398                    deletedPackage.applicationInfo.getResourcePath(),
16399                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16400        } else {
16401            res.removedInfo.args = null;
16402        }
16403
16404        // Successfully disabled the old package. Now proceed with re-installation
16405        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16406                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16407        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16408
16409        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16410        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16411                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16412
16413        PackageParser.Package newPackage = null;
16414        try {
16415            // Add the package to the internal data structures
16416            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16417
16418            // Set the update and install times
16419            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16420            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16421                    System.currentTimeMillis());
16422
16423            // Update the package dynamic state if succeeded
16424            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16425                // Now that the install succeeded make sure we remove data
16426                // directories for any child package the update removed.
16427                final int deletedChildCount = (deletedPackage.childPackages != null)
16428                        ? deletedPackage.childPackages.size() : 0;
16429                final int newChildCount = (newPackage.childPackages != null)
16430                        ? newPackage.childPackages.size() : 0;
16431                for (int i = 0; i < deletedChildCount; i++) {
16432                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16433                    boolean childPackageDeleted = true;
16434                    for (int j = 0; j < newChildCount; j++) {
16435                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16436                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16437                            childPackageDeleted = false;
16438                            break;
16439                        }
16440                    }
16441                    if (childPackageDeleted) {
16442                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16443                                deletedChildPkg.packageName);
16444                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16445                            PackageRemovedInfo removedChildRes = res.removedInfo
16446                                    .removedChildPackages.get(deletedChildPkg.packageName);
16447                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16448                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16449                        }
16450                    }
16451                }
16452
16453                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16454                        installReason);
16455                prepareAppDataAfterInstallLIF(newPackage);
16456
16457                mDexManager.notifyPackageUpdated(newPackage.packageName,
16458                            newPackage.baseCodePath, newPackage.splitCodePaths);
16459            }
16460        } catch (PackageManagerException e) {
16461            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16462            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16463        }
16464
16465        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16466            // Re installation failed. Restore old information
16467            // Remove new pkg information
16468            if (newPackage != null) {
16469                removeInstalledPackageLI(newPackage, true);
16470            }
16471            // Add back the old system package
16472            try {
16473                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16474            } catch (PackageManagerException e) {
16475                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16476            }
16477
16478            synchronized (mPackages) {
16479                if (disabledSystem) {
16480                    enableSystemPackageLPw(deletedPackage);
16481                }
16482
16483                // Ensure the installer package name up to date
16484                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16485
16486                // Update permissions for restored package
16487                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16488
16489                mSettings.writeLPr();
16490            }
16491
16492            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16493                    + " after failed upgrade");
16494        }
16495    }
16496
16497    /**
16498     * Checks whether the parent or any of the child packages have a change shared
16499     * user. For a package to be a valid update the shred users of the parent and
16500     * the children should match. We may later support changing child shared users.
16501     * @param oldPkg The updated package.
16502     * @param newPkg The update package.
16503     * @return The shared user that change between the versions.
16504     */
16505    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16506            PackageParser.Package newPkg) {
16507        // Check parent shared user
16508        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16509            return newPkg.packageName;
16510        }
16511        // Check child shared users
16512        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16513        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16514        for (int i = 0; i < newChildCount; i++) {
16515            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16516            // If this child was present, did it have the same shared user?
16517            for (int j = 0; j < oldChildCount; j++) {
16518                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16519                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16520                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16521                    return newChildPkg.packageName;
16522                }
16523            }
16524        }
16525        return null;
16526    }
16527
16528    private void removeNativeBinariesLI(PackageSetting ps) {
16529        // Remove the lib path for the parent package
16530        if (ps != null) {
16531            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16532            // Remove the lib path for the child packages
16533            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16534            for (int i = 0; i < childCount; i++) {
16535                PackageSetting childPs = null;
16536                synchronized (mPackages) {
16537                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16538                }
16539                if (childPs != null) {
16540                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16541                            .legacyNativeLibraryPathString);
16542                }
16543            }
16544        }
16545    }
16546
16547    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16548        // Enable the parent package
16549        mSettings.enableSystemPackageLPw(pkg.packageName);
16550        // Enable the child packages
16551        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16552        for (int i = 0; i < childCount; i++) {
16553            PackageParser.Package childPkg = pkg.childPackages.get(i);
16554            mSettings.enableSystemPackageLPw(childPkg.packageName);
16555        }
16556    }
16557
16558    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16559            PackageParser.Package newPkg) {
16560        // Disable the parent package (parent always replaced)
16561        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16562        // Disable the child packages
16563        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16564        for (int i = 0; i < childCount; i++) {
16565            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16566            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16567            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16568        }
16569        return disabled;
16570    }
16571
16572    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16573            String installerPackageName) {
16574        // Enable the parent package
16575        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16576        // Enable the child packages
16577        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16578        for (int i = 0; i < childCount; i++) {
16579            PackageParser.Package childPkg = pkg.childPackages.get(i);
16580            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16581        }
16582    }
16583
16584    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16585        // Collect all used permissions in the UID
16586        ArraySet<String> usedPermissions = new ArraySet<>();
16587        final int packageCount = su.packages.size();
16588        for (int i = 0; i < packageCount; i++) {
16589            PackageSetting ps = su.packages.valueAt(i);
16590            if (ps.pkg == null) {
16591                continue;
16592            }
16593            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16594            for (int j = 0; j < requestedPermCount; j++) {
16595                String permission = ps.pkg.requestedPermissions.get(j);
16596                BasePermission bp = mSettings.mPermissions.get(permission);
16597                if (bp != null) {
16598                    usedPermissions.add(permission);
16599                }
16600            }
16601        }
16602
16603        PermissionsState permissionsState = su.getPermissionsState();
16604        // Prune install permissions
16605        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16606        final int installPermCount = installPermStates.size();
16607        for (int i = installPermCount - 1; i >= 0;  i--) {
16608            PermissionState permissionState = installPermStates.get(i);
16609            if (!usedPermissions.contains(permissionState.getName())) {
16610                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16611                if (bp != null) {
16612                    permissionsState.revokeInstallPermission(bp);
16613                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16614                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16615                }
16616            }
16617        }
16618
16619        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16620
16621        // Prune runtime permissions
16622        for (int userId : allUserIds) {
16623            List<PermissionState> runtimePermStates = permissionsState
16624                    .getRuntimePermissionStates(userId);
16625            final int runtimePermCount = runtimePermStates.size();
16626            for (int i = runtimePermCount - 1; i >= 0; i--) {
16627                PermissionState permissionState = runtimePermStates.get(i);
16628                if (!usedPermissions.contains(permissionState.getName())) {
16629                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16630                    if (bp != null) {
16631                        permissionsState.revokeRuntimePermission(bp, userId);
16632                        permissionsState.updatePermissionFlags(bp, userId,
16633                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16634                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16635                                runtimePermissionChangedUserIds, userId);
16636                    }
16637                }
16638            }
16639        }
16640
16641        return runtimePermissionChangedUserIds;
16642    }
16643
16644    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16645            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16646        // Update the parent package setting
16647        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16648                res, user, installReason);
16649        // Update the child packages setting
16650        final int childCount = (newPackage.childPackages != null)
16651                ? newPackage.childPackages.size() : 0;
16652        for (int i = 0; i < childCount; i++) {
16653            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16654            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16655            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16656                    childRes.origUsers, childRes, user, installReason);
16657        }
16658    }
16659
16660    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16661            String installerPackageName, int[] allUsers, int[] installedForUsers,
16662            PackageInstalledInfo res, UserHandle user, int installReason) {
16663        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16664
16665        String pkgName = newPackage.packageName;
16666        synchronized (mPackages) {
16667            //write settings. the installStatus will be incomplete at this stage.
16668            //note that the new package setting would have already been
16669            //added to mPackages. It hasn't been persisted yet.
16670            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16671            // TODO: Remove this write? It's also written at the end of this method
16672            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16673            mSettings.writeLPr();
16674            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16675        }
16676
16677        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16678        synchronized (mPackages) {
16679            updatePermissionsLPw(newPackage.packageName, newPackage,
16680                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16681                            ? UPDATE_PERMISSIONS_ALL : 0));
16682            // For system-bundled packages, we assume that installing an upgraded version
16683            // of the package implies that the user actually wants to run that new code,
16684            // so we enable the package.
16685            PackageSetting ps = mSettings.mPackages.get(pkgName);
16686            final int userId = user.getIdentifier();
16687            if (ps != null) {
16688                if (isSystemApp(newPackage)) {
16689                    if (DEBUG_INSTALL) {
16690                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16691                    }
16692                    // Enable system package for requested users
16693                    if (res.origUsers != null) {
16694                        for (int origUserId : res.origUsers) {
16695                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16696                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16697                                        origUserId, installerPackageName);
16698                            }
16699                        }
16700                    }
16701                    // Also convey the prior install/uninstall state
16702                    if (allUsers != null && installedForUsers != null) {
16703                        for (int currentUserId : allUsers) {
16704                            final boolean installed = ArrayUtils.contains(
16705                                    installedForUsers, currentUserId);
16706                            if (DEBUG_INSTALL) {
16707                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16708                            }
16709                            ps.setInstalled(installed, currentUserId);
16710                        }
16711                        // these install state changes will be persisted in the
16712                        // upcoming call to mSettings.writeLPr().
16713                    }
16714                }
16715                // It's implied that when a user requests installation, they want the app to be
16716                // installed and enabled.
16717                if (userId != UserHandle.USER_ALL) {
16718                    ps.setInstalled(true, userId);
16719                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16720                }
16721
16722                // When replacing an existing package, preserve the original install reason for all
16723                // users that had the package installed before.
16724                final Set<Integer> previousUserIds = new ArraySet<>();
16725                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16726                    final int installReasonCount = res.removedInfo.installReasons.size();
16727                    for (int i = 0; i < installReasonCount; i++) {
16728                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16729                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16730                        ps.setInstallReason(previousInstallReason, previousUserId);
16731                        previousUserIds.add(previousUserId);
16732                    }
16733                }
16734
16735                // Set install reason for users that are having the package newly installed.
16736                if (userId == UserHandle.USER_ALL) {
16737                    for (int currentUserId : sUserManager.getUserIds()) {
16738                        if (!previousUserIds.contains(currentUserId)) {
16739                            ps.setInstallReason(installReason, currentUserId);
16740                        }
16741                    }
16742                } else if (!previousUserIds.contains(userId)) {
16743                    ps.setInstallReason(installReason, userId);
16744                }
16745                mSettings.writeKernelMappingLPr(ps);
16746            }
16747            res.name = pkgName;
16748            res.uid = newPackage.applicationInfo.uid;
16749            res.pkg = newPackage;
16750            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16751            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16752            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16753            //to update install status
16754            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16755            mSettings.writeLPr();
16756            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16757        }
16758
16759        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16760    }
16761
16762    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16763        try {
16764            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16765            installPackageLI(args, res);
16766        } finally {
16767            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16768        }
16769    }
16770
16771    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16772        final int installFlags = args.installFlags;
16773        final String installerPackageName = args.installerPackageName;
16774        final String volumeUuid = args.volumeUuid;
16775        final File tmpPackageFile = new File(args.getCodePath());
16776        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16777        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16778                || (args.volumeUuid != null));
16779        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16780        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16781        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16782        boolean replace = false;
16783        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16784        if (args.move != null) {
16785            // moving a complete application; perform an initial scan on the new install location
16786            scanFlags |= SCAN_INITIAL;
16787        }
16788        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16789            scanFlags |= SCAN_DONT_KILL_APP;
16790        }
16791        if (instantApp) {
16792            scanFlags |= SCAN_AS_INSTANT_APP;
16793        }
16794        if (fullApp) {
16795            scanFlags |= SCAN_AS_FULL_APP;
16796        }
16797
16798        // Result object to be returned
16799        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16800
16801        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16802
16803        // Sanity check
16804        if (instantApp && (forwardLocked || onExternal)) {
16805            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16806                    + " external=" + onExternal);
16807            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16808            return;
16809        }
16810
16811        // Retrieve PackageSettings and parse package
16812        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16813                | PackageParser.PARSE_ENFORCE_CODE
16814                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16815                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16816                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16817                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16818        PackageParser pp = new PackageParser();
16819        pp.setSeparateProcesses(mSeparateProcesses);
16820        pp.setDisplayMetrics(mMetrics);
16821        pp.setCallback(mPackageParserCallback);
16822
16823        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16824        final PackageParser.Package pkg;
16825        try {
16826            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16827        } catch (PackageParserException e) {
16828            res.setError("Failed parse during installPackageLI", e);
16829            return;
16830        } finally {
16831            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16832        }
16833
16834        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16835        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16836            Slog.w(TAG, "Instant app package " + pkg.packageName
16837                    + " does not target O, this will be a fatal error.");
16838            // STOPSHIP: Make this a fatal error
16839            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16840        }
16841        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16842            Slog.w(TAG, "Instant app package " + pkg.packageName
16843                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16844            // STOPSHIP: Make this a fatal error
16845            pkg.applicationInfo.targetSandboxVersion = 2;
16846        }
16847
16848        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16849            // Static shared libraries have synthetic package names
16850            renameStaticSharedLibraryPackage(pkg);
16851
16852            // No static shared libs on external storage
16853            if (onExternal) {
16854                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16855                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16856                        "Packages declaring static-shared libs cannot be updated");
16857                return;
16858            }
16859        }
16860
16861        // If we are installing a clustered package add results for the children
16862        if (pkg.childPackages != null) {
16863            synchronized (mPackages) {
16864                final int childCount = pkg.childPackages.size();
16865                for (int i = 0; i < childCount; i++) {
16866                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16867                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16868                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16869                    childRes.pkg = childPkg;
16870                    childRes.name = childPkg.packageName;
16871                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16872                    if (childPs != null) {
16873                        childRes.origUsers = childPs.queryInstalledUsers(
16874                                sUserManager.getUserIds(), true);
16875                    }
16876                    if ((mPackages.containsKey(childPkg.packageName))) {
16877                        childRes.removedInfo = new PackageRemovedInfo();
16878                        childRes.removedInfo.removedPackage = childPkg.packageName;
16879                    }
16880                    if (res.addedChildPackages == null) {
16881                        res.addedChildPackages = new ArrayMap<>();
16882                    }
16883                    res.addedChildPackages.put(childPkg.packageName, childRes);
16884                }
16885            }
16886        }
16887
16888        // If package doesn't declare API override, mark that we have an install
16889        // time CPU ABI override.
16890        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16891            pkg.cpuAbiOverride = args.abiOverride;
16892        }
16893
16894        String pkgName = res.name = pkg.packageName;
16895        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16896            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16897                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16898                return;
16899            }
16900        }
16901
16902        try {
16903            // either use what we've been given or parse directly from the APK
16904            if (args.certificates != null) {
16905                try {
16906                    PackageParser.populateCertificates(pkg, args.certificates);
16907                } catch (PackageParserException e) {
16908                    // there was something wrong with the certificates we were given;
16909                    // try to pull them from the APK
16910                    PackageParser.collectCertificates(pkg, parseFlags);
16911                }
16912            } else {
16913                PackageParser.collectCertificates(pkg, parseFlags);
16914            }
16915        } catch (PackageParserException e) {
16916            res.setError("Failed collect during installPackageLI", e);
16917            return;
16918        }
16919
16920        // Get rid of all references to package scan path via parser.
16921        pp = null;
16922        String oldCodePath = null;
16923        boolean systemApp = false;
16924        synchronized (mPackages) {
16925            // Check if installing already existing package
16926            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16927                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16928                if (pkg.mOriginalPackages != null
16929                        && pkg.mOriginalPackages.contains(oldName)
16930                        && mPackages.containsKey(oldName)) {
16931                    // This package is derived from an original package,
16932                    // and this device has been updating from that original
16933                    // name.  We must continue using the original name, so
16934                    // rename the new package here.
16935                    pkg.setPackageName(oldName);
16936                    pkgName = pkg.packageName;
16937                    replace = true;
16938                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16939                            + oldName + " pkgName=" + pkgName);
16940                } else if (mPackages.containsKey(pkgName)) {
16941                    // This package, under its official name, already exists
16942                    // on the device; we should replace it.
16943                    replace = true;
16944                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16945                }
16946
16947                // Child packages are installed through the parent package
16948                if (pkg.parentPackage != null) {
16949                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16950                            "Package " + pkg.packageName + " is child of package "
16951                                    + pkg.parentPackage.parentPackage + ". Child packages "
16952                                    + "can be updated only through the parent package.");
16953                    return;
16954                }
16955
16956                if (replace) {
16957                    // Prevent apps opting out from runtime permissions
16958                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16959                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16960                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16961                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16962                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16963                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16964                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16965                                        + " doesn't support runtime permissions but the old"
16966                                        + " target SDK " + oldTargetSdk + " does.");
16967                        return;
16968                    }
16969                    // Prevent apps from downgrading their targetSandbox.
16970                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16971                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16972                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16973                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16974                                "Package " + pkg.packageName + " new target sandbox "
16975                                + newTargetSandbox + " is incompatible with the previous value of"
16976                                + oldTargetSandbox + ".");
16977                        return;
16978                    }
16979
16980                    // Prevent installing of child packages
16981                    if (oldPackage.parentPackage != null) {
16982                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16983                                "Package " + pkg.packageName + " is child of package "
16984                                        + oldPackage.parentPackage + ". Child packages "
16985                                        + "can be updated only through the parent package.");
16986                        return;
16987                    }
16988                }
16989            }
16990
16991            PackageSetting ps = mSettings.mPackages.get(pkgName);
16992            if (ps != null) {
16993                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16994
16995                // Static shared libs have same package with different versions where
16996                // we internally use a synthetic package name to allow multiple versions
16997                // of the same package, therefore we need to compare signatures against
16998                // the package setting for the latest library version.
16999                PackageSetting signatureCheckPs = ps;
17000                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17001                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17002                    if (libraryEntry != null) {
17003                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17004                    }
17005                }
17006
17007                // Quick sanity check that we're signed correctly if updating;
17008                // we'll check this again later when scanning, but we want to
17009                // bail early here before tripping over redefined permissions.
17010                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17011                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17012                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17013                                + pkg.packageName + " upgrade keys do not match the "
17014                                + "previously installed version");
17015                        return;
17016                    }
17017                } else {
17018                    try {
17019                        verifySignaturesLP(signatureCheckPs, pkg);
17020                    } catch (PackageManagerException e) {
17021                        res.setError(e.error, e.getMessage());
17022                        return;
17023                    }
17024                }
17025
17026                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17027                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17028                    systemApp = (ps.pkg.applicationInfo.flags &
17029                            ApplicationInfo.FLAG_SYSTEM) != 0;
17030                }
17031                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17032            }
17033
17034            int N = pkg.permissions.size();
17035            for (int i = N-1; i >= 0; i--) {
17036                PackageParser.Permission perm = pkg.permissions.get(i);
17037                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17038
17039                // Don't allow anyone but the platform to define ephemeral permissions.
17040                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17041                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17042                    Slog.w(TAG, "Package " + pkg.packageName
17043                            + " attempting to delcare ephemeral permission "
17044                            + perm.info.name + "; Removing ephemeral.");
17045                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17046                }
17047                // Check whether the newly-scanned package wants to define an already-defined perm
17048                if (bp != null) {
17049                    // If the defining package is signed with our cert, it's okay.  This
17050                    // also includes the "updating the same package" case, of course.
17051                    // "updating same package" could also involve key-rotation.
17052                    final boolean sigsOk;
17053                    if (bp.sourcePackage.equals(pkg.packageName)
17054                            && (bp.packageSetting instanceof PackageSetting)
17055                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17056                                    scanFlags))) {
17057                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17058                    } else {
17059                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17060                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17061                    }
17062                    if (!sigsOk) {
17063                        // If the owning package is the system itself, we log but allow
17064                        // install to proceed; we fail the install on all other permission
17065                        // redefinitions.
17066                        if (!bp.sourcePackage.equals("android")) {
17067                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17068                                    + pkg.packageName + " attempting to redeclare permission "
17069                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17070                            res.origPermission = perm.info.name;
17071                            res.origPackage = bp.sourcePackage;
17072                            return;
17073                        } else {
17074                            Slog.w(TAG, "Package " + pkg.packageName
17075                                    + " attempting to redeclare system permission "
17076                                    + perm.info.name + "; ignoring new declaration");
17077                            pkg.permissions.remove(i);
17078                        }
17079                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17080                        // Prevent apps to change protection level to dangerous from any other
17081                        // type as this would allow a privilege escalation where an app adds a
17082                        // normal/signature permission in other app's group and later redefines
17083                        // it as dangerous leading to the group auto-grant.
17084                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17085                                == PermissionInfo.PROTECTION_DANGEROUS) {
17086                            if (bp != null && !bp.isRuntime()) {
17087                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17088                                        + "non-runtime permission " + perm.info.name
17089                                        + " to runtime; keeping old protection level");
17090                                perm.info.protectionLevel = bp.protectionLevel;
17091                            }
17092                        }
17093                    }
17094                }
17095            }
17096        }
17097
17098        if (systemApp) {
17099            if (onExternal) {
17100                // Abort update; system app can't be replaced with app on sdcard
17101                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17102                        "Cannot install updates to system apps on sdcard");
17103                return;
17104            } else if (instantApp) {
17105                // Abort update; system app can't be replaced with an instant app
17106                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17107                        "Cannot update a system app with an instant app");
17108                return;
17109            }
17110        }
17111
17112        if (args.move != null) {
17113            // We did an in-place move, so dex is ready to roll
17114            scanFlags |= SCAN_NO_DEX;
17115            scanFlags |= SCAN_MOVE;
17116
17117            synchronized (mPackages) {
17118                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17119                if (ps == null) {
17120                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17121                            "Missing settings for moved package " + pkgName);
17122                }
17123
17124                // We moved the entire application as-is, so bring over the
17125                // previously derived ABI information.
17126                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17127                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17128            }
17129
17130        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17131            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17132            scanFlags |= SCAN_NO_DEX;
17133
17134            try {
17135                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17136                    args.abiOverride : pkg.cpuAbiOverride);
17137                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17138                        true /*extractLibs*/, mAppLib32InstallDir);
17139            } catch (PackageManagerException pme) {
17140                Slog.e(TAG, "Error deriving application ABI", pme);
17141                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17142                return;
17143            }
17144
17145            // Shared libraries for the package need to be updated.
17146            synchronized (mPackages) {
17147                try {
17148                    updateSharedLibrariesLPr(pkg, null);
17149                } catch (PackageManagerException e) {
17150                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17151                }
17152            }
17153
17154            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17155            // Do not run PackageDexOptimizer through the local performDexOpt
17156            // method because `pkg` may not be in `mPackages` yet.
17157            //
17158            // Also, don't fail application installs if the dexopt step fails.
17159            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17160                    null /* instructionSets */, false /* checkProfiles */,
17161                    getCompilerFilterForReason(REASON_INSTALL),
17162                    getOrCreateCompilerPackageStats(pkg),
17163                    mDexManager.isUsedByOtherApps(pkg.packageName));
17164            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17165
17166            // Notify BackgroundDexOptService that the package has been changed.
17167            // If this is an update of a package which used to fail to compile,
17168            // BDOS will remove it from its blacklist.
17169            // TODO: Layering violation
17170            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17171        }
17172
17173        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17174            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17175            return;
17176        }
17177
17178        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17179
17180        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17181                "installPackageLI")) {
17182            if (replace) {
17183                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17184                    // Static libs have a synthetic package name containing the version
17185                    // and cannot be updated as an update would get a new package name,
17186                    // unless this is the exact same version code which is useful for
17187                    // development.
17188                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17189                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17190                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17191                                + "static-shared libs cannot be updated");
17192                        return;
17193                    }
17194                }
17195                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17196                        installerPackageName, res, args.installReason);
17197            } else {
17198                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17199                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17200            }
17201        }
17202
17203        synchronized (mPackages) {
17204            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17205            if (ps != null) {
17206                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17207                ps.setUpdateAvailable(false /*updateAvailable*/);
17208            }
17209
17210            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17211            for (int i = 0; i < childCount; i++) {
17212                PackageParser.Package childPkg = pkg.childPackages.get(i);
17213                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17214                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17215                if (childPs != null) {
17216                    childRes.newUsers = childPs.queryInstalledUsers(
17217                            sUserManager.getUserIds(), true);
17218                }
17219            }
17220
17221            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17222                updateSequenceNumberLP(pkgName, res.newUsers);
17223                updateInstantAppInstallerLocked(pkgName);
17224            }
17225        }
17226    }
17227
17228    private void startIntentFilterVerifications(int userId, boolean replacing,
17229            PackageParser.Package pkg) {
17230        if (mIntentFilterVerifierComponent == null) {
17231            Slog.w(TAG, "No IntentFilter verification will not be done as "
17232                    + "there is no IntentFilterVerifier available!");
17233            return;
17234        }
17235
17236        final int verifierUid = getPackageUid(
17237                mIntentFilterVerifierComponent.getPackageName(),
17238                MATCH_DEBUG_TRIAGED_MISSING,
17239                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17240
17241        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17242        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17243        mHandler.sendMessage(msg);
17244
17245        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17246        for (int i = 0; i < childCount; i++) {
17247            PackageParser.Package childPkg = pkg.childPackages.get(i);
17248            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17249            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17250            mHandler.sendMessage(msg);
17251        }
17252    }
17253
17254    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17255            PackageParser.Package pkg) {
17256        int size = pkg.activities.size();
17257        if (size == 0) {
17258            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17259                    "No activity, so no need to verify any IntentFilter!");
17260            return;
17261        }
17262
17263        final boolean hasDomainURLs = hasDomainURLs(pkg);
17264        if (!hasDomainURLs) {
17265            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17266                    "No domain URLs, so no need to verify any IntentFilter!");
17267            return;
17268        }
17269
17270        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17271                + " if any IntentFilter from the " + size
17272                + " Activities needs verification ...");
17273
17274        int count = 0;
17275        final String packageName = pkg.packageName;
17276
17277        synchronized (mPackages) {
17278            // If this is a new install and we see that we've already run verification for this
17279            // package, we have nothing to do: it means the state was restored from backup.
17280            if (!replacing) {
17281                IntentFilterVerificationInfo ivi =
17282                        mSettings.getIntentFilterVerificationLPr(packageName);
17283                if (ivi != null) {
17284                    if (DEBUG_DOMAIN_VERIFICATION) {
17285                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17286                                + ivi.getStatusString());
17287                    }
17288                    return;
17289                }
17290            }
17291
17292            // If any filters need to be verified, then all need to be.
17293            boolean needToVerify = false;
17294            for (PackageParser.Activity a : pkg.activities) {
17295                for (ActivityIntentInfo filter : a.intents) {
17296                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17297                        if (DEBUG_DOMAIN_VERIFICATION) {
17298                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17299                        }
17300                        needToVerify = true;
17301                        break;
17302                    }
17303                }
17304            }
17305
17306            if (needToVerify) {
17307                final int verificationId = mIntentFilterVerificationToken++;
17308                for (PackageParser.Activity a : pkg.activities) {
17309                    for (ActivityIntentInfo filter : a.intents) {
17310                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17311                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17312                                    "Verification needed for IntentFilter:" + filter.toString());
17313                            mIntentFilterVerifier.addOneIntentFilterVerification(
17314                                    verifierUid, userId, verificationId, filter, packageName);
17315                            count++;
17316                        }
17317                    }
17318                }
17319            }
17320        }
17321
17322        if (count > 0) {
17323            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17324                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17325                    +  " for userId:" + userId);
17326            mIntentFilterVerifier.startVerifications(userId);
17327        } else {
17328            if (DEBUG_DOMAIN_VERIFICATION) {
17329                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17330            }
17331        }
17332    }
17333
17334    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17335        final ComponentName cn  = filter.activity.getComponentName();
17336        final String packageName = cn.getPackageName();
17337
17338        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17339                packageName);
17340        if (ivi == null) {
17341            return true;
17342        }
17343        int status = ivi.getStatus();
17344        switch (status) {
17345            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17346            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17347                return true;
17348
17349            default:
17350                // Nothing to do
17351                return false;
17352        }
17353    }
17354
17355    private static boolean isMultiArch(ApplicationInfo info) {
17356        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17357    }
17358
17359    private static boolean isExternal(PackageParser.Package pkg) {
17360        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17361    }
17362
17363    private static boolean isExternal(PackageSetting ps) {
17364        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17365    }
17366
17367    private static boolean isSystemApp(PackageParser.Package pkg) {
17368        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17369    }
17370
17371    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17372        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17373    }
17374
17375    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17376        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17377    }
17378
17379    private static boolean isSystemApp(PackageSetting ps) {
17380        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17381    }
17382
17383    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17384        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17385    }
17386
17387    private int packageFlagsToInstallFlags(PackageSetting ps) {
17388        int installFlags = 0;
17389        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17390            // This existing package was an external ASEC install when we have
17391            // the external flag without a UUID
17392            installFlags |= PackageManager.INSTALL_EXTERNAL;
17393        }
17394        if (ps.isForwardLocked()) {
17395            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17396        }
17397        return installFlags;
17398    }
17399
17400    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17401        if (isExternal(pkg)) {
17402            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17403                return StorageManager.UUID_PRIMARY_PHYSICAL;
17404            } else {
17405                return pkg.volumeUuid;
17406            }
17407        } else {
17408            return StorageManager.UUID_PRIVATE_INTERNAL;
17409        }
17410    }
17411
17412    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17413        if (isExternal(pkg)) {
17414            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17415                return mSettings.getExternalVersion();
17416            } else {
17417                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17418            }
17419        } else {
17420            return mSettings.getInternalVersion();
17421        }
17422    }
17423
17424    private void deleteTempPackageFiles() {
17425        final FilenameFilter filter = new FilenameFilter() {
17426            public boolean accept(File dir, String name) {
17427                return name.startsWith("vmdl") && name.endsWith(".tmp");
17428            }
17429        };
17430        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17431            file.delete();
17432        }
17433    }
17434
17435    @Override
17436    public void deletePackageAsUser(String packageName, int versionCode,
17437            IPackageDeleteObserver observer, int userId, int flags) {
17438        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17439                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17440    }
17441
17442    @Override
17443    public void deletePackageVersioned(VersionedPackage versionedPackage,
17444            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17445        mContext.enforceCallingOrSelfPermission(
17446                android.Manifest.permission.DELETE_PACKAGES, null);
17447        Preconditions.checkNotNull(versionedPackage);
17448        Preconditions.checkNotNull(observer);
17449        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17450                PackageManager.VERSION_CODE_HIGHEST,
17451                Integer.MAX_VALUE, "versionCode must be >= -1");
17452
17453        final String packageName = versionedPackage.getPackageName();
17454        // TODO: We will change version code to long, so in the new API it is long
17455        final int versionCode = (int) versionedPackage.getVersionCode();
17456        final String internalPackageName;
17457        synchronized (mPackages) {
17458            // Normalize package name to handle renamed packages and static libs
17459            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17460                    // TODO: We will change version code to long, so in the new API it is long
17461                    (int) versionedPackage.getVersionCode());
17462        }
17463
17464        final int uid = Binder.getCallingUid();
17465        if (!isOrphaned(internalPackageName)
17466                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17467            try {
17468                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17469                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17470                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17471                observer.onUserActionRequired(intent);
17472            } catch (RemoteException re) {
17473            }
17474            return;
17475        }
17476        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17477        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17478        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17479            mContext.enforceCallingOrSelfPermission(
17480                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17481                    "deletePackage for user " + userId);
17482        }
17483
17484        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17485            try {
17486                observer.onPackageDeleted(packageName,
17487                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17488            } catch (RemoteException re) {
17489            }
17490            return;
17491        }
17492
17493        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17494            try {
17495                observer.onPackageDeleted(packageName,
17496                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17497            } catch (RemoteException re) {
17498            }
17499            return;
17500        }
17501
17502        if (DEBUG_REMOVE) {
17503            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17504                    + " deleteAllUsers: " + deleteAllUsers + " version="
17505                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17506                    ? "VERSION_CODE_HIGHEST" : versionCode));
17507        }
17508        // Queue up an async operation since the package deletion may take a little while.
17509        mHandler.post(new Runnable() {
17510            public void run() {
17511                mHandler.removeCallbacks(this);
17512                int returnCode;
17513                if (!deleteAllUsers) {
17514                    returnCode = deletePackageX(internalPackageName, versionCode,
17515                            userId, deleteFlags);
17516                } else {
17517                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17518                            internalPackageName, users);
17519                    // If nobody is blocking uninstall, proceed with delete for all users
17520                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17521                        returnCode = deletePackageX(internalPackageName, versionCode,
17522                                userId, deleteFlags);
17523                    } else {
17524                        // Otherwise uninstall individually for users with blockUninstalls=false
17525                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17526                        for (int userId : users) {
17527                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17528                                returnCode = deletePackageX(internalPackageName, versionCode,
17529                                        userId, userFlags);
17530                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17531                                    Slog.w(TAG, "Package delete failed for user " + userId
17532                                            + ", returnCode " + returnCode);
17533                                }
17534                            }
17535                        }
17536                        // The app has only been marked uninstalled for certain users.
17537                        // We still need to report that delete was blocked
17538                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17539                    }
17540                }
17541                try {
17542                    observer.onPackageDeleted(packageName, returnCode, null);
17543                } catch (RemoteException e) {
17544                    Log.i(TAG, "Observer no longer exists.");
17545                } //end catch
17546            } //end run
17547        });
17548    }
17549
17550    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17551        if (pkg.staticSharedLibName != null) {
17552            return pkg.manifestPackageName;
17553        }
17554        return pkg.packageName;
17555    }
17556
17557    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17558        // Handle renamed packages
17559        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17560        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17561
17562        // Is this a static library?
17563        SparseArray<SharedLibraryEntry> versionedLib =
17564                mStaticLibsByDeclaringPackage.get(packageName);
17565        if (versionedLib == null || versionedLib.size() <= 0) {
17566            return packageName;
17567        }
17568
17569        // Figure out which lib versions the caller can see
17570        SparseIntArray versionsCallerCanSee = null;
17571        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17572        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17573                && callingAppId != Process.ROOT_UID) {
17574            versionsCallerCanSee = new SparseIntArray();
17575            String libName = versionedLib.valueAt(0).info.getName();
17576            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17577            if (uidPackages != null) {
17578                for (String uidPackage : uidPackages) {
17579                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17580                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17581                    if (libIdx >= 0) {
17582                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17583                        versionsCallerCanSee.append(libVersion, libVersion);
17584                    }
17585                }
17586            }
17587        }
17588
17589        // Caller can see nothing - done
17590        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17591            return packageName;
17592        }
17593
17594        // Find the version the caller can see and the app version code
17595        SharedLibraryEntry highestVersion = null;
17596        final int versionCount = versionedLib.size();
17597        for (int i = 0; i < versionCount; i++) {
17598            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17599            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17600                    libEntry.info.getVersion()) < 0) {
17601                continue;
17602            }
17603            // TODO: We will change version code to long, so in the new API it is long
17604            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17605            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17606                if (libVersionCode == versionCode) {
17607                    return libEntry.apk;
17608                }
17609            } else if (highestVersion == null) {
17610                highestVersion = libEntry;
17611            } else if (libVersionCode  > highestVersion.info
17612                    .getDeclaringPackage().getVersionCode()) {
17613                highestVersion = libEntry;
17614            }
17615        }
17616
17617        if (highestVersion != null) {
17618            return highestVersion.apk;
17619        }
17620
17621        return packageName;
17622    }
17623
17624    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17625        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17626              || callingUid == Process.SYSTEM_UID) {
17627            return true;
17628        }
17629        final int callingUserId = UserHandle.getUserId(callingUid);
17630        // If the caller installed the pkgName, then allow it to silently uninstall.
17631        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17632            return true;
17633        }
17634
17635        // Allow package verifier to silently uninstall.
17636        if (mRequiredVerifierPackage != null &&
17637                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17638            return true;
17639        }
17640
17641        // Allow package uninstaller to silently uninstall.
17642        if (mRequiredUninstallerPackage != null &&
17643                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17644            return true;
17645        }
17646
17647        // Allow storage manager to silently uninstall.
17648        if (mStorageManagerPackage != null &&
17649                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17650            return true;
17651        }
17652        return false;
17653    }
17654
17655    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17656        int[] result = EMPTY_INT_ARRAY;
17657        for (int userId : userIds) {
17658            if (getBlockUninstallForUser(packageName, userId)) {
17659                result = ArrayUtils.appendInt(result, userId);
17660            }
17661        }
17662        return result;
17663    }
17664
17665    @Override
17666    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17667        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17668    }
17669
17670    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17671        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17672                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17673        try {
17674            if (dpm != null) {
17675                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17676                        /* callingUserOnly =*/ false);
17677                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17678                        : deviceOwnerComponentName.getPackageName();
17679                // Does the package contains the device owner?
17680                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17681                // this check is probably not needed, since DO should be registered as a device
17682                // admin on some user too. (Original bug for this: b/17657954)
17683                if (packageName.equals(deviceOwnerPackageName)) {
17684                    return true;
17685                }
17686                // Does it contain a device admin for any user?
17687                int[] users;
17688                if (userId == UserHandle.USER_ALL) {
17689                    users = sUserManager.getUserIds();
17690                } else {
17691                    users = new int[]{userId};
17692                }
17693                for (int i = 0; i < users.length; ++i) {
17694                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17695                        return true;
17696                    }
17697                }
17698            }
17699        } catch (RemoteException e) {
17700        }
17701        return false;
17702    }
17703
17704    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17705        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17706    }
17707
17708    /**
17709     *  This method is an internal method that could be get invoked either
17710     *  to delete an installed package or to clean up a failed installation.
17711     *  After deleting an installed package, a broadcast is sent to notify any
17712     *  listeners that the package has been removed. For cleaning up a failed
17713     *  installation, the broadcast is not necessary since the package's
17714     *  installation wouldn't have sent the initial broadcast either
17715     *  The key steps in deleting a package are
17716     *  deleting the package information in internal structures like mPackages,
17717     *  deleting the packages base directories through installd
17718     *  updating mSettings to reflect current status
17719     *  persisting settings for later use
17720     *  sending a broadcast if necessary
17721     */
17722    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17723        final PackageRemovedInfo info = new PackageRemovedInfo();
17724        final boolean res;
17725
17726        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17727                ? UserHandle.USER_ALL : userId;
17728
17729        if (isPackageDeviceAdmin(packageName, removeUser)) {
17730            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17731            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17732        }
17733
17734        PackageSetting uninstalledPs = null;
17735        PackageParser.Package pkg = null;
17736
17737        // for the uninstall-updates case and restricted profiles, remember the per-
17738        // user handle installed state
17739        int[] allUsers;
17740        synchronized (mPackages) {
17741            uninstalledPs = mSettings.mPackages.get(packageName);
17742            if (uninstalledPs == null) {
17743                Slog.w(TAG, "Not removing non-existent package " + packageName);
17744                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17745            }
17746
17747            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17748                    && uninstalledPs.versionCode != versionCode) {
17749                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17750                        + uninstalledPs.versionCode + " != " + versionCode);
17751                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17752            }
17753
17754            // Static shared libs can be declared by any package, so let us not
17755            // allow removing a package if it provides a lib others depend on.
17756            pkg = mPackages.get(packageName);
17757            if (pkg != null && pkg.staticSharedLibName != null) {
17758                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17759                        pkg.staticSharedLibVersion);
17760                if (libEntry != null) {
17761                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17762                            libEntry.info, 0, userId);
17763                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17764                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17765                                + " hosting lib " + libEntry.info.getName() + " version "
17766                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17767                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17768                    }
17769                }
17770            }
17771
17772            allUsers = sUserManager.getUserIds();
17773            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17774        }
17775
17776        final int freezeUser;
17777        if (isUpdatedSystemApp(uninstalledPs)
17778                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17779            // We're downgrading a system app, which will apply to all users, so
17780            // freeze them all during the downgrade
17781            freezeUser = UserHandle.USER_ALL;
17782        } else {
17783            freezeUser = removeUser;
17784        }
17785
17786        synchronized (mInstallLock) {
17787            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17788            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17789                    deleteFlags, "deletePackageX")) {
17790                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17791                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17792            }
17793            synchronized (mPackages) {
17794                if (res) {
17795                    if (pkg != null) {
17796                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17797                    }
17798                    updateSequenceNumberLP(packageName, info.removedUsers);
17799                    updateInstantAppInstallerLocked(packageName);
17800                }
17801            }
17802        }
17803
17804        if (res) {
17805            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17806            info.sendPackageRemovedBroadcasts(killApp);
17807            info.sendSystemPackageUpdatedBroadcasts();
17808            info.sendSystemPackageAppearedBroadcasts();
17809        }
17810        // Force a gc here.
17811        Runtime.getRuntime().gc();
17812        // Delete the resources here after sending the broadcast to let
17813        // other processes clean up before deleting resources.
17814        if (info.args != null) {
17815            synchronized (mInstallLock) {
17816                info.args.doPostDeleteLI(true);
17817            }
17818        }
17819
17820        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17821    }
17822
17823    class PackageRemovedInfo {
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        void sendPackageRemovedBroadcasts(boolean killApp) {
17842            sendPackageRemovedBroadcastInternal(killApp);
17843            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17844            for (int i = 0; i < childCount; i++) {
17845                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17846                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17847            }
17848        }
17849
17850        void sendSystemPackageUpdatedBroadcasts() {
17851            if (isRemovedPackageSystemUpdate) {
17852                sendSystemPackageUpdatedBroadcastsInternal();
17853                final int childCount = (removedChildPackages != null)
17854                        ? removedChildPackages.size() : 0;
17855                for (int i = 0; i < childCount; i++) {
17856                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17857                    if (childInfo.isRemovedPackageSystemUpdate) {
17858                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17859                    }
17860                }
17861            }
17862        }
17863
17864        void sendSystemPackageAppearedBroadcasts() {
17865            final int packageCount = (appearedChildPackages != null)
17866                    ? appearedChildPackages.size() : 0;
17867            for (int i = 0; i < packageCount; i++) {
17868                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17869                sendPackageAddedForNewUsers(installedInfo.name, true,
17870                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17871            }
17872        }
17873
17874        private void sendSystemPackageUpdatedBroadcastsInternal() {
17875            Bundle extras = new Bundle(2);
17876            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17877            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17878            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17879                    extras, 0, null, null, null);
17880            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17881                    extras, 0, null, null, null);
17882            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17883                    null, 0, removedPackage, null, null);
17884        }
17885
17886        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17887            // Don't send static shared library removal broadcasts as these
17888            // libs are visible only the the apps that depend on them an one
17889            // cannot remove the library if it has a dependency.
17890            if (isStaticSharedLib) {
17891                return;
17892            }
17893            Bundle extras = new Bundle(2);
17894            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17895            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17896            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17897            if (isUpdate || isRemovedPackageSystemUpdate) {
17898                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17899            }
17900            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17901            if (removedPackage != null) {
17902                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17903                        extras, 0, null, null, broadcastUsers);
17904                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17905                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17906                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17907                            null, null, broadcastUsers);
17908                }
17909            }
17910            if (removedAppId >= 0) {
17911                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
17912                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
17913            }
17914        }
17915    }
17916
17917    /*
17918     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17919     * flag is not set, the data directory is removed as well.
17920     * make sure this flag is set for partially installed apps. If not its meaningless to
17921     * delete a partially installed application.
17922     */
17923    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17924            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17925        String packageName = ps.name;
17926        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17927        // Retrieve object to delete permissions for shared user later on
17928        final PackageParser.Package deletedPkg;
17929        final PackageSetting deletedPs;
17930        // reader
17931        synchronized (mPackages) {
17932            deletedPkg = mPackages.get(packageName);
17933            deletedPs = mSettings.mPackages.get(packageName);
17934            if (outInfo != null) {
17935                outInfo.removedPackage = packageName;
17936                outInfo.isStaticSharedLib = deletedPkg != null
17937                        && deletedPkg.staticSharedLibName != null;
17938                outInfo.removedUsers = deletedPs != null
17939                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17940                        : null;
17941                if (outInfo.removedUsers == null) {
17942                    outInfo.broadcastUsers = null;
17943                } else {
17944                    outInfo.broadcastUsers = EMPTY_INT_ARRAY;
17945                    int[] allUsers = outInfo.removedUsers;
17946                    for (int i = allUsers.length - 1; i >= 0; --i) {
17947                        final int userId = allUsers[i];
17948                        if (deletedPs.getInstantApp(userId)) {
17949                            continue;
17950                        }
17951                        outInfo.broadcastUsers =
17952                                ArrayUtils.appendInt(outInfo.broadcastUsers, userId);
17953                    }
17954                }
17955            }
17956        }
17957
17958        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17959
17960        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17961            final PackageParser.Package resolvedPkg;
17962            if (deletedPkg != null) {
17963                resolvedPkg = deletedPkg;
17964            } else {
17965                // We don't have a parsed package when it lives on an ejected
17966                // adopted storage device, so fake something together
17967                resolvedPkg = new PackageParser.Package(ps.name);
17968                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17969            }
17970            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17971                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17972            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17973            if (outInfo != null) {
17974                outInfo.dataRemoved = true;
17975            }
17976            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17977        }
17978
17979        int removedAppId = -1;
17980
17981        // writer
17982        synchronized (mPackages) {
17983            boolean installedStateChanged = false;
17984            if (deletedPs != null) {
17985                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17986                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17987                    clearDefaultBrowserIfNeeded(packageName);
17988                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17989                    removedAppId = mSettings.removePackageLPw(packageName);
17990                    if (outInfo != null) {
17991                        outInfo.removedAppId = removedAppId;
17992                    }
17993                    updatePermissionsLPw(deletedPs.name, null, 0);
17994                    if (deletedPs.sharedUser != null) {
17995                        // Remove permissions associated with package. Since runtime
17996                        // permissions are per user we have to kill the removed package
17997                        // or packages running under the shared user of the removed
17998                        // package if revoking the permissions requested only by the removed
17999                        // package is successful and this causes a change in gids.
18000                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18001                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18002                                    userId);
18003                            if (userIdToKill == UserHandle.USER_ALL
18004                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18005                                // If gids changed for this user, kill all affected packages.
18006                                mHandler.post(new Runnable() {
18007                                    @Override
18008                                    public void run() {
18009                                        // This has to happen with no lock held.
18010                                        killApplication(deletedPs.name, deletedPs.appId,
18011                                                KILL_APP_REASON_GIDS_CHANGED);
18012                                    }
18013                                });
18014                                break;
18015                            }
18016                        }
18017                    }
18018                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18019                }
18020                // make sure to preserve per-user disabled state if this removal was just
18021                // a downgrade of a system app to the factory package
18022                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18023                    if (DEBUG_REMOVE) {
18024                        Slog.d(TAG, "Propagating install state across downgrade");
18025                    }
18026                    for (int userId : allUserHandles) {
18027                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18028                        if (DEBUG_REMOVE) {
18029                            Slog.d(TAG, "    user " + userId + " => " + installed);
18030                        }
18031                        if (installed != ps.getInstalled(userId)) {
18032                            installedStateChanged = true;
18033                        }
18034                        ps.setInstalled(installed, userId);
18035                    }
18036                }
18037            }
18038            // can downgrade to reader
18039            if (writeSettings) {
18040                // Save settings now
18041                mSettings.writeLPr();
18042            }
18043            if (installedStateChanged) {
18044                mSettings.writeKernelMappingLPr(ps);
18045            }
18046        }
18047        if (removedAppId != -1) {
18048            // A user ID was deleted here. Go through all users and remove it
18049            // from KeyStore.
18050            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18051        }
18052    }
18053
18054    static boolean locationIsPrivileged(File path) {
18055        try {
18056            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18057                    .getCanonicalPath();
18058            return path.getCanonicalPath().startsWith(privilegedAppDir);
18059        } catch (IOException e) {
18060            Slog.e(TAG, "Unable to access code path " + path);
18061        }
18062        return false;
18063    }
18064
18065    /*
18066     * Tries to delete system package.
18067     */
18068    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18069            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18070            boolean writeSettings) {
18071        if (deletedPs.parentPackageName != null) {
18072            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18073            return false;
18074        }
18075
18076        final boolean applyUserRestrictions
18077                = (allUserHandles != null) && (outInfo.origUsers != null);
18078        final PackageSetting disabledPs;
18079        // Confirm if the system package has been updated
18080        // An updated system app can be deleted. This will also have to restore
18081        // the system pkg from system partition
18082        // reader
18083        synchronized (mPackages) {
18084            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18085        }
18086
18087        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18088                + " disabledPs=" + disabledPs);
18089
18090        if (disabledPs == null) {
18091            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18092            return false;
18093        } else if (DEBUG_REMOVE) {
18094            Slog.d(TAG, "Deleting system pkg from data partition");
18095        }
18096
18097        if (DEBUG_REMOVE) {
18098            if (applyUserRestrictions) {
18099                Slog.d(TAG, "Remembering install states:");
18100                for (int userId : allUserHandles) {
18101                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18102                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18103                }
18104            }
18105        }
18106
18107        // Delete the updated package
18108        outInfo.isRemovedPackageSystemUpdate = true;
18109        if (outInfo.removedChildPackages != null) {
18110            final int childCount = (deletedPs.childPackageNames != null)
18111                    ? deletedPs.childPackageNames.size() : 0;
18112            for (int i = 0; i < childCount; i++) {
18113                String childPackageName = deletedPs.childPackageNames.get(i);
18114                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18115                        .contains(childPackageName)) {
18116                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18117                            childPackageName);
18118                    if (childInfo != null) {
18119                        childInfo.isRemovedPackageSystemUpdate = true;
18120                    }
18121                }
18122            }
18123        }
18124
18125        if (disabledPs.versionCode < deletedPs.versionCode) {
18126            // Delete data for downgrades
18127            flags &= ~PackageManager.DELETE_KEEP_DATA;
18128        } else {
18129            // Preserve data by setting flag
18130            flags |= PackageManager.DELETE_KEEP_DATA;
18131        }
18132
18133        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18134                outInfo, writeSettings, disabledPs.pkg);
18135        if (!ret) {
18136            return false;
18137        }
18138
18139        // writer
18140        synchronized (mPackages) {
18141            // Reinstate the old system package
18142            enableSystemPackageLPw(disabledPs.pkg);
18143            // Remove any native libraries from the upgraded package.
18144            removeNativeBinariesLI(deletedPs);
18145        }
18146
18147        // Install the system package
18148        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18149        int parseFlags = mDefParseFlags
18150                | PackageParser.PARSE_MUST_BE_APK
18151                | PackageParser.PARSE_IS_SYSTEM
18152                | PackageParser.PARSE_IS_SYSTEM_DIR;
18153        if (locationIsPrivileged(disabledPs.codePath)) {
18154            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18155        }
18156
18157        final PackageParser.Package newPkg;
18158        try {
18159            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18160                0 /* currentTime */, null);
18161        } catch (PackageManagerException e) {
18162            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18163                    + e.getMessage());
18164            return false;
18165        }
18166
18167        try {
18168            // update shared libraries for the newly re-installed system package
18169            updateSharedLibrariesLPr(newPkg, null);
18170        } catch (PackageManagerException e) {
18171            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18172        }
18173
18174        prepareAppDataAfterInstallLIF(newPkg);
18175
18176        // writer
18177        synchronized (mPackages) {
18178            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18179
18180            // Propagate the permissions state as we do not want to drop on the floor
18181            // runtime permissions. The update permissions method below will take
18182            // care of removing obsolete permissions and grant install permissions.
18183            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18184            updatePermissionsLPw(newPkg.packageName, newPkg,
18185                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18186
18187            if (applyUserRestrictions) {
18188                boolean installedStateChanged = false;
18189                if (DEBUG_REMOVE) {
18190                    Slog.d(TAG, "Propagating install state across reinstall");
18191                }
18192                for (int userId : allUserHandles) {
18193                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18194                    if (DEBUG_REMOVE) {
18195                        Slog.d(TAG, "    user " + userId + " => " + installed);
18196                    }
18197                    if (installed != ps.getInstalled(userId)) {
18198                        installedStateChanged = true;
18199                    }
18200                    ps.setInstalled(installed, userId);
18201
18202                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18203                }
18204                // Regardless of writeSettings we need to ensure that this restriction
18205                // state propagation is persisted
18206                mSettings.writeAllUsersPackageRestrictionsLPr();
18207                if (installedStateChanged) {
18208                    mSettings.writeKernelMappingLPr(ps);
18209                }
18210            }
18211            // can downgrade to reader here
18212            if (writeSettings) {
18213                mSettings.writeLPr();
18214            }
18215        }
18216        return true;
18217    }
18218
18219    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18220            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18221            PackageRemovedInfo outInfo, boolean writeSettings,
18222            PackageParser.Package replacingPackage) {
18223        synchronized (mPackages) {
18224            if (outInfo != null) {
18225                outInfo.uid = ps.appId;
18226            }
18227
18228            if (outInfo != null && outInfo.removedChildPackages != null) {
18229                final int childCount = (ps.childPackageNames != null)
18230                        ? ps.childPackageNames.size() : 0;
18231                for (int i = 0; i < childCount; i++) {
18232                    String childPackageName = ps.childPackageNames.get(i);
18233                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18234                    if (childPs == null) {
18235                        return false;
18236                    }
18237                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18238                            childPackageName);
18239                    if (childInfo != null) {
18240                        childInfo.uid = childPs.appId;
18241                    }
18242                }
18243            }
18244        }
18245
18246        // Delete package data from internal structures and also remove data if flag is set
18247        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18248
18249        // Delete the child packages data
18250        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18251        for (int i = 0; i < childCount; i++) {
18252            PackageSetting childPs;
18253            synchronized (mPackages) {
18254                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18255            }
18256            if (childPs != null) {
18257                PackageRemovedInfo childOutInfo = (outInfo != null
18258                        && outInfo.removedChildPackages != null)
18259                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18260                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18261                        && (replacingPackage != null
18262                        && !replacingPackage.hasChildPackage(childPs.name))
18263                        ? flags & ~DELETE_KEEP_DATA : flags;
18264                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18265                        deleteFlags, writeSettings);
18266            }
18267        }
18268
18269        // Delete application code and resources only for parent packages
18270        if (ps.parentPackageName == null) {
18271            if (deleteCodeAndResources && (outInfo != null)) {
18272                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18273                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18274                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18275            }
18276        }
18277
18278        return true;
18279    }
18280
18281    @Override
18282    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18283            int userId) {
18284        mContext.enforceCallingOrSelfPermission(
18285                android.Manifest.permission.DELETE_PACKAGES, null);
18286        synchronized (mPackages) {
18287            PackageSetting ps = mSettings.mPackages.get(packageName);
18288            if (ps == null) {
18289                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18290                return false;
18291            }
18292            // Cannot block uninstall of static shared libs as they are
18293            // considered a part of the using app (emulating static linking).
18294            // Also static libs are installed always on internal storage.
18295            PackageParser.Package pkg = mPackages.get(packageName);
18296            if (pkg != null && pkg.staticSharedLibName != null) {
18297                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18298                        + " providing static shared library: " + pkg.staticSharedLibName);
18299                return false;
18300            }
18301            if (!ps.getInstalled(userId)) {
18302                // Can't block uninstall for an app that is not installed or enabled.
18303                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18304                return false;
18305            }
18306            ps.setBlockUninstall(blockUninstall, userId);
18307            mSettings.writePackageRestrictionsLPr(userId);
18308        }
18309        return true;
18310    }
18311
18312    @Override
18313    public boolean getBlockUninstallForUser(String packageName, int userId) {
18314        synchronized (mPackages) {
18315            PackageSetting ps = mSettings.mPackages.get(packageName);
18316            if (ps == null) {
18317                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18318                return false;
18319            }
18320            return ps.getBlockUninstall(userId);
18321        }
18322    }
18323
18324    @Override
18325    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18326        int callingUid = Binder.getCallingUid();
18327        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18328            throw new SecurityException(
18329                    "setRequiredForSystemUser can only be run by the system or root");
18330        }
18331        synchronized (mPackages) {
18332            PackageSetting ps = mSettings.mPackages.get(packageName);
18333            if (ps == null) {
18334                Log.w(TAG, "Package doesn't exist: " + packageName);
18335                return false;
18336            }
18337            if (systemUserApp) {
18338                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18339            } else {
18340                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18341            }
18342            mSettings.writeLPr();
18343        }
18344        return true;
18345    }
18346
18347    /*
18348     * This method handles package deletion in general
18349     */
18350    private boolean deletePackageLIF(String packageName, UserHandle user,
18351            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18352            PackageRemovedInfo outInfo, boolean writeSettings,
18353            PackageParser.Package replacingPackage) {
18354        if (packageName == null) {
18355            Slog.w(TAG, "Attempt to delete null packageName.");
18356            return false;
18357        }
18358
18359        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18360
18361        PackageSetting ps;
18362        synchronized (mPackages) {
18363            ps = mSettings.mPackages.get(packageName);
18364            if (ps == null) {
18365                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18366                return false;
18367            }
18368
18369            if (ps.parentPackageName != null && (!isSystemApp(ps)
18370                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18371                if (DEBUG_REMOVE) {
18372                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18373                            + ((user == null) ? UserHandle.USER_ALL : user));
18374                }
18375                final int removedUserId = (user != null) ? user.getIdentifier()
18376                        : UserHandle.USER_ALL;
18377                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18378                    return false;
18379                }
18380                markPackageUninstalledForUserLPw(ps, user);
18381                scheduleWritePackageRestrictionsLocked(user);
18382                return true;
18383            }
18384        }
18385
18386        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18387                && user.getIdentifier() != UserHandle.USER_ALL)) {
18388            // The caller is asking that the package only be deleted for a single
18389            // user.  To do this, we just mark its uninstalled state and delete
18390            // its data. If this is a system app, we only allow this to happen if
18391            // they have set the special DELETE_SYSTEM_APP which requests different
18392            // semantics than normal for uninstalling system apps.
18393            markPackageUninstalledForUserLPw(ps, user);
18394
18395            if (!isSystemApp(ps)) {
18396                // Do not uninstall the APK if an app should be cached
18397                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18398                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18399                    // Other user still have this package installed, so all
18400                    // we need to do is clear this user's data and save that
18401                    // it is uninstalled.
18402                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18403                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18404                        return false;
18405                    }
18406                    scheduleWritePackageRestrictionsLocked(user);
18407                    return true;
18408                } else {
18409                    // We need to set it back to 'installed' so the uninstall
18410                    // broadcasts will be sent correctly.
18411                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18412                    ps.setInstalled(true, user.getIdentifier());
18413                    mSettings.writeKernelMappingLPr(ps);
18414                }
18415            } else {
18416                // This is a system app, so we assume that the
18417                // other users still have this package installed, so all
18418                // we need to do is clear this user's data and save that
18419                // it is uninstalled.
18420                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18421                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18422                    return false;
18423                }
18424                scheduleWritePackageRestrictionsLocked(user);
18425                return true;
18426            }
18427        }
18428
18429        // If we are deleting a composite package for all users, keep track
18430        // of result for each child.
18431        if (ps.childPackageNames != null && outInfo != null) {
18432            synchronized (mPackages) {
18433                final int childCount = ps.childPackageNames.size();
18434                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18435                for (int i = 0; i < childCount; i++) {
18436                    String childPackageName = ps.childPackageNames.get(i);
18437                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18438                    childInfo.removedPackage = childPackageName;
18439                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18440                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18441                    if (childPs != null) {
18442                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18443                    }
18444                }
18445            }
18446        }
18447
18448        boolean ret = false;
18449        if (isSystemApp(ps)) {
18450            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18451            // When an updated system application is deleted we delete the existing resources
18452            // as well and fall back to existing code in system partition
18453            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18454        } else {
18455            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18456            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18457                    outInfo, writeSettings, replacingPackage);
18458        }
18459
18460        // Take a note whether we deleted the package for all users
18461        if (outInfo != null) {
18462            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18463            if (outInfo.removedChildPackages != null) {
18464                synchronized (mPackages) {
18465                    final int childCount = outInfo.removedChildPackages.size();
18466                    for (int i = 0; i < childCount; i++) {
18467                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18468                        if (childInfo != null) {
18469                            childInfo.removedForAllUsers = mPackages.get(
18470                                    childInfo.removedPackage) == null;
18471                        }
18472                    }
18473                }
18474            }
18475            // If we uninstalled an update to a system app there may be some
18476            // child packages that appeared as they are declared in the system
18477            // app but were not declared in the update.
18478            if (isSystemApp(ps)) {
18479                synchronized (mPackages) {
18480                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18481                    final int childCount = (updatedPs.childPackageNames != null)
18482                            ? updatedPs.childPackageNames.size() : 0;
18483                    for (int i = 0; i < childCount; i++) {
18484                        String childPackageName = updatedPs.childPackageNames.get(i);
18485                        if (outInfo.removedChildPackages == null
18486                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18487                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18488                            if (childPs == null) {
18489                                continue;
18490                            }
18491                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18492                            installRes.name = childPackageName;
18493                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18494                            installRes.pkg = mPackages.get(childPackageName);
18495                            installRes.uid = childPs.pkg.applicationInfo.uid;
18496                            if (outInfo.appearedChildPackages == null) {
18497                                outInfo.appearedChildPackages = new ArrayMap<>();
18498                            }
18499                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18500                        }
18501                    }
18502                }
18503            }
18504        }
18505
18506        return ret;
18507    }
18508
18509    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18510        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18511                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18512        for (int nextUserId : userIds) {
18513            if (DEBUG_REMOVE) {
18514                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18515            }
18516            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18517                    false /*installed*/,
18518                    true /*stopped*/,
18519                    true /*notLaunched*/,
18520                    false /*hidden*/,
18521                    false /*suspended*/,
18522                    false /*instantApp*/,
18523                    null /*lastDisableAppCaller*/,
18524                    null /*enabledComponents*/,
18525                    null /*disabledComponents*/,
18526                    false /*blockUninstall*/,
18527                    ps.readUserState(nextUserId).domainVerificationStatus,
18528                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18529        }
18530        mSettings.writeKernelMappingLPr(ps);
18531    }
18532
18533    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18534            PackageRemovedInfo outInfo) {
18535        final PackageParser.Package pkg;
18536        synchronized (mPackages) {
18537            pkg = mPackages.get(ps.name);
18538        }
18539
18540        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18541                : new int[] {userId};
18542        for (int nextUserId : userIds) {
18543            if (DEBUG_REMOVE) {
18544                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18545                        + nextUserId);
18546            }
18547
18548            destroyAppDataLIF(pkg, userId,
18549                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18550            destroyAppProfilesLIF(pkg, userId);
18551            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18552            schedulePackageCleaning(ps.name, nextUserId, false);
18553            synchronized (mPackages) {
18554                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18555                    scheduleWritePackageRestrictionsLocked(nextUserId);
18556                }
18557                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18558            }
18559        }
18560
18561        if (outInfo != null) {
18562            outInfo.removedPackage = ps.name;
18563            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18564            outInfo.removedAppId = ps.appId;
18565            outInfo.removedUsers = userIds;
18566            outInfo.broadcastUsers = userIds;
18567        }
18568
18569        return true;
18570    }
18571
18572    private final class ClearStorageConnection implements ServiceConnection {
18573        IMediaContainerService mContainerService;
18574
18575        @Override
18576        public void onServiceConnected(ComponentName name, IBinder service) {
18577            synchronized (this) {
18578                mContainerService = IMediaContainerService.Stub
18579                        .asInterface(Binder.allowBlocking(service));
18580                notifyAll();
18581            }
18582        }
18583
18584        @Override
18585        public void onServiceDisconnected(ComponentName name) {
18586        }
18587    }
18588
18589    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18590        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18591
18592        final boolean mounted;
18593        if (Environment.isExternalStorageEmulated()) {
18594            mounted = true;
18595        } else {
18596            final String status = Environment.getExternalStorageState();
18597
18598            mounted = status.equals(Environment.MEDIA_MOUNTED)
18599                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18600        }
18601
18602        if (!mounted) {
18603            return;
18604        }
18605
18606        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18607        int[] users;
18608        if (userId == UserHandle.USER_ALL) {
18609            users = sUserManager.getUserIds();
18610        } else {
18611            users = new int[] { userId };
18612        }
18613        final ClearStorageConnection conn = new ClearStorageConnection();
18614        if (mContext.bindServiceAsUser(
18615                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18616            try {
18617                for (int curUser : users) {
18618                    long timeout = SystemClock.uptimeMillis() + 5000;
18619                    synchronized (conn) {
18620                        long now;
18621                        while (conn.mContainerService == null &&
18622                                (now = SystemClock.uptimeMillis()) < timeout) {
18623                            try {
18624                                conn.wait(timeout - now);
18625                            } catch (InterruptedException e) {
18626                            }
18627                        }
18628                    }
18629                    if (conn.mContainerService == null) {
18630                        return;
18631                    }
18632
18633                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18634                    clearDirectory(conn.mContainerService,
18635                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18636                    if (allData) {
18637                        clearDirectory(conn.mContainerService,
18638                                userEnv.buildExternalStorageAppDataDirs(packageName));
18639                        clearDirectory(conn.mContainerService,
18640                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18641                    }
18642                }
18643            } finally {
18644                mContext.unbindService(conn);
18645            }
18646        }
18647    }
18648
18649    @Override
18650    public void clearApplicationProfileData(String packageName) {
18651        enforceSystemOrRoot("Only the system can clear all profile data");
18652
18653        final PackageParser.Package pkg;
18654        synchronized (mPackages) {
18655            pkg = mPackages.get(packageName);
18656        }
18657
18658        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18659            synchronized (mInstallLock) {
18660                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18661            }
18662        }
18663    }
18664
18665    @Override
18666    public void clearApplicationUserData(final String packageName,
18667            final IPackageDataObserver observer, final int userId) {
18668        mContext.enforceCallingOrSelfPermission(
18669                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18670
18671        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18672                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18673
18674        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18675            throw new SecurityException("Cannot clear data for a protected package: "
18676                    + packageName);
18677        }
18678        // Queue up an async operation since the package deletion may take a little while.
18679        mHandler.post(new Runnable() {
18680            public void run() {
18681                mHandler.removeCallbacks(this);
18682                final boolean succeeded;
18683                try (PackageFreezer freezer = freezePackage(packageName,
18684                        "clearApplicationUserData")) {
18685                    synchronized (mInstallLock) {
18686                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18687                    }
18688                    clearExternalStorageDataSync(packageName, userId, true);
18689                    synchronized (mPackages) {
18690                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18691                                packageName, userId);
18692                    }
18693                }
18694                if (succeeded) {
18695                    // invoke DeviceStorageMonitor's update method to clear any notifications
18696                    DeviceStorageMonitorInternal dsm = LocalServices
18697                            .getService(DeviceStorageMonitorInternal.class);
18698                    if (dsm != null) {
18699                        dsm.checkMemory();
18700                    }
18701                }
18702                if(observer != null) {
18703                    try {
18704                        observer.onRemoveCompleted(packageName, succeeded);
18705                    } catch (RemoteException e) {
18706                        Log.i(TAG, "Observer no longer exists.");
18707                    }
18708                } //end if observer
18709            } //end run
18710        });
18711    }
18712
18713    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18714        if (packageName == null) {
18715            Slog.w(TAG, "Attempt to delete null packageName.");
18716            return false;
18717        }
18718
18719        // Try finding details about the requested package
18720        PackageParser.Package pkg;
18721        synchronized (mPackages) {
18722            pkg = mPackages.get(packageName);
18723            if (pkg == null) {
18724                final PackageSetting ps = mSettings.mPackages.get(packageName);
18725                if (ps != null) {
18726                    pkg = ps.pkg;
18727                }
18728            }
18729
18730            if (pkg == null) {
18731                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18732                return false;
18733            }
18734
18735            PackageSetting ps = (PackageSetting) pkg.mExtras;
18736            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18737        }
18738
18739        clearAppDataLIF(pkg, userId,
18740                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18741
18742        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18743        removeKeystoreDataIfNeeded(userId, appId);
18744
18745        UserManagerInternal umInternal = getUserManagerInternal();
18746        final int flags;
18747        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18748            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18749        } else if (umInternal.isUserRunning(userId)) {
18750            flags = StorageManager.FLAG_STORAGE_DE;
18751        } else {
18752            flags = 0;
18753        }
18754        prepareAppDataContentsLIF(pkg, userId, flags);
18755
18756        return true;
18757    }
18758
18759    /**
18760     * Reverts user permission state changes (permissions and flags) in
18761     * all packages for a given user.
18762     *
18763     * @param userId The device user for which to do a reset.
18764     */
18765    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18766        final int packageCount = mPackages.size();
18767        for (int i = 0; i < packageCount; i++) {
18768            PackageParser.Package pkg = mPackages.valueAt(i);
18769            PackageSetting ps = (PackageSetting) pkg.mExtras;
18770            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18771        }
18772    }
18773
18774    private void resetNetworkPolicies(int userId) {
18775        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18776    }
18777
18778    /**
18779     * Reverts user permission state changes (permissions and flags).
18780     *
18781     * @param ps The package for which to reset.
18782     * @param userId The device user for which to do a reset.
18783     */
18784    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18785            final PackageSetting ps, final int userId) {
18786        if (ps.pkg == null) {
18787            return;
18788        }
18789
18790        // These are flags that can change base on user actions.
18791        final int userSettableMask = FLAG_PERMISSION_USER_SET
18792                | FLAG_PERMISSION_USER_FIXED
18793                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18794                | FLAG_PERMISSION_REVIEW_REQUIRED;
18795
18796        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18797                | FLAG_PERMISSION_POLICY_FIXED;
18798
18799        boolean writeInstallPermissions = false;
18800        boolean writeRuntimePermissions = false;
18801
18802        final int permissionCount = ps.pkg.requestedPermissions.size();
18803        for (int i = 0; i < permissionCount; i++) {
18804            String permission = ps.pkg.requestedPermissions.get(i);
18805
18806            BasePermission bp = mSettings.mPermissions.get(permission);
18807            if (bp == null) {
18808                continue;
18809            }
18810
18811            // If shared user we just reset the state to which only this app contributed.
18812            if (ps.sharedUser != null) {
18813                boolean used = false;
18814                final int packageCount = ps.sharedUser.packages.size();
18815                for (int j = 0; j < packageCount; j++) {
18816                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18817                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18818                            && pkg.pkg.requestedPermissions.contains(permission)) {
18819                        used = true;
18820                        break;
18821                    }
18822                }
18823                if (used) {
18824                    continue;
18825                }
18826            }
18827
18828            PermissionsState permissionsState = ps.getPermissionsState();
18829
18830            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18831
18832            // Always clear the user settable flags.
18833            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18834                    bp.name) != null;
18835            // If permission review is enabled and this is a legacy app, mark the
18836            // permission as requiring a review as this is the initial state.
18837            int flags = 0;
18838            if (mPermissionReviewRequired
18839                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18840                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18841            }
18842            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18843                if (hasInstallState) {
18844                    writeInstallPermissions = true;
18845                } else {
18846                    writeRuntimePermissions = true;
18847                }
18848            }
18849
18850            // Below is only runtime permission handling.
18851            if (!bp.isRuntime()) {
18852                continue;
18853            }
18854
18855            // Never clobber system or policy.
18856            if ((oldFlags & policyOrSystemFlags) != 0) {
18857                continue;
18858            }
18859
18860            // If this permission was granted by default, make sure it is.
18861            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18862                if (permissionsState.grantRuntimePermission(bp, userId)
18863                        != PERMISSION_OPERATION_FAILURE) {
18864                    writeRuntimePermissions = true;
18865                }
18866            // If permission review is enabled the permissions for a legacy apps
18867            // are represented as constantly granted runtime ones, so don't revoke.
18868            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18869                // Otherwise, reset the permission.
18870                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18871                switch (revokeResult) {
18872                    case PERMISSION_OPERATION_SUCCESS:
18873                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18874                        writeRuntimePermissions = true;
18875                        final int appId = ps.appId;
18876                        mHandler.post(new Runnable() {
18877                            @Override
18878                            public void run() {
18879                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18880                            }
18881                        });
18882                    } break;
18883                }
18884            }
18885        }
18886
18887        // Synchronously write as we are taking permissions away.
18888        if (writeRuntimePermissions) {
18889            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18890        }
18891
18892        // Synchronously write as we are taking permissions away.
18893        if (writeInstallPermissions) {
18894            mSettings.writeLPr();
18895        }
18896    }
18897
18898    /**
18899     * Remove entries from the keystore daemon. Will only remove it if the
18900     * {@code appId} is valid.
18901     */
18902    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18903        if (appId < 0) {
18904            return;
18905        }
18906
18907        final KeyStore keyStore = KeyStore.getInstance();
18908        if (keyStore != null) {
18909            if (userId == UserHandle.USER_ALL) {
18910                for (final int individual : sUserManager.getUserIds()) {
18911                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18912                }
18913            } else {
18914                keyStore.clearUid(UserHandle.getUid(userId, appId));
18915            }
18916        } else {
18917            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18918        }
18919    }
18920
18921    @Override
18922    public void deleteApplicationCacheFiles(final String packageName,
18923            final IPackageDataObserver observer) {
18924        final int userId = UserHandle.getCallingUserId();
18925        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18926    }
18927
18928    @Override
18929    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18930            final IPackageDataObserver observer) {
18931        mContext.enforceCallingOrSelfPermission(
18932                android.Manifest.permission.DELETE_CACHE_FILES, null);
18933        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18934                /* requireFullPermission= */ true, /* checkShell= */ false,
18935                "delete application cache files");
18936
18937        final PackageParser.Package pkg;
18938        synchronized (mPackages) {
18939            pkg = mPackages.get(packageName);
18940        }
18941
18942        // Queue up an async operation since the package deletion may take a little while.
18943        mHandler.post(new Runnable() {
18944            public void run() {
18945                synchronized (mInstallLock) {
18946                    final int flags = StorageManager.FLAG_STORAGE_DE
18947                            | StorageManager.FLAG_STORAGE_CE;
18948                    // We're only clearing cache files, so we don't care if the
18949                    // app is unfrozen and still able to run
18950                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18951                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18952                }
18953                clearExternalStorageDataSync(packageName, userId, false);
18954                if (observer != null) {
18955                    try {
18956                        observer.onRemoveCompleted(packageName, true);
18957                    } catch (RemoteException e) {
18958                        Log.i(TAG, "Observer no longer exists.");
18959                    }
18960                }
18961            }
18962        });
18963    }
18964
18965    @Override
18966    public void getPackageSizeInfo(final String packageName, int userHandle,
18967            final IPackageStatsObserver observer) {
18968        throw new UnsupportedOperationException(
18969                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18970    }
18971
18972    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18973        final PackageSetting ps;
18974        synchronized (mPackages) {
18975            ps = mSettings.mPackages.get(packageName);
18976            if (ps == null) {
18977                Slog.w(TAG, "Failed to find settings for " + packageName);
18978                return false;
18979            }
18980        }
18981
18982        final String[] packageNames = { packageName };
18983        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18984        final String[] codePaths = { ps.codePathString };
18985
18986        try {
18987            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18988                    ps.appId, ceDataInodes, codePaths, stats);
18989
18990            // For now, ignore code size of packages on system partition
18991            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18992                stats.codeSize = 0;
18993            }
18994
18995            // External clients expect these to be tracked separately
18996            stats.dataSize -= stats.cacheSize;
18997
18998        } catch (InstallerException e) {
18999            Slog.w(TAG, String.valueOf(e));
19000            return false;
19001        }
19002
19003        return true;
19004    }
19005
19006    private int getUidTargetSdkVersionLockedLPr(int uid) {
19007        Object obj = mSettings.getUserIdLPr(uid);
19008        if (obj instanceof SharedUserSetting) {
19009            final SharedUserSetting sus = (SharedUserSetting) obj;
19010            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19011            final Iterator<PackageSetting> it = sus.packages.iterator();
19012            while (it.hasNext()) {
19013                final PackageSetting ps = it.next();
19014                if (ps.pkg != null) {
19015                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19016                    if (v < vers) vers = v;
19017                }
19018            }
19019            return vers;
19020        } else if (obj instanceof PackageSetting) {
19021            final PackageSetting ps = (PackageSetting) obj;
19022            if (ps.pkg != null) {
19023                return ps.pkg.applicationInfo.targetSdkVersion;
19024            }
19025        }
19026        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19027    }
19028
19029    @Override
19030    public void addPreferredActivity(IntentFilter filter, int match,
19031            ComponentName[] set, ComponentName activity, int userId) {
19032        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19033                "Adding preferred");
19034    }
19035
19036    private void addPreferredActivityInternal(IntentFilter filter, int match,
19037            ComponentName[] set, ComponentName activity, boolean always, int userId,
19038            String opname) {
19039        // writer
19040        int callingUid = Binder.getCallingUid();
19041        enforceCrossUserPermission(callingUid, userId,
19042                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19043        if (filter.countActions() == 0) {
19044            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19045            return;
19046        }
19047        synchronized (mPackages) {
19048            if (mContext.checkCallingOrSelfPermission(
19049                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19050                    != PackageManager.PERMISSION_GRANTED) {
19051                if (getUidTargetSdkVersionLockedLPr(callingUid)
19052                        < Build.VERSION_CODES.FROYO) {
19053                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19054                            + callingUid);
19055                    return;
19056                }
19057                mContext.enforceCallingOrSelfPermission(
19058                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19059            }
19060
19061            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19062            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19063                    + userId + ":");
19064            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19065            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19066            scheduleWritePackageRestrictionsLocked(userId);
19067            postPreferredActivityChangedBroadcast(userId);
19068        }
19069    }
19070
19071    private void postPreferredActivityChangedBroadcast(int userId) {
19072        mHandler.post(() -> {
19073            final IActivityManager am = ActivityManager.getService();
19074            if (am == null) {
19075                return;
19076            }
19077
19078            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19079            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19080            try {
19081                am.broadcastIntent(null, intent, null, null,
19082                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19083                        null, false, false, userId);
19084            } catch (RemoteException e) {
19085            }
19086        });
19087    }
19088
19089    @Override
19090    public void replacePreferredActivity(IntentFilter filter, int match,
19091            ComponentName[] set, ComponentName activity, int userId) {
19092        if (filter.countActions() != 1) {
19093            throw new IllegalArgumentException(
19094                    "replacePreferredActivity expects filter to have only 1 action.");
19095        }
19096        if (filter.countDataAuthorities() != 0
19097                || filter.countDataPaths() != 0
19098                || filter.countDataSchemes() > 1
19099                || filter.countDataTypes() != 0) {
19100            throw new IllegalArgumentException(
19101                    "replacePreferredActivity expects filter to have no data authorities, " +
19102                    "paths, or types; and at most one scheme.");
19103        }
19104
19105        final int callingUid = Binder.getCallingUid();
19106        enforceCrossUserPermission(callingUid, userId,
19107                true /* requireFullPermission */, false /* checkShell */,
19108                "replace preferred activity");
19109        synchronized (mPackages) {
19110            if (mContext.checkCallingOrSelfPermission(
19111                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19112                    != PackageManager.PERMISSION_GRANTED) {
19113                if (getUidTargetSdkVersionLockedLPr(callingUid)
19114                        < Build.VERSION_CODES.FROYO) {
19115                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19116                            + Binder.getCallingUid());
19117                    return;
19118                }
19119                mContext.enforceCallingOrSelfPermission(
19120                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19121            }
19122
19123            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19124            if (pir != null) {
19125                // Get all of the existing entries that exactly match this filter.
19126                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19127                if (existing != null && existing.size() == 1) {
19128                    PreferredActivity cur = existing.get(0);
19129                    if (DEBUG_PREFERRED) {
19130                        Slog.i(TAG, "Checking replace of preferred:");
19131                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19132                        if (!cur.mPref.mAlways) {
19133                            Slog.i(TAG, "  -- CUR; not mAlways!");
19134                        } else {
19135                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19136                            Slog.i(TAG, "  -- CUR: mSet="
19137                                    + Arrays.toString(cur.mPref.mSetComponents));
19138                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19139                            Slog.i(TAG, "  -- NEW: mMatch="
19140                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19141                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19142                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19143                        }
19144                    }
19145                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19146                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19147                            && cur.mPref.sameSet(set)) {
19148                        // Setting the preferred activity to what it happens to be already
19149                        if (DEBUG_PREFERRED) {
19150                            Slog.i(TAG, "Replacing with same preferred activity "
19151                                    + cur.mPref.mShortComponent + " for user "
19152                                    + userId + ":");
19153                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19154                        }
19155                        return;
19156                    }
19157                }
19158
19159                if (existing != null) {
19160                    if (DEBUG_PREFERRED) {
19161                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19162                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19163                    }
19164                    for (int i = 0; i < existing.size(); i++) {
19165                        PreferredActivity pa = existing.get(i);
19166                        if (DEBUG_PREFERRED) {
19167                            Slog.i(TAG, "Removing existing preferred activity "
19168                                    + pa.mPref.mComponent + ":");
19169                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19170                        }
19171                        pir.removeFilter(pa);
19172                    }
19173                }
19174            }
19175            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19176                    "Replacing preferred");
19177        }
19178    }
19179
19180    @Override
19181    public void clearPackagePreferredActivities(String packageName) {
19182        final int uid = Binder.getCallingUid();
19183        // writer
19184        synchronized (mPackages) {
19185            PackageParser.Package pkg = mPackages.get(packageName);
19186            if (pkg == null || pkg.applicationInfo.uid != uid) {
19187                if (mContext.checkCallingOrSelfPermission(
19188                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19189                        != PackageManager.PERMISSION_GRANTED) {
19190                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
19191                            < Build.VERSION_CODES.FROYO) {
19192                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19193                                + Binder.getCallingUid());
19194                        return;
19195                    }
19196                    mContext.enforceCallingOrSelfPermission(
19197                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19198                }
19199            }
19200
19201            int user = UserHandle.getCallingUserId();
19202            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19203                scheduleWritePackageRestrictionsLocked(user);
19204            }
19205        }
19206    }
19207
19208    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19209    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19210        ArrayList<PreferredActivity> removed = null;
19211        boolean changed = false;
19212        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19213            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19214            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19215            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19216                continue;
19217            }
19218            Iterator<PreferredActivity> it = pir.filterIterator();
19219            while (it.hasNext()) {
19220                PreferredActivity pa = it.next();
19221                // Mark entry for removal only if it matches the package name
19222                // and the entry is of type "always".
19223                if (packageName == null ||
19224                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19225                                && pa.mPref.mAlways)) {
19226                    if (removed == null) {
19227                        removed = new ArrayList<PreferredActivity>();
19228                    }
19229                    removed.add(pa);
19230                }
19231            }
19232            if (removed != null) {
19233                for (int j=0; j<removed.size(); j++) {
19234                    PreferredActivity pa = removed.get(j);
19235                    pir.removeFilter(pa);
19236                }
19237                changed = true;
19238            }
19239        }
19240        if (changed) {
19241            postPreferredActivityChangedBroadcast(userId);
19242        }
19243        return changed;
19244    }
19245
19246    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19247    private void clearIntentFilterVerificationsLPw(int userId) {
19248        final int packageCount = mPackages.size();
19249        for (int i = 0; i < packageCount; i++) {
19250            PackageParser.Package pkg = mPackages.valueAt(i);
19251            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19252        }
19253    }
19254
19255    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19256    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19257        if (userId == UserHandle.USER_ALL) {
19258            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19259                    sUserManager.getUserIds())) {
19260                for (int oneUserId : sUserManager.getUserIds()) {
19261                    scheduleWritePackageRestrictionsLocked(oneUserId);
19262                }
19263            }
19264        } else {
19265            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19266                scheduleWritePackageRestrictionsLocked(userId);
19267            }
19268        }
19269    }
19270
19271    void clearDefaultBrowserIfNeeded(String packageName) {
19272        for (int oneUserId : sUserManager.getUserIds()) {
19273            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19274            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19275            if (packageName.equals(defaultBrowserPackageName)) {
19276                setDefaultBrowserPackageName(null, oneUserId);
19277            }
19278        }
19279    }
19280
19281    @Override
19282    public void resetApplicationPreferences(int userId) {
19283        mContext.enforceCallingOrSelfPermission(
19284                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19285        final long identity = Binder.clearCallingIdentity();
19286        // writer
19287        try {
19288            synchronized (mPackages) {
19289                clearPackagePreferredActivitiesLPw(null, userId);
19290                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19291                // TODO: We have to reset the default SMS and Phone. This requires
19292                // significant refactoring to keep all default apps in the package
19293                // manager (cleaner but more work) or have the services provide
19294                // callbacks to the package manager to request a default app reset.
19295                applyFactoryDefaultBrowserLPw(userId);
19296                clearIntentFilterVerificationsLPw(userId);
19297                primeDomainVerificationsLPw(userId);
19298                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19299                scheduleWritePackageRestrictionsLocked(userId);
19300            }
19301            resetNetworkPolicies(userId);
19302        } finally {
19303            Binder.restoreCallingIdentity(identity);
19304        }
19305    }
19306
19307    @Override
19308    public int getPreferredActivities(List<IntentFilter> outFilters,
19309            List<ComponentName> outActivities, String packageName) {
19310
19311        int num = 0;
19312        final int userId = UserHandle.getCallingUserId();
19313        // reader
19314        synchronized (mPackages) {
19315            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19316            if (pir != null) {
19317                final Iterator<PreferredActivity> it = pir.filterIterator();
19318                while (it.hasNext()) {
19319                    final PreferredActivity pa = it.next();
19320                    if (packageName == null
19321                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19322                                    && pa.mPref.mAlways)) {
19323                        if (outFilters != null) {
19324                            outFilters.add(new IntentFilter(pa));
19325                        }
19326                        if (outActivities != null) {
19327                            outActivities.add(pa.mPref.mComponent);
19328                        }
19329                    }
19330                }
19331            }
19332        }
19333
19334        return num;
19335    }
19336
19337    @Override
19338    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19339            int userId) {
19340        int callingUid = Binder.getCallingUid();
19341        if (callingUid != Process.SYSTEM_UID) {
19342            throw new SecurityException(
19343                    "addPersistentPreferredActivity can only be run by the system");
19344        }
19345        if (filter.countActions() == 0) {
19346            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19347            return;
19348        }
19349        synchronized (mPackages) {
19350            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19351                    ":");
19352            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19353            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19354                    new PersistentPreferredActivity(filter, activity));
19355            scheduleWritePackageRestrictionsLocked(userId);
19356            postPreferredActivityChangedBroadcast(userId);
19357        }
19358    }
19359
19360    @Override
19361    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19362        int callingUid = Binder.getCallingUid();
19363        if (callingUid != Process.SYSTEM_UID) {
19364            throw new SecurityException(
19365                    "clearPackagePersistentPreferredActivities can only be run by the system");
19366        }
19367        ArrayList<PersistentPreferredActivity> removed = null;
19368        boolean changed = false;
19369        synchronized (mPackages) {
19370            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19371                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19372                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19373                        .valueAt(i);
19374                if (userId != thisUserId) {
19375                    continue;
19376                }
19377                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19378                while (it.hasNext()) {
19379                    PersistentPreferredActivity ppa = it.next();
19380                    // Mark entry for removal only if it matches the package name.
19381                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19382                        if (removed == null) {
19383                            removed = new ArrayList<PersistentPreferredActivity>();
19384                        }
19385                        removed.add(ppa);
19386                    }
19387                }
19388                if (removed != null) {
19389                    for (int j=0; j<removed.size(); j++) {
19390                        PersistentPreferredActivity ppa = removed.get(j);
19391                        ppir.removeFilter(ppa);
19392                    }
19393                    changed = true;
19394                }
19395            }
19396
19397            if (changed) {
19398                scheduleWritePackageRestrictionsLocked(userId);
19399                postPreferredActivityChangedBroadcast(userId);
19400            }
19401        }
19402    }
19403
19404    /**
19405     * Common machinery for picking apart a restored XML blob and passing
19406     * it to a caller-supplied functor to be applied to the running system.
19407     */
19408    private void restoreFromXml(XmlPullParser parser, int userId,
19409            String expectedStartTag, BlobXmlRestorer functor)
19410            throws IOException, XmlPullParserException {
19411        int type;
19412        while ((type = parser.next()) != XmlPullParser.START_TAG
19413                && type != XmlPullParser.END_DOCUMENT) {
19414        }
19415        if (type != XmlPullParser.START_TAG) {
19416            // oops didn't find a start tag?!
19417            if (DEBUG_BACKUP) {
19418                Slog.e(TAG, "Didn't find start tag during restore");
19419            }
19420            return;
19421        }
19422Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19423        // this is supposed to be TAG_PREFERRED_BACKUP
19424        if (!expectedStartTag.equals(parser.getName())) {
19425            if (DEBUG_BACKUP) {
19426                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19427            }
19428            return;
19429        }
19430
19431        // skip interfering stuff, then we're aligned with the backing implementation
19432        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19433Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19434        functor.apply(parser, userId);
19435    }
19436
19437    private interface BlobXmlRestorer {
19438        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19439    }
19440
19441    /**
19442     * Non-Binder method, support for the backup/restore mechanism: write the
19443     * full set of preferred activities in its canonical XML format.  Returns the
19444     * XML output as a byte array, or null if there is none.
19445     */
19446    @Override
19447    public byte[] getPreferredActivityBackup(int userId) {
19448        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19449            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19450        }
19451
19452        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19453        try {
19454            final XmlSerializer serializer = new FastXmlSerializer();
19455            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19456            serializer.startDocument(null, true);
19457            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19458
19459            synchronized (mPackages) {
19460                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19461            }
19462
19463            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19464            serializer.endDocument();
19465            serializer.flush();
19466        } catch (Exception e) {
19467            if (DEBUG_BACKUP) {
19468                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19469            }
19470            return null;
19471        }
19472
19473        return dataStream.toByteArray();
19474    }
19475
19476    @Override
19477    public void restorePreferredActivities(byte[] backup, int userId) {
19478        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19479            throw new SecurityException("Only the system may call restorePreferredActivities()");
19480        }
19481
19482        try {
19483            final XmlPullParser parser = Xml.newPullParser();
19484            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19485            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19486                    new BlobXmlRestorer() {
19487                        @Override
19488                        public void apply(XmlPullParser parser, int userId)
19489                                throws XmlPullParserException, IOException {
19490                            synchronized (mPackages) {
19491                                mSettings.readPreferredActivitiesLPw(parser, userId);
19492                            }
19493                        }
19494                    } );
19495        } catch (Exception e) {
19496            if (DEBUG_BACKUP) {
19497                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19498            }
19499        }
19500    }
19501
19502    /**
19503     * Non-Binder method, support for the backup/restore mechanism: write the
19504     * default browser (etc) settings in its canonical XML format.  Returns the default
19505     * browser XML representation as a byte array, or null if there is none.
19506     */
19507    @Override
19508    public byte[] getDefaultAppsBackup(int userId) {
19509        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19510            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19511        }
19512
19513        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19514        try {
19515            final XmlSerializer serializer = new FastXmlSerializer();
19516            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19517            serializer.startDocument(null, true);
19518            serializer.startTag(null, TAG_DEFAULT_APPS);
19519
19520            synchronized (mPackages) {
19521                mSettings.writeDefaultAppsLPr(serializer, userId);
19522            }
19523
19524            serializer.endTag(null, TAG_DEFAULT_APPS);
19525            serializer.endDocument();
19526            serializer.flush();
19527        } catch (Exception e) {
19528            if (DEBUG_BACKUP) {
19529                Slog.e(TAG, "Unable to write default apps for backup", e);
19530            }
19531            return null;
19532        }
19533
19534        return dataStream.toByteArray();
19535    }
19536
19537    @Override
19538    public void restoreDefaultApps(byte[] backup, int userId) {
19539        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19540            throw new SecurityException("Only the system may call restoreDefaultApps()");
19541        }
19542
19543        try {
19544            final XmlPullParser parser = Xml.newPullParser();
19545            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19546            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19547                    new BlobXmlRestorer() {
19548                        @Override
19549                        public void apply(XmlPullParser parser, int userId)
19550                                throws XmlPullParserException, IOException {
19551                            synchronized (mPackages) {
19552                                mSettings.readDefaultAppsLPw(parser, userId);
19553                            }
19554                        }
19555                    } );
19556        } catch (Exception e) {
19557            if (DEBUG_BACKUP) {
19558                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19559            }
19560        }
19561    }
19562
19563    @Override
19564    public byte[] getIntentFilterVerificationBackup(int userId) {
19565        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19566            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19567        }
19568
19569        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19570        try {
19571            final XmlSerializer serializer = new FastXmlSerializer();
19572            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19573            serializer.startDocument(null, true);
19574            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19575
19576            synchronized (mPackages) {
19577                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19578            }
19579
19580            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19581            serializer.endDocument();
19582            serializer.flush();
19583        } catch (Exception e) {
19584            if (DEBUG_BACKUP) {
19585                Slog.e(TAG, "Unable to write default apps for backup", e);
19586            }
19587            return null;
19588        }
19589
19590        return dataStream.toByteArray();
19591    }
19592
19593    @Override
19594    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19595        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19596            throw new SecurityException("Only the system may call restorePreferredActivities()");
19597        }
19598
19599        try {
19600            final XmlPullParser parser = Xml.newPullParser();
19601            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19602            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19603                    new BlobXmlRestorer() {
19604                        @Override
19605                        public void apply(XmlPullParser parser, int userId)
19606                                throws XmlPullParserException, IOException {
19607                            synchronized (mPackages) {
19608                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19609                                mSettings.writeLPr();
19610                            }
19611                        }
19612                    } );
19613        } catch (Exception e) {
19614            if (DEBUG_BACKUP) {
19615                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19616            }
19617        }
19618    }
19619
19620    @Override
19621    public byte[] getPermissionGrantBackup(int userId) {
19622        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19623            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19624        }
19625
19626        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19627        try {
19628            final XmlSerializer serializer = new FastXmlSerializer();
19629            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19630            serializer.startDocument(null, true);
19631            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19632
19633            synchronized (mPackages) {
19634                serializeRuntimePermissionGrantsLPr(serializer, userId);
19635            }
19636
19637            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19638            serializer.endDocument();
19639            serializer.flush();
19640        } catch (Exception e) {
19641            if (DEBUG_BACKUP) {
19642                Slog.e(TAG, "Unable to write default apps for backup", e);
19643            }
19644            return null;
19645        }
19646
19647        return dataStream.toByteArray();
19648    }
19649
19650    @Override
19651    public void restorePermissionGrants(byte[] backup, int userId) {
19652        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19653            throw new SecurityException("Only the system may call restorePermissionGrants()");
19654        }
19655
19656        try {
19657            final XmlPullParser parser = Xml.newPullParser();
19658            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19659            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19660                    new BlobXmlRestorer() {
19661                        @Override
19662                        public void apply(XmlPullParser parser, int userId)
19663                                throws XmlPullParserException, IOException {
19664                            synchronized (mPackages) {
19665                                processRestoredPermissionGrantsLPr(parser, userId);
19666                            }
19667                        }
19668                    } );
19669        } catch (Exception e) {
19670            if (DEBUG_BACKUP) {
19671                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19672            }
19673        }
19674    }
19675
19676    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19677            throws IOException {
19678        serializer.startTag(null, TAG_ALL_GRANTS);
19679
19680        final int N = mSettings.mPackages.size();
19681        for (int i = 0; i < N; i++) {
19682            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19683            boolean pkgGrantsKnown = false;
19684
19685            PermissionsState packagePerms = ps.getPermissionsState();
19686
19687            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19688                final int grantFlags = state.getFlags();
19689                // only look at grants that are not system/policy fixed
19690                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19691                    final boolean isGranted = state.isGranted();
19692                    // And only back up the user-twiddled state bits
19693                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19694                        final String packageName = mSettings.mPackages.keyAt(i);
19695                        if (!pkgGrantsKnown) {
19696                            serializer.startTag(null, TAG_GRANT);
19697                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19698                            pkgGrantsKnown = true;
19699                        }
19700
19701                        final boolean userSet =
19702                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19703                        final boolean userFixed =
19704                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19705                        final boolean revoke =
19706                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19707
19708                        serializer.startTag(null, TAG_PERMISSION);
19709                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19710                        if (isGranted) {
19711                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19712                        }
19713                        if (userSet) {
19714                            serializer.attribute(null, ATTR_USER_SET, "true");
19715                        }
19716                        if (userFixed) {
19717                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19718                        }
19719                        if (revoke) {
19720                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19721                        }
19722                        serializer.endTag(null, TAG_PERMISSION);
19723                    }
19724                }
19725            }
19726
19727            if (pkgGrantsKnown) {
19728                serializer.endTag(null, TAG_GRANT);
19729            }
19730        }
19731
19732        serializer.endTag(null, TAG_ALL_GRANTS);
19733    }
19734
19735    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19736            throws XmlPullParserException, IOException {
19737        String pkgName = null;
19738        int outerDepth = parser.getDepth();
19739        int type;
19740        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19741                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19742            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19743                continue;
19744            }
19745
19746            final String tagName = parser.getName();
19747            if (tagName.equals(TAG_GRANT)) {
19748                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19749                if (DEBUG_BACKUP) {
19750                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19751                }
19752            } else if (tagName.equals(TAG_PERMISSION)) {
19753
19754                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19755                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19756
19757                int newFlagSet = 0;
19758                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19759                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19760                }
19761                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19762                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19763                }
19764                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19765                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19766                }
19767                if (DEBUG_BACKUP) {
19768                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19769                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19770                }
19771                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19772                if (ps != null) {
19773                    // Already installed so we apply the grant immediately
19774                    if (DEBUG_BACKUP) {
19775                        Slog.v(TAG, "        + already installed; applying");
19776                    }
19777                    PermissionsState perms = ps.getPermissionsState();
19778                    BasePermission bp = mSettings.mPermissions.get(permName);
19779                    if (bp != null) {
19780                        if (isGranted) {
19781                            perms.grantRuntimePermission(bp, userId);
19782                        }
19783                        if (newFlagSet != 0) {
19784                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19785                        }
19786                    }
19787                } else {
19788                    // Need to wait for post-restore install to apply the grant
19789                    if (DEBUG_BACKUP) {
19790                        Slog.v(TAG, "        - not yet installed; saving for later");
19791                    }
19792                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19793                            isGranted, newFlagSet, userId);
19794                }
19795            } else {
19796                PackageManagerService.reportSettingsProblem(Log.WARN,
19797                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19798                XmlUtils.skipCurrentTag(parser);
19799            }
19800        }
19801
19802        scheduleWriteSettingsLocked();
19803        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19804    }
19805
19806    @Override
19807    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19808            int sourceUserId, int targetUserId, int flags) {
19809        mContext.enforceCallingOrSelfPermission(
19810                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19811        int callingUid = Binder.getCallingUid();
19812        enforceOwnerRights(ownerPackage, callingUid);
19813        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19814        if (intentFilter.countActions() == 0) {
19815            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19816            return;
19817        }
19818        synchronized (mPackages) {
19819            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19820                    ownerPackage, targetUserId, flags);
19821            CrossProfileIntentResolver resolver =
19822                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19823            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19824            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19825            if (existing != null) {
19826                int size = existing.size();
19827                for (int i = 0; i < size; i++) {
19828                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19829                        return;
19830                    }
19831                }
19832            }
19833            resolver.addFilter(newFilter);
19834            scheduleWritePackageRestrictionsLocked(sourceUserId);
19835        }
19836    }
19837
19838    @Override
19839    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19840        mContext.enforceCallingOrSelfPermission(
19841                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19842        int callingUid = Binder.getCallingUid();
19843        enforceOwnerRights(ownerPackage, callingUid);
19844        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19845        synchronized (mPackages) {
19846            CrossProfileIntentResolver resolver =
19847                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19848            ArraySet<CrossProfileIntentFilter> set =
19849                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19850            for (CrossProfileIntentFilter filter : set) {
19851                if (filter.getOwnerPackage().equals(ownerPackage)) {
19852                    resolver.removeFilter(filter);
19853                }
19854            }
19855            scheduleWritePackageRestrictionsLocked(sourceUserId);
19856        }
19857    }
19858
19859    // Enforcing that callingUid is owning pkg on userId
19860    private void enforceOwnerRights(String pkg, int callingUid) {
19861        // The system owns everything.
19862        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19863            return;
19864        }
19865        int callingUserId = UserHandle.getUserId(callingUid);
19866        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19867        if (pi == null) {
19868            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19869                    + callingUserId);
19870        }
19871        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19872            throw new SecurityException("Calling uid " + callingUid
19873                    + " does not own package " + pkg);
19874        }
19875    }
19876
19877    @Override
19878    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19879        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19880    }
19881
19882    /**
19883     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19884     * then reports the most likely home activity or null if there are more than one.
19885     */
19886    public ComponentName getDefaultHomeActivity(int userId) {
19887        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19888        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19889        if (cn != null) {
19890            return cn;
19891        }
19892
19893        // Find the launcher with the highest priority and return that component if there are no
19894        // other home activity with the same priority.
19895        int lastPriority = Integer.MIN_VALUE;
19896        ComponentName lastComponent = null;
19897        final int size = allHomeCandidates.size();
19898        for (int i = 0; i < size; i++) {
19899            final ResolveInfo ri = allHomeCandidates.get(i);
19900            if (ri.priority > lastPriority) {
19901                lastComponent = ri.activityInfo.getComponentName();
19902                lastPriority = ri.priority;
19903            } else if (ri.priority == lastPriority) {
19904                // Two components found with same priority.
19905                lastComponent = null;
19906            }
19907        }
19908        return lastComponent;
19909    }
19910
19911    private Intent getHomeIntent() {
19912        Intent intent = new Intent(Intent.ACTION_MAIN);
19913        intent.addCategory(Intent.CATEGORY_HOME);
19914        intent.addCategory(Intent.CATEGORY_DEFAULT);
19915        return intent;
19916    }
19917
19918    private IntentFilter getHomeFilter() {
19919        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19920        filter.addCategory(Intent.CATEGORY_HOME);
19921        filter.addCategory(Intent.CATEGORY_DEFAULT);
19922        return filter;
19923    }
19924
19925    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19926            int userId) {
19927        Intent intent  = getHomeIntent();
19928        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19929                PackageManager.GET_META_DATA, userId);
19930        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19931                true, false, false, userId);
19932
19933        allHomeCandidates.clear();
19934        if (list != null) {
19935            for (ResolveInfo ri : list) {
19936                allHomeCandidates.add(ri);
19937            }
19938        }
19939        return (preferred == null || preferred.activityInfo == null)
19940                ? null
19941                : new ComponentName(preferred.activityInfo.packageName,
19942                        preferred.activityInfo.name);
19943    }
19944
19945    @Override
19946    public void setHomeActivity(ComponentName comp, int userId) {
19947        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19948        getHomeActivitiesAsUser(homeActivities, userId);
19949
19950        boolean found = false;
19951
19952        final int size = homeActivities.size();
19953        final ComponentName[] set = new ComponentName[size];
19954        for (int i = 0; i < size; i++) {
19955            final ResolveInfo candidate = homeActivities.get(i);
19956            final ActivityInfo info = candidate.activityInfo;
19957            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19958            set[i] = activityName;
19959            if (!found && activityName.equals(comp)) {
19960                found = true;
19961            }
19962        }
19963        if (!found) {
19964            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19965                    + userId);
19966        }
19967        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19968                set, comp, userId);
19969    }
19970
19971    private @Nullable String getSetupWizardPackageName() {
19972        final Intent intent = new Intent(Intent.ACTION_MAIN);
19973        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19974
19975        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19976                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19977                        | MATCH_DISABLED_COMPONENTS,
19978                UserHandle.myUserId());
19979        if (matches.size() == 1) {
19980            return matches.get(0).getComponentInfo().packageName;
19981        } else {
19982            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19983                    + ": matches=" + matches);
19984            return null;
19985        }
19986    }
19987
19988    private @Nullable String getStorageManagerPackageName() {
19989        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19990
19991        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19992                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19993                        | MATCH_DISABLED_COMPONENTS,
19994                UserHandle.myUserId());
19995        if (matches.size() == 1) {
19996            return matches.get(0).getComponentInfo().packageName;
19997        } else {
19998            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19999                    + matches.size() + ": matches=" + matches);
20000            return null;
20001        }
20002    }
20003
20004    @Override
20005    public void setApplicationEnabledSetting(String appPackageName,
20006            int newState, int flags, int userId, String callingPackage) {
20007        if (!sUserManager.exists(userId)) return;
20008        if (callingPackage == null) {
20009            callingPackage = Integer.toString(Binder.getCallingUid());
20010        }
20011        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20012    }
20013
20014    @Override
20015    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20016        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20017        synchronized (mPackages) {
20018            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20019            if (pkgSetting != null) {
20020                pkgSetting.setUpdateAvailable(updateAvailable);
20021            }
20022        }
20023    }
20024
20025    @Override
20026    public void setComponentEnabledSetting(ComponentName componentName,
20027            int newState, int flags, int userId) {
20028        if (!sUserManager.exists(userId)) return;
20029        setEnabledSetting(componentName.getPackageName(),
20030                componentName.getClassName(), newState, flags, userId, null);
20031    }
20032
20033    private void setEnabledSetting(final String packageName, String className, int newState,
20034            final int flags, int userId, String callingPackage) {
20035        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20036              || newState == COMPONENT_ENABLED_STATE_ENABLED
20037              || newState == COMPONENT_ENABLED_STATE_DISABLED
20038              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20039              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20040            throw new IllegalArgumentException("Invalid new component state: "
20041                    + newState);
20042        }
20043        PackageSetting pkgSetting;
20044        final int uid = Binder.getCallingUid();
20045        final int permission;
20046        if (uid == Process.SYSTEM_UID) {
20047            permission = PackageManager.PERMISSION_GRANTED;
20048        } else {
20049            permission = mContext.checkCallingOrSelfPermission(
20050                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20051        }
20052        enforceCrossUserPermission(uid, userId,
20053                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20054        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20055        boolean sendNow = false;
20056        boolean isApp = (className == null);
20057        String componentName = isApp ? packageName : className;
20058        int packageUid = -1;
20059        ArrayList<String> components;
20060
20061        // writer
20062        synchronized (mPackages) {
20063            pkgSetting = mSettings.mPackages.get(packageName);
20064            if (pkgSetting == null) {
20065                if (className == null) {
20066                    throw new IllegalArgumentException("Unknown package: " + packageName);
20067                }
20068                throw new IllegalArgumentException(
20069                        "Unknown component: " + packageName + "/" + className);
20070            }
20071        }
20072
20073        // Limit who can change which apps
20074        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
20075            // Don't allow apps that don't have permission to modify other apps
20076            if (!allowedByPermission) {
20077                throw new SecurityException(
20078                        "Permission Denial: attempt to change component state from pid="
20079                        + Binder.getCallingPid()
20080                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
20081            }
20082            // Don't allow changing protected packages.
20083            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20084                throw new SecurityException("Cannot disable a protected package: " + packageName);
20085            }
20086        }
20087
20088        synchronized (mPackages) {
20089            if (uid == Process.SHELL_UID
20090                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20091                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20092                // unless it is a test package.
20093                int oldState = pkgSetting.getEnabled(userId);
20094                if (className == null
20095                    &&
20096                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20097                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20098                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20099                    &&
20100                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20101                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20102                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20103                    // ok
20104                } else {
20105                    throw new SecurityException(
20106                            "Shell cannot change component state for " + packageName + "/"
20107                            + className + " to " + newState);
20108                }
20109            }
20110            if (className == null) {
20111                // We're dealing with an application/package level state change
20112                if (pkgSetting.getEnabled(userId) == newState) {
20113                    // Nothing to do
20114                    return;
20115                }
20116                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20117                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20118                    // Don't care about who enables an app.
20119                    callingPackage = null;
20120                }
20121                pkgSetting.setEnabled(newState, userId, callingPackage);
20122                // pkgSetting.pkg.mSetEnabled = newState;
20123            } else {
20124                // We're dealing with a component level state change
20125                // First, verify that this is a valid class name.
20126                PackageParser.Package pkg = pkgSetting.pkg;
20127                if (pkg == null || !pkg.hasComponentClassName(className)) {
20128                    if (pkg != null &&
20129                            pkg.applicationInfo.targetSdkVersion >=
20130                                    Build.VERSION_CODES.JELLY_BEAN) {
20131                        throw new IllegalArgumentException("Component class " + className
20132                                + " does not exist in " + packageName);
20133                    } else {
20134                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20135                                + className + " does not exist in " + packageName);
20136                    }
20137                }
20138                switch (newState) {
20139                case COMPONENT_ENABLED_STATE_ENABLED:
20140                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20141                        return;
20142                    }
20143                    break;
20144                case COMPONENT_ENABLED_STATE_DISABLED:
20145                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20146                        return;
20147                    }
20148                    break;
20149                case COMPONENT_ENABLED_STATE_DEFAULT:
20150                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20151                        return;
20152                    }
20153                    break;
20154                default:
20155                    Slog.e(TAG, "Invalid new component state: " + newState);
20156                    return;
20157                }
20158            }
20159            scheduleWritePackageRestrictionsLocked(userId);
20160            updateSequenceNumberLP(packageName, new int[] { userId });
20161            final long callingId = Binder.clearCallingIdentity();
20162            try {
20163                updateInstantAppInstallerLocked(packageName);
20164            } finally {
20165                Binder.restoreCallingIdentity(callingId);
20166            }
20167            components = mPendingBroadcasts.get(userId, packageName);
20168            final boolean newPackage = components == null;
20169            if (newPackage) {
20170                components = new ArrayList<String>();
20171            }
20172            if (!components.contains(componentName)) {
20173                components.add(componentName);
20174            }
20175            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20176                sendNow = true;
20177                // Purge entry from pending broadcast list if another one exists already
20178                // since we are sending one right away.
20179                mPendingBroadcasts.remove(userId, packageName);
20180            } else {
20181                if (newPackage) {
20182                    mPendingBroadcasts.put(userId, packageName, components);
20183                }
20184                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20185                    // Schedule a message
20186                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20187                }
20188            }
20189        }
20190
20191        long callingId = Binder.clearCallingIdentity();
20192        try {
20193            if (sendNow) {
20194                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20195                sendPackageChangedBroadcast(packageName,
20196                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20197            }
20198        } finally {
20199            Binder.restoreCallingIdentity(callingId);
20200        }
20201    }
20202
20203    @Override
20204    public void flushPackageRestrictionsAsUser(int userId) {
20205        if (!sUserManager.exists(userId)) {
20206            return;
20207        }
20208        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20209                false /* checkShell */, "flushPackageRestrictions");
20210        synchronized (mPackages) {
20211            mSettings.writePackageRestrictionsLPr(userId);
20212            mDirtyUsers.remove(userId);
20213            if (mDirtyUsers.isEmpty()) {
20214                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20215            }
20216        }
20217    }
20218
20219    private void sendPackageChangedBroadcast(String packageName,
20220            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20221        if (DEBUG_INSTALL)
20222            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20223                    + componentNames);
20224        Bundle extras = new Bundle(4);
20225        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20226        String nameList[] = new String[componentNames.size()];
20227        componentNames.toArray(nameList);
20228        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20229        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20230        extras.putInt(Intent.EXTRA_UID, packageUid);
20231        // If this is not reporting a change of the overall package, then only send it
20232        // to registered receivers.  We don't want to launch a swath of apps for every
20233        // little component state change.
20234        final int flags = !componentNames.contains(packageName)
20235                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20236        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20237                new int[] {UserHandle.getUserId(packageUid)});
20238    }
20239
20240    @Override
20241    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20242        if (!sUserManager.exists(userId)) return;
20243        final int uid = Binder.getCallingUid();
20244        final int permission = mContext.checkCallingOrSelfPermission(
20245                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20246        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20247        enforceCrossUserPermission(uid, userId,
20248                true /* requireFullPermission */, true /* checkShell */, "stop package");
20249        // writer
20250        synchronized (mPackages) {
20251            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20252                    allowedByPermission, uid, userId)) {
20253                scheduleWritePackageRestrictionsLocked(userId);
20254            }
20255        }
20256    }
20257
20258    @Override
20259    public String getInstallerPackageName(String packageName) {
20260        // reader
20261        synchronized (mPackages) {
20262            return mSettings.getInstallerPackageNameLPr(packageName);
20263        }
20264    }
20265
20266    public boolean isOrphaned(String packageName) {
20267        // reader
20268        synchronized (mPackages) {
20269            return mSettings.isOrphaned(packageName);
20270        }
20271    }
20272
20273    @Override
20274    public int getApplicationEnabledSetting(String packageName, int userId) {
20275        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20276        int uid = Binder.getCallingUid();
20277        enforceCrossUserPermission(uid, userId,
20278                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20279        // reader
20280        synchronized (mPackages) {
20281            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20282        }
20283    }
20284
20285    @Override
20286    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20287        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20288        int uid = Binder.getCallingUid();
20289        enforceCrossUserPermission(uid, userId,
20290                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20291        // reader
20292        synchronized (mPackages) {
20293            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20294        }
20295    }
20296
20297    @Override
20298    public void enterSafeMode() {
20299        enforceSystemOrRoot("Only the system can request entering safe mode");
20300
20301        if (!mSystemReady) {
20302            mSafeMode = true;
20303        }
20304    }
20305
20306    @Override
20307    public void systemReady() {
20308        mSystemReady = true;
20309        final ContentResolver resolver = mContext.getContentResolver();
20310        ContentObserver co = new ContentObserver(mHandler) {
20311            @Override
20312            public void onChange(boolean selfChange) {
20313                mEphemeralAppsDisabled =
20314                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20315                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20316            }
20317        };
20318        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20319                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20320                false, co, UserHandle.USER_SYSTEM);
20321        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20322                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20323        co.onChange(true);
20324
20325        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20326        // disabled after already being started.
20327        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20328                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20329
20330        // Read the compatibilty setting when the system is ready.
20331        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20332                mContext.getContentResolver(),
20333                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20334        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20335        if (DEBUG_SETTINGS) {
20336            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20337        }
20338
20339        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20340
20341        synchronized (mPackages) {
20342            // Verify that all of the preferred activity components actually
20343            // exist.  It is possible for applications to be updated and at
20344            // that point remove a previously declared activity component that
20345            // had been set as a preferred activity.  We try to clean this up
20346            // the next time we encounter that preferred activity, but it is
20347            // possible for the user flow to never be able to return to that
20348            // situation so here we do a sanity check to make sure we haven't
20349            // left any junk around.
20350            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20351            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20352                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20353                removed.clear();
20354                for (PreferredActivity pa : pir.filterSet()) {
20355                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20356                        removed.add(pa);
20357                    }
20358                }
20359                if (removed.size() > 0) {
20360                    for (int r=0; r<removed.size(); r++) {
20361                        PreferredActivity pa = removed.get(r);
20362                        Slog.w(TAG, "Removing dangling preferred activity: "
20363                                + pa.mPref.mComponent);
20364                        pir.removeFilter(pa);
20365                    }
20366                    mSettings.writePackageRestrictionsLPr(
20367                            mSettings.mPreferredActivities.keyAt(i));
20368                }
20369            }
20370
20371            for (int userId : UserManagerService.getInstance().getUserIds()) {
20372                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20373                    grantPermissionsUserIds = ArrayUtils.appendInt(
20374                            grantPermissionsUserIds, userId);
20375                }
20376            }
20377        }
20378        sUserManager.systemReady();
20379
20380        // If we upgraded grant all default permissions before kicking off.
20381        for (int userId : grantPermissionsUserIds) {
20382            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20383        }
20384
20385        // If we did not grant default permissions, we preload from this the
20386        // default permission exceptions lazily to ensure we don't hit the
20387        // disk on a new user creation.
20388        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20389            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20390        }
20391
20392        // Kick off any messages waiting for system ready
20393        if (mPostSystemReadyMessages != null) {
20394            for (Message msg : mPostSystemReadyMessages) {
20395                msg.sendToTarget();
20396            }
20397            mPostSystemReadyMessages = null;
20398        }
20399
20400        // Watch for external volumes that come and go over time
20401        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20402        storage.registerListener(mStorageListener);
20403
20404        mInstallerService.systemReady();
20405        mPackageDexOptimizer.systemReady();
20406
20407        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20408                StorageManagerInternal.class);
20409        StorageManagerInternal.addExternalStoragePolicy(
20410                new StorageManagerInternal.ExternalStorageMountPolicy() {
20411            @Override
20412            public int getMountMode(int uid, String packageName) {
20413                if (Process.isIsolated(uid)) {
20414                    return Zygote.MOUNT_EXTERNAL_NONE;
20415                }
20416                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20417                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20418                }
20419                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20420                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20421                }
20422                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20423                    return Zygote.MOUNT_EXTERNAL_READ;
20424                }
20425                return Zygote.MOUNT_EXTERNAL_WRITE;
20426            }
20427
20428            @Override
20429            public boolean hasExternalStorage(int uid, String packageName) {
20430                return true;
20431            }
20432        });
20433
20434        // Now that we're mostly running, clean up stale users and apps
20435        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20436        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20437
20438        if (mPrivappPermissionsViolations != null) {
20439            Slog.wtf(TAG,"Signature|privileged permissions not in "
20440                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20441            mPrivappPermissionsViolations = null;
20442        }
20443    }
20444
20445    public void waitForAppDataPrepared() {
20446        if (mPrepareAppDataFuture == null) {
20447            return;
20448        }
20449        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20450        mPrepareAppDataFuture = null;
20451    }
20452
20453    @Override
20454    public boolean isSafeMode() {
20455        return mSafeMode;
20456    }
20457
20458    @Override
20459    public boolean hasSystemUidErrors() {
20460        return mHasSystemUidErrors;
20461    }
20462
20463    static String arrayToString(int[] array) {
20464        StringBuffer buf = new StringBuffer(128);
20465        buf.append('[');
20466        if (array != null) {
20467            for (int i=0; i<array.length; i++) {
20468                if (i > 0) buf.append(", ");
20469                buf.append(array[i]);
20470            }
20471        }
20472        buf.append(']');
20473        return buf.toString();
20474    }
20475
20476    static class DumpState {
20477        public static final int DUMP_LIBS = 1 << 0;
20478        public static final int DUMP_FEATURES = 1 << 1;
20479        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20480        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20481        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20482        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20483        public static final int DUMP_PERMISSIONS = 1 << 6;
20484        public static final int DUMP_PACKAGES = 1 << 7;
20485        public static final int DUMP_SHARED_USERS = 1 << 8;
20486        public static final int DUMP_MESSAGES = 1 << 9;
20487        public static final int DUMP_PROVIDERS = 1 << 10;
20488        public static final int DUMP_VERIFIERS = 1 << 11;
20489        public static final int DUMP_PREFERRED = 1 << 12;
20490        public static final int DUMP_PREFERRED_XML = 1 << 13;
20491        public static final int DUMP_KEYSETS = 1 << 14;
20492        public static final int DUMP_VERSION = 1 << 15;
20493        public static final int DUMP_INSTALLS = 1 << 16;
20494        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20495        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20496        public static final int DUMP_FROZEN = 1 << 19;
20497        public static final int DUMP_DEXOPT = 1 << 20;
20498        public static final int DUMP_COMPILER_STATS = 1 << 21;
20499        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20500
20501        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20502
20503        private int mTypes;
20504
20505        private int mOptions;
20506
20507        private boolean mTitlePrinted;
20508
20509        private SharedUserSetting mSharedUser;
20510
20511        public boolean isDumping(int type) {
20512            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20513                return true;
20514            }
20515
20516            return (mTypes & type) != 0;
20517        }
20518
20519        public void setDump(int type) {
20520            mTypes |= type;
20521        }
20522
20523        public boolean isOptionEnabled(int option) {
20524            return (mOptions & option) != 0;
20525        }
20526
20527        public void setOptionEnabled(int option) {
20528            mOptions |= option;
20529        }
20530
20531        public boolean onTitlePrinted() {
20532            final boolean printed = mTitlePrinted;
20533            mTitlePrinted = true;
20534            return printed;
20535        }
20536
20537        public boolean getTitlePrinted() {
20538            return mTitlePrinted;
20539        }
20540
20541        public void setTitlePrinted(boolean enabled) {
20542            mTitlePrinted = enabled;
20543        }
20544
20545        public SharedUserSetting getSharedUser() {
20546            return mSharedUser;
20547        }
20548
20549        public void setSharedUser(SharedUserSetting user) {
20550            mSharedUser = user;
20551        }
20552    }
20553
20554    @Override
20555    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20556            FileDescriptor err, String[] args, ShellCallback callback,
20557            ResultReceiver resultReceiver) {
20558        (new PackageManagerShellCommand(this)).exec(
20559                this, in, out, err, args, callback, resultReceiver);
20560    }
20561
20562    @Override
20563    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20564        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20565
20566        DumpState dumpState = new DumpState();
20567        boolean fullPreferred = false;
20568        boolean checkin = false;
20569
20570        String packageName = null;
20571        ArraySet<String> permissionNames = null;
20572
20573        int opti = 0;
20574        while (opti < args.length) {
20575            String opt = args[opti];
20576            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20577                break;
20578            }
20579            opti++;
20580
20581            if ("-a".equals(opt)) {
20582                // Right now we only know how to print all.
20583            } else if ("-h".equals(opt)) {
20584                pw.println("Package manager dump options:");
20585                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20586                pw.println("    --checkin: dump for a checkin");
20587                pw.println("    -f: print details of intent filters");
20588                pw.println("    -h: print this help");
20589                pw.println("  cmd may be one of:");
20590                pw.println("    l[ibraries]: list known shared libraries");
20591                pw.println("    f[eatures]: list device features");
20592                pw.println("    k[eysets]: print known keysets");
20593                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20594                pw.println("    perm[issions]: dump permissions");
20595                pw.println("    permission [name ...]: dump declaration and use of given permission");
20596                pw.println("    pref[erred]: print preferred package settings");
20597                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20598                pw.println("    prov[iders]: dump content providers");
20599                pw.println("    p[ackages]: dump installed packages");
20600                pw.println("    s[hared-users]: dump shared user IDs");
20601                pw.println("    m[essages]: print collected runtime messages");
20602                pw.println("    v[erifiers]: print package verifier info");
20603                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20604                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20605                pw.println("    version: print database version info");
20606                pw.println("    write: write current settings now");
20607                pw.println("    installs: details about install sessions");
20608                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20609                pw.println("    dexopt: dump dexopt state");
20610                pw.println("    compiler-stats: dump compiler statistics");
20611                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20612                pw.println("    <package.name>: info about given package");
20613                return;
20614            } else if ("--checkin".equals(opt)) {
20615                checkin = true;
20616            } else if ("-f".equals(opt)) {
20617                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20618            } else if ("--proto".equals(opt)) {
20619                dumpProto(fd);
20620                return;
20621            } else {
20622                pw.println("Unknown argument: " + opt + "; use -h for help");
20623            }
20624        }
20625
20626        // Is the caller requesting to dump a particular piece of data?
20627        if (opti < args.length) {
20628            String cmd = args[opti];
20629            opti++;
20630            // Is this a package name?
20631            if ("android".equals(cmd) || cmd.contains(".")) {
20632                packageName = cmd;
20633                // When dumping a single package, we always dump all of its
20634                // filter information since the amount of data will be reasonable.
20635                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20636            } else if ("check-permission".equals(cmd)) {
20637                if (opti >= args.length) {
20638                    pw.println("Error: check-permission missing permission argument");
20639                    return;
20640                }
20641                String perm = args[opti];
20642                opti++;
20643                if (opti >= args.length) {
20644                    pw.println("Error: check-permission missing package argument");
20645                    return;
20646                }
20647
20648                String pkg = args[opti];
20649                opti++;
20650                int user = UserHandle.getUserId(Binder.getCallingUid());
20651                if (opti < args.length) {
20652                    try {
20653                        user = Integer.parseInt(args[opti]);
20654                    } catch (NumberFormatException e) {
20655                        pw.println("Error: check-permission user argument is not a number: "
20656                                + args[opti]);
20657                        return;
20658                    }
20659                }
20660
20661                // Normalize package name to handle renamed packages and static libs
20662                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20663
20664                pw.println(checkPermission(perm, pkg, user));
20665                return;
20666            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20667                dumpState.setDump(DumpState.DUMP_LIBS);
20668            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20669                dumpState.setDump(DumpState.DUMP_FEATURES);
20670            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20671                if (opti >= args.length) {
20672                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20673                            | DumpState.DUMP_SERVICE_RESOLVERS
20674                            | DumpState.DUMP_RECEIVER_RESOLVERS
20675                            | DumpState.DUMP_CONTENT_RESOLVERS);
20676                } else {
20677                    while (opti < args.length) {
20678                        String name = args[opti];
20679                        if ("a".equals(name) || "activity".equals(name)) {
20680                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20681                        } else if ("s".equals(name) || "service".equals(name)) {
20682                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20683                        } else if ("r".equals(name) || "receiver".equals(name)) {
20684                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20685                        } else if ("c".equals(name) || "content".equals(name)) {
20686                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20687                        } else {
20688                            pw.println("Error: unknown resolver table type: " + name);
20689                            return;
20690                        }
20691                        opti++;
20692                    }
20693                }
20694            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20695                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20696            } else if ("permission".equals(cmd)) {
20697                if (opti >= args.length) {
20698                    pw.println("Error: permission requires permission name");
20699                    return;
20700                }
20701                permissionNames = new ArraySet<>();
20702                while (opti < args.length) {
20703                    permissionNames.add(args[opti]);
20704                    opti++;
20705                }
20706                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20707                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20708            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20709                dumpState.setDump(DumpState.DUMP_PREFERRED);
20710            } else if ("preferred-xml".equals(cmd)) {
20711                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20712                if (opti < args.length && "--full".equals(args[opti])) {
20713                    fullPreferred = true;
20714                    opti++;
20715                }
20716            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20717                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20718            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20719                dumpState.setDump(DumpState.DUMP_PACKAGES);
20720            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20721                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20722            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20723                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20724            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20725                dumpState.setDump(DumpState.DUMP_MESSAGES);
20726            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20727                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20728            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20729                    || "intent-filter-verifiers".equals(cmd)) {
20730                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20731            } else if ("version".equals(cmd)) {
20732                dumpState.setDump(DumpState.DUMP_VERSION);
20733            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20734                dumpState.setDump(DumpState.DUMP_KEYSETS);
20735            } else if ("installs".equals(cmd)) {
20736                dumpState.setDump(DumpState.DUMP_INSTALLS);
20737            } else if ("frozen".equals(cmd)) {
20738                dumpState.setDump(DumpState.DUMP_FROZEN);
20739            } else if ("dexopt".equals(cmd)) {
20740                dumpState.setDump(DumpState.DUMP_DEXOPT);
20741            } else if ("compiler-stats".equals(cmd)) {
20742                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20743            } else if ("enabled-overlays".equals(cmd)) {
20744                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20745            } else if ("write".equals(cmd)) {
20746                synchronized (mPackages) {
20747                    mSettings.writeLPr();
20748                    pw.println("Settings written.");
20749                    return;
20750                }
20751            }
20752        }
20753
20754        if (checkin) {
20755            pw.println("vers,1");
20756        }
20757
20758        // reader
20759        synchronized (mPackages) {
20760            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20761                if (!checkin) {
20762                    if (dumpState.onTitlePrinted())
20763                        pw.println();
20764                    pw.println("Database versions:");
20765                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20766                }
20767            }
20768
20769            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20770                if (!checkin) {
20771                    if (dumpState.onTitlePrinted())
20772                        pw.println();
20773                    pw.println("Verifiers:");
20774                    pw.print("  Required: ");
20775                    pw.print(mRequiredVerifierPackage);
20776                    pw.print(" (uid=");
20777                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20778                            UserHandle.USER_SYSTEM));
20779                    pw.println(")");
20780                } else if (mRequiredVerifierPackage != null) {
20781                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20782                    pw.print(",");
20783                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20784                            UserHandle.USER_SYSTEM));
20785                }
20786            }
20787
20788            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20789                    packageName == null) {
20790                if (mIntentFilterVerifierComponent != null) {
20791                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20792                    if (!checkin) {
20793                        if (dumpState.onTitlePrinted())
20794                            pw.println();
20795                        pw.println("Intent Filter Verifier:");
20796                        pw.print("  Using: ");
20797                        pw.print(verifierPackageName);
20798                        pw.print(" (uid=");
20799                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20800                                UserHandle.USER_SYSTEM));
20801                        pw.println(")");
20802                    } else if (verifierPackageName != null) {
20803                        pw.print("ifv,"); pw.print(verifierPackageName);
20804                        pw.print(",");
20805                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20806                                UserHandle.USER_SYSTEM));
20807                    }
20808                } else {
20809                    pw.println();
20810                    pw.println("No Intent Filter Verifier available!");
20811                }
20812            }
20813
20814            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20815                boolean printedHeader = false;
20816                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20817                while (it.hasNext()) {
20818                    String libName = it.next();
20819                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20820                    if (versionedLib == null) {
20821                        continue;
20822                    }
20823                    final int versionCount = versionedLib.size();
20824                    for (int i = 0; i < versionCount; i++) {
20825                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20826                        if (!checkin) {
20827                            if (!printedHeader) {
20828                                if (dumpState.onTitlePrinted())
20829                                    pw.println();
20830                                pw.println("Libraries:");
20831                                printedHeader = true;
20832                            }
20833                            pw.print("  ");
20834                        } else {
20835                            pw.print("lib,");
20836                        }
20837                        pw.print(libEntry.info.getName());
20838                        if (libEntry.info.isStatic()) {
20839                            pw.print(" version=" + libEntry.info.getVersion());
20840                        }
20841                        if (!checkin) {
20842                            pw.print(" -> ");
20843                        }
20844                        if (libEntry.path != null) {
20845                            pw.print(" (jar) ");
20846                            pw.print(libEntry.path);
20847                        } else {
20848                            pw.print(" (apk) ");
20849                            pw.print(libEntry.apk);
20850                        }
20851                        pw.println();
20852                    }
20853                }
20854            }
20855
20856            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20857                if (dumpState.onTitlePrinted())
20858                    pw.println();
20859                if (!checkin) {
20860                    pw.println("Features:");
20861                }
20862
20863                synchronized (mAvailableFeatures) {
20864                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20865                        if (checkin) {
20866                            pw.print("feat,");
20867                            pw.print(feat.name);
20868                            pw.print(",");
20869                            pw.println(feat.version);
20870                        } else {
20871                            pw.print("  ");
20872                            pw.print(feat.name);
20873                            if (feat.version > 0) {
20874                                pw.print(" version=");
20875                                pw.print(feat.version);
20876                            }
20877                            pw.println();
20878                        }
20879                    }
20880                }
20881            }
20882
20883            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20884                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20885                        : "Activity Resolver Table:", "  ", packageName,
20886                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20887                    dumpState.setTitlePrinted(true);
20888                }
20889            }
20890            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20891                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20892                        : "Receiver Resolver Table:", "  ", packageName,
20893                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20894                    dumpState.setTitlePrinted(true);
20895                }
20896            }
20897            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20898                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20899                        : "Service Resolver Table:", "  ", packageName,
20900                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20901                    dumpState.setTitlePrinted(true);
20902                }
20903            }
20904            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20905                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20906                        : "Provider Resolver Table:", "  ", packageName,
20907                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20908                    dumpState.setTitlePrinted(true);
20909                }
20910            }
20911
20912            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20913                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20914                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20915                    int user = mSettings.mPreferredActivities.keyAt(i);
20916                    if (pir.dump(pw,
20917                            dumpState.getTitlePrinted()
20918                                ? "\nPreferred Activities User " + user + ":"
20919                                : "Preferred Activities User " + user + ":", "  ",
20920                            packageName, true, false)) {
20921                        dumpState.setTitlePrinted(true);
20922                    }
20923                }
20924            }
20925
20926            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20927                pw.flush();
20928                FileOutputStream fout = new FileOutputStream(fd);
20929                BufferedOutputStream str = new BufferedOutputStream(fout);
20930                XmlSerializer serializer = new FastXmlSerializer();
20931                try {
20932                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20933                    serializer.startDocument(null, true);
20934                    serializer.setFeature(
20935                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20936                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20937                    serializer.endDocument();
20938                    serializer.flush();
20939                } catch (IllegalArgumentException e) {
20940                    pw.println("Failed writing: " + e);
20941                } catch (IllegalStateException e) {
20942                    pw.println("Failed writing: " + e);
20943                } catch (IOException e) {
20944                    pw.println("Failed writing: " + e);
20945                }
20946            }
20947
20948            if (!checkin
20949                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20950                    && packageName == null) {
20951                pw.println();
20952                int count = mSettings.mPackages.size();
20953                if (count == 0) {
20954                    pw.println("No applications!");
20955                    pw.println();
20956                } else {
20957                    final String prefix = "  ";
20958                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20959                    if (allPackageSettings.size() == 0) {
20960                        pw.println("No domain preferred apps!");
20961                        pw.println();
20962                    } else {
20963                        pw.println("App verification status:");
20964                        pw.println();
20965                        count = 0;
20966                        for (PackageSetting ps : allPackageSettings) {
20967                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20968                            if (ivi == null || ivi.getPackageName() == null) continue;
20969                            pw.println(prefix + "Package: " + ivi.getPackageName());
20970                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20971                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20972                            pw.println();
20973                            count++;
20974                        }
20975                        if (count == 0) {
20976                            pw.println(prefix + "No app verification established.");
20977                            pw.println();
20978                        }
20979                        for (int userId : sUserManager.getUserIds()) {
20980                            pw.println("App linkages for user " + userId + ":");
20981                            pw.println();
20982                            count = 0;
20983                            for (PackageSetting ps : allPackageSettings) {
20984                                final long status = ps.getDomainVerificationStatusForUser(userId);
20985                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20986                                        && !DEBUG_DOMAIN_VERIFICATION) {
20987                                    continue;
20988                                }
20989                                pw.println(prefix + "Package: " + ps.name);
20990                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20991                                String statusStr = IntentFilterVerificationInfo.
20992                                        getStatusStringFromValue(status);
20993                                pw.println(prefix + "Status:  " + statusStr);
20994                                pw.println();
20995                                count++;
20996                            }
20997                            if (count == 0) {
20998                                pw.println(prefix + "No configured app linkages.");
20999                                pw.println();
21000                            }
21001                        }
21002                    }
21003                }
21004            }
21005
21006            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21007                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21008                if (packageName == null && permissionNames == null) {
21009                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21010                        if (iperm == 0) {
21011                            if (dumpState.onTitlePrinted())
21012                                pw.println();
21013                            pw.println("AppOp Permissions:");
21014                        }
21015                        pw.print("  AppOp Permission ");
21016                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21017                        pw.println(":");
21018                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21019                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21020                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21021                        }
21022                    }
21023                }
21024            }
21025
21026            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21027                boolean printedSomething = false;
21028                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21029                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21030                        continue;
21031                    }
21032                    if (!printedSomething) {
21033                        if (dumpState.onTitlePrinted())
21034                            pw.println();
21035                        pw.println("Registered ContentProviders:");
21036                        printedSomething = true;
21037                    }
21038                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21039                    pw.print("    "); pw.println(p.toString());
21040                }
21041                printedSomething = false;
21042                for (Map.Entry<String, PackageParser.Provider> entry :
21043                        mProvidersByAuthority.entrySet()) {
21044                    PackageParser.Provider p = entry.getValue();
21045                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21046                        continue;
21047                    }
21048                    if (!printedSomething) {
21049                        if (dumpState.onTitlePrinted())
21050                            pw.println();
21051                        pw.println("ContentProvider Authorities:");
21052                        printedSomething = true;
21053                    }
21054                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21055                    pw.print("    "); pw.println(p.toString());
21056                    if (p.info != null && p.info.applicationInfo != null) {
21057                        final String appInfo = p.info.applicationInfo.toString();
21058                        pw.print("      applicationInfo="); pw.println(appInfo);
21059                    }
21060                }
21061            }
21062
21063            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21064                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21065            }
21066
21067            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21068                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21069            }
21070
21071            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21072                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21073            }
21074
21075            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21076                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21077            }
21078
21079            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21080                // XXX should handle packageName != null by dumping only install data that
21081                // the given package is involved with.
21082                if (dumpState.onTitlePrinted()) pw.println();
21083
21084                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21085                ipw.println();
21086                ipw.println("Frozen packages:");
21087                ipw.increaseIndent();
21088                if (mFrozenPackages.size() == 0) {
21089                    ipw.println("(none)");
21090                } else {
21091                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21092                        ipw.println(mFrozenPackages.valueAt(i));
21093                    }
21094                }
21095                ipw.decreaseIndent();
21096            }
21097
21098            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21099                if (dumpState.onTitlePrinted()) pw.println();
21100                dumpDexoptStateLPr(pw, packageName);
21101            }
21102
21103            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21104                if (dumpState.onTitlePrinted()) pw.println();
21105                dumpCompilerStatsLPr(pw, packageName);
21106            }
21107
21108            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21109                if (dumpState.onTitlePrinted()) pw.println();
21110                dumpEnabledOverlaysLPr(pw);
21111            }
21112
21113            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21114                if (dumpState.onTitlePrinted()) pw.println();
21115                mSettings.dumpReadMessagesLPr(pw, dumpState);
21116
21117                pw.println();
21118                pw.println("Package warning messages:");
21119                BufferedReader in = null;
21120                String line = null;
21121                try {
21122                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21123                    while ((line = in.readLine()) != null) {
21124                        if (line.contains("ignored: updated version")) continue;
21125                        pw.println(line);
21126                    }
21127                } catch (IOException ignored) {
21128                } finally {
21129                    IoUtils.closeQuietly(in);
21130                }
21131            }
21132
21133            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21134                BufferedReader in = null;
21135                String line = null;
21136                try {
21137                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21138                    while ((line = in.readLine()) != null) {
21139                        if (line.contains("ignored: updated version")) continue;
21140                        pw.print("msg,");
21141                        pw.println(line);
21142                    }
21143                } catch (IOException ignored) {
21144                } finally {
21145                    IoUtils.closeQuietly(in);
21146                }
21147            }
21148        }
21149
21150        // PackageInstaller should be called outside of mPackages lock
21151        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21152            // XXX should handle packageName != null by dumping only install data that
21153            // the given package is involved with.
21154            if (dumpState.onTitlePrinted()) pw.println();
21155            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21156        }
21157    }
21158
21159    private void dumpProto(FileDescriptor fd) {
21160        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21161
21162        synchronized (mPackages) {
21163            final long requiredVerifierPackageToken =
21164                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21165            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21166            proto.write(
21167                    PackageServiceDumpProto.PackageShortProto.UID,
21168                    getPackageUid(
21169                            mRequiredVerifierPackage,
21170                            MATCH_DEBUG_TRIAGED_MISSING,
21171                            UserHandle.USER_SYSTEM));
21172            proto.end(requiredVerifierPackageToken);
21173
21174            if (mIntentFilterVerifierComponent != null) {
21175                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21176                final long verifierPackageToken =
21177                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21178                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21179                proto.write(
21180                        PackageServiceDumpProto.PackageShortProto.UID,
21181                        getPackageUid(
21182                                verifierPackageName,
21183                                MATCH_DEBUG_TRIAGED_MISSING,
21184                                UserHandle.USER_SYSTEM));
21185                proto.end(verifierPackageToken);
21186            }
21187
21188            dumpSharedLibrariesProto(proto);
21189            dumpFeaturesProto(proto);
21190            mSettings.dumpPackagesProto(proto);
21191            mSettings.dumpSharedUsersProto(proto);
21192            dumpMessagesProto(proto);
21193        }
21194        proto.flush();
21195    }
21196
21197    private void dumpMessagesProto(ProtoOutputStream proto) {
21198        BufferedReader in = null;
21199        String line = null;
21200        try {
21201            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21202            while ((line = in.readLine()) != null) {
21203                if (line.contains("ignored: updated version")) continue;
21204                proto.write(PackageServiceDumpProto.MESSAGES, line);
21205            }
21206        } catch (IOException ignored) {
21207        } finally {
21208            IoUtils.closeQuietly(in);
21209        }
21210    }
21211
21212    private void dumpFeaturesProto(ProtoOutputStream proto) {
21213        synchronized (mAvailableFeatures) {
21214            final int count = mAvailableFeatures.size();
21215            for (int i = 0; i < count; i++) {
21216                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21217                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21218                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21219                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21220                proto.end(featureToken);
21221            }
21222        }
21223    }
21224
21225    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21226        final int count = mSharedLibraries.size();
21227        for (int i = 0; i < count; i++) {
21228            final String libName = mSharedLibraries.keyAt(i);
21229            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21230            if (versionedLib == null) {
21231                continue;
21232            }
21233            final int versionCount = versionedLib.size();
21234            for (int j = 0; j < versionCount; j++) {
21235                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21236                final long sharedLibraryToken =
21237                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21238                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21239                final boolean isJar = (libEntry.path != null);
21240                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21241                if (isJar) {
21242                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21243                } else {
21244                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21245                }
21246                proto.end(sharedLibraryToken);
21247            }
21248        }
21249    }
21250
21251    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21252        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21253        ipw.println();
21254        ipw.println("Dexopt state:");
21255        ipw.increaseIndent();
21256        Collection<PackageParser.Package> packages = null;
21257        if (packageName != null) {
21258            PackageParser.Package targetPackage = mPackages.get(packageName);
21259            if (targetPackage != null) {
21260                packages = Collections.singletonList(targetPackage);
21261            } else {
21262                ipw.println("Unable to find package: " + packageName);
21263                return;
21264            }
21265        } else {
21266            packages = mPackages.values();
21267        }
21268
21269        for (PackageParser.Package pkg : packages) {
21270            ipw.println("[" + pkg.packageName + "]");
21271            ipw.increaseIndent();
21272            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21273            ipw.decreaseIndent();
21274        }
21275    }
21276
21277    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21278        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21279        ipw.println();
21280        ipw.println("Compiler stats:");
21281        ipw.increaseIndent();
21282        Collection<PackageParser.Package> packages = null;
21283        if (packageName != null) {
21284            PackageParser.Package targetPackage = mPackages.get(packageName);
21285            if (targetPackage != null) {
21286                packages = Collections.singletonList(targetPackage);
21287            } else {
21288                ipw.println("Unable to find package: " + packageName);
21289                return;
21290            }
21291        } else {
21292            packages = mPackages.values();
21293        }
21294
21295        for (PackageParser.Package pkg : packages) {
21296            ipw.println("[" + pkg.packageName + "]");
21297            ipw.increaseIndent();
21298
21299            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21300            if (stats == null) {
21301                ipw.println("(No recorded stats)");
21302            } else {
21303                stats.dump(ipw);
21304            }
21305            ipw.decreaseIndent();
21306        }
21307    }
21308
21309    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21310        pw.println("Enabled overlay paths:");
21311        final int N = mEnabledOverlayPaths.size();
21312        for (int i = 0; i < N; i++) {
21313            final int userId = mEnabledOverlayPaths.keyAt(i);
21314            pw.println(String.format("    User %d:", userId));
21315            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21316                mEnabledOverlayPaths.valueAt(i);
21317            final int M = userSpecificOverlays.size();
21318            for (int j = 0; j < M; j++) {
21319                final String targetPackageName = userSpecificOverlays.keyAt(j);
21320                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21321                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21322            }
21323        }
21324    }
21325
21326    private String dumpDomainString(String packageName) {
21327        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21328                .getList();
21329        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21330
21331        ArraySet<String> result = new ArraySet<>();
21332        if (iviList.size() > 0) {
21333            for (IntentFilterVerificationInfo ivi : iviList) {
21334                for (String host : ivi.getDomains()) {
21335                    result.add(host);
21336                }
21337            }
21338        }
21339        if (filters != null && filters.size() > 0) {
21340            for (IntentFilter filter : filters) {
21341                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21342                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21343                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21344                    result.addAll(filter.getHostsList());
21345                }
21346            }
21347        }
21348
21349        StringBuilder sb = new StringBuilder(result.size() * 16);
21350        for (String domain : result) {
21351            if (sb.length() > 0) sb.append(" ");
21352            sb.append(domain);
21353        }
21354        return sb.toString();
21355    }
21356
21357    // ------- apps on sdcard specific code -------
21358    static final boolean DEBUG_SD_INSTALL = false;
21359
21360    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21361
21362    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21363
21364    private boolean mMediaMounted = false;
21365
21366    static String getEncryptKey() {
21367        try {
21368            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21369                    SD_ENCRYPTION_KEYSTORE_NAME);
21370            if (sdEncKey == null) {
21371                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21372                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21373                if (sdEncKey == null) {
21374                    Slog.e(TAG, "Failed to create encryption keys");
21375                    return null;
21376                }
21377            }
21378            return sdEncKey;
21379        } catch (NoSuchAlgorithmException nsae) {
21380            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21381            return null;
21382        } catch (IOException ioe) {
21383            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21384            return null;
21385        }
21386    }
21387
21388    /*
21389     * Update media status on PackageManager.
21390     */
21391    @Override
21392    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21393        int callingUid = Binder.getCallingUid();
21394        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21395            throw new SecurityException("Media status can only be updated by the system");
21396        }
21397        // reader; this apparently protects mMediaMounted, but should probably
21398        // be a different lock in that case.
21399        synchronized (mPackages) {
21400            Log.i(TAG, "Updating external media status from "
21401                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21402                    + (mediaStatus ? "mounted" : "unmounted"));
21403            if (DEBUG_SD_INSTALL)
21404                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21405                        + ", mMediaMounted=" + mMediaMounted);
21406            if (mediaStatus == mMediaMounted) {
21407                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21408                        : 0, -1);
21409                mHandler.sendMessage(msg);
21410                return;
21411            }
21412            mMediaMounted = mediaStatus;
21413        }
21414        // Queue up an async operation since the package installation may take a
21415        // little while.
21416        mHandler.post(new Runnable() {
21417            public void run() {
21418                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21419            }
21420        });
21421    }
21422
21423    /**
21424     * Called by StorageManagerService when the initial ASECs to scan are available.
21425     * Should block until all the ASEC containers are finished being scanned.
21426     */
21427    public void scanAvailableAsecs() {
21428        updateExternalMediaStatusInner(true, false, false);
21429    }
21430
21431    /*
21432     * Collect information of applications on external media, map them against
21433     * existing containers and update information based on current mount status.
21434     * Please note that we always have to report status if reportStatus has been
21435     * set to true especially when unloading packages.
21436     */
21437    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21438            boolean externalStorage) {
21439        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21440        int[] uidArr = EmptyArray.INT;
21441
21442        final String[] list = PackageHelper.getSecureContainerList();
21443        if (ArrayUtils.isEmpty(list)) {
21444            Log.i(TAG, "No secure containers found");
21445        } else {
21446            // Process list of secure containers and categorize them
21447            // as active or stale based on their package internal state.
21448
21449            // reader
21450            synchronized (mPackages) {
21451                for (String cid : list) {
21452                    // Leave stages untouched for now; installer service owns them
21453                    if (PackageInstallerService.isStageName(cid)) continue;
21454
21455                    if (DEBUG_SD_INSTALL)
21456                        Log.i(TAG, "Processing container " + cid);
21457                    String pkgName = getAsecPackageName(cid);
21458                    if (pkgName == null) {
21459                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21460                        continue;
21461                    }
21462                    if (DEBUG_SD_INSTALL)
21463                        Log.i(TAG, "Looking for pkg : " + pkgName);
21464
21465                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21466                    if (ps == null) {
21467                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21468                        continue;
21469                    }
21470
21471                    /*
21472                     * Skip packages that are not external if we're unmounting
21473                     * external storage.
21474                     */
21475                    if (externalStorage && !isMounted && !isExternal(ps)) {
21476                        continue;
21477                    }
21478
21479                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21480                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21481                    // The package status is changed only if the code path
21482                    // matches between settings and the container id.
21483                    if (ps.codePathString != null
21484                            && ps.codePathString.startsWith(args.getCodePath())) {
21485                        if (DEBUG_SD_INSTALL) {
21486                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21487                                    + " at code path: " + ps.codePathString);
21488                        }
21489
21490                        // We do have a valid package installed on sdcard
21491                        processCids.put(args, ps.codePathString);
21492                        final int uid = ps.appId;
21493                        if (uid != -1) {
21494                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21495                        }
21496                    } else {
21497                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21498                                + ps.codePathString);
21499                    }
21500                }
21501            }
21502
21503            Arrays.sort(uidArr);
21504        }
21505
21506        // Process packages with valid entries.
21507        if (isMounted) {
21508            if (DEBUG_SD_INSTALL)
21509                Log.i(TAG, "Loading packages");
21510            loadMediaPackages(processCids, uidArr, externalStorage);
21511            startCleaningPackages();
21512            mInstallerService.onSecureContainersAvailable();
21513        } else {
21514            if (DEBUG_SD_INSTALL)
21515                Log.i(TAG, "Unloading packages");
21516            unloadMediaPackages(processCids, uidArr, reportStatus);
21517        }
21518    }
21519
21520    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21521            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21522        final int size = infos.size();
21523        final String[] packageNames = new String[size];
21524        final int[] packageUids = new int[size];
21525        for (int i = 0; i < size; i++) {
21526            final ApplicationInfo info = infos.get(i);
21527            packageNames[i] = info.packageName;
21528            packageUids[i] = info.uid;
21529        }
21530        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21531                finishedReceiver);
21532    }
21533
21534    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21535            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21536        sendResourcesChangedBroadcast(mediaStatus, replacing,
21537                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21538    }
21539
21540    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21541            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21542        int size = pkgList.length;
21543        if (size > 0) {
21544            // Send broadcasts here
21545            Bundle extras = new Bundle();
21546            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21547            if (uidArr != null) {
21548                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21549            }
21550            if (replacing) {
21551                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21552            }
21553            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21554                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21555            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21556        }
21557    }
21558
21559   /*
21560     * Look at potentially valid container ids from processCids If package
21561     * information doesn't match the one on record or package scanning fails,
21562     * the cid is added to list of removeCids. We currently don't delete stale
21563     * containers.
21564     */
21565    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21566            boolean externalStorage) {
21567        ArrayList<String> pkgList = new ArrayList<String>();
21568        Set<AsecInstallArgs> keys = processCids.keySet();
21569
21570        for (AsecInstallArgs args : keys) {
21571            String codePath = processCids.get(args);
21572            if (DEBUG_SD_INSTALL)
21573                Log.i(TAG, "Loading container : " + args.cid);
21574            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21575            try {
21576                // Make sure there are no container errors first.
21577                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21578                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21579                            + " when installing from sdcard");
21580                    continue;
21581                }
21582                // Check code path here.
21583                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21584                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21585                            + " does not match one in settings " + codePath);
21586                    continue;
21587                }
21588                // Parse package
21589                int parseFlags = mDefParseFlags;
21590                if (args.isExternalAsec()) {
21591                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21592                }
21593                if (args.isFwdLocked()) {
21594                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21595                }
21596
21597                synchronized (mInstallLock) {
21598                    PackageParser.Package pkg = null;
21599                    try {
21600                        // Sadly we don't know the package name yet to freeze it
21601                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21602                                SCAN_IGNORE_FROZEN, 0, null);
21603                    } catch (PackageManagerException e) {
21604                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21605                    }
21606                    // Scan the package
21607                    if (pkg != null) {
21608                        /*
21609                         * TODO why is the lock being held? doPostInstall is
21610                         * called in other places without the lock. This needs
21611                         * to be straightened out.
21612                         */
21613                        // writer
21614                        synchronized (mPackages) {
21615                            retCode = PackageManager.INSTALL_SUCCEEDED;
21616                            pkgList.add(pkg.packageName);
21617                            // Post process args
21618                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21619                                    pkg.applicationInfo.uid);
21620                        }
21621                    } else {
21622                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21623                    }
21624                }
21625
21626            } finally {
21627                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21628                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21629                }
21630            }
21631        }
21632        // writer
21633        synchronized (mPackages) {
21634            // If the platform SDK has changed since the last time we booted,
21635            // we need to re-grant app permission to catch any new ones that
21636            // appear. This is really a hack, and means that apps can in some
21637            // cases get permissions that the user didn't initially explicitly
21638            // allow... it would be nice to have some better way to handle
21639            // this situation.
21640            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21641                    : mSettings.getInternalVersion();
21642            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21643                    : StorageManager.UUID_PRIVATE_INTERNAL;
21644
21645            int updateFlags = UPDATE_PERMISSIONS_ALL;
21646            if (ver.sdkVersion != mSdkVersion) {
21647                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21648                        + mSdkVersion + "; regranting permissions for external");
21649                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21650            }
21651            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21652
21653            // Yay, everything is now upgraded
21654            ver.forceCurrent();
21655
21656            // can downgrade to reader
21657            // Persist settings
21658            mSettings.writeLPr();
21659        }
21660        // Send a broadcast to let everyone know we are done processing
21661        if (pkgList.size() > 0) {
21662            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21663        }
21664    }
21665
21666   /*
21667     * Utility method to unload a list of specified containers
21668     */
21669    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21670        // Just unmount all valid containers.
21671        for (AsecInstallArgs arg : cidArgs) {
21672            synchronized (mInstallLock) {
21673                arg.doPostDeleteLI(false);
21674           }
21675       }
21676   }
21677
21678    /*
21679     * Unload packages mounted on external media. This involves deleting package
21680     * data from internal structures, sending broadcasts about disabled packages,
21681     * gc'ing to free up references, unmounting all secure containers
21682     * corresponding to packages on external media, and posting a
21683     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21684     * that we always have to post this message if status has been requested no
21685     * matter what.
21686     */
21687    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21688            final boolean reportStatus) {
21689        if (DEBUG_SD_INSTALL)
21690            Log.i(TAG, "unloading media packages");
21691        ArrayList<String> pkgList = new ArrayList<String>();
21692        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21693        final Set<AsecInstallArgs> keys = processCids.keySet();
21694        for (AsecInstallArgs args : keys) {
21695            String pkgName = args.getPackageName();
21696            if (DEBUG_SD_INSTALL)
21697                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21698            // Delete package internally
21699            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21700            synchronized (mInstallLock) {
21701                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21702                final boolean res;
21703                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21704                        "unloadMediaPackages")) {
21705                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21706                            null);
21707                }
21708                if (res) {
21709                    pkgList.add(pkgName);
21710                } else {
21711                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21712                    failedList.add(args);
21713                }
21714            }
21715        }
21716
21717        // reader
21718        synchronized (mPackages) {
21719            // We didn't update the settings after removing each package;
21720            // write them now for all packages.
21721            mSettings.writeLPr();
21722        }
21723
21724        // We have to absolutely send UPDATED_MEDIA_STATUS only
21725        // after confirming that all the receivers processed the ordered
21726        // broadcast when packages get disabled, force a gc to clean things up.
21727        // and unload all the containers.
21728        if (pkgList.size() > 0) {
21729            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21730                    new IIntentReceiver.Stub() {
21731                public void performReceive(Intent intent, int resultCode, String data,
21732                        Bundle extras, boolean ordered, boolean sticky,
21733                        int sendingUser) throws RemoteException {
21734                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21735                            reportStatus ? 1 : 0, 1, keys);
21736                    mHandler.sendMessage(msg);
21737                }
21738            });
21739        } else {
21740            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21741                    keys);
21742            mHandler.sendMessage(msg);
21743        }
21744    }
21745
21746    private void loadPrivatePackages(final VolumeInfo vol) {
21747        mHandler.post(new Runnable() {
21748            @Override
21749            public void run() {
21750                loadPrivatePackagesInner(vol);
21751            }
21752        });
21753    }
21754
21755    private void loadPrivatePackagesInner(VolumeInfo vol) {
21756        final String volumeUuid = vol.fsUuid;
21757        if (TextUtils.isEmpty(volumeUuid)) {
21758            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21759            return;
21760        }
21761
21762        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21763        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21764        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21765
21766        final VersionInfo ver;
21767        final List<PackageSetting> packages;
21768        synchronized (mPackages) {
21769            ver = mSettings.findOrCreateVersion(volumeUuid);
21770            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21771        }
21772
21773        for (PackageSetting ps : packages) {
21774            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21775            synchronized (mInstallLock) {
21776                final PackageParser.Package pkg;
21777                try {
21778                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21779                    loaded.add(pkg.applicationInfo);
21780
21781                } catch (PackageManagerException e) {
21782                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21783                }
21784
21785                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21786                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21787                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21788                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21789                }
21790            }
21791        }
21792
21793        // Reconcile app data for all started/unlocked users
21794        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21795        final UserManager um = mContext.getSystemService(UserManager.class);
21796        UserManagerInternal umInternal = getUserManagerInternal();
21797        for (UserInfo user : um.getUsers()) {
21798            final int flags;
21799            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21800                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21801            } else if (umInternal.isUserRunning(user.id)) {
21802                flags = StorageManager.FLAG_STORAGE_DE;
21803            } else {
21804                continue;
21805            }
21806
21807            try {
21808                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21809                synchronized (mInstallLock) {
21810                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21811                }
21812            } catch (IllegalStateException e) {
21813                // Device was probably ejected, and we'll process that event momentarily
21814                Slog.w(TAG, "Failed to prepare storage: " + e);
21815            }
21816        }
21817
21818        synchronized (mPackages) {
21819            int updateFlags = UPDATE_PERMISSIONS_ALL;
21820            if (ver.sdkVersion != mSdkVersion) {
21821                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21822                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21823                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21824            }
21825            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21826
21827            // Yay, everything is now upgraded
21828            ver.forceCurrent();
21829
21830            mSettings.writeLPr();
21831        }
21832
21833        for (PackageFreezer freezer : freezers) {
21834            freezer.close();
21835        }
21836
21837        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21838        sendResourcesChangedBroadcast(true, false, loaded, null);
21839    }
21840
21841    private void unloadPrivatePackages(final VolumeInfo vol) {
21842        mHandler.post(new Runnable() {
21843            @Override
21844            public void run() {
21845                unloadPrivatePackagesInner(vol);
21846            }
21847        });
21848    }
21849
21850    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21851        final String volumeUuid = vol.fsUuid;
21852        if (TextUtils.isEmpty(volumeUuid)) {
21853            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21854            return;
21855        }
21856
21857        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21858        synchronized (mInstallLock) {
21859        synchronized (mPackages) {
21860            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21861            for (PackageSetting ps : packages) {
21862                if (ps.pkg == null) continue;
21863
21864                final ApplicationInfo info = ps.pkg.applicationInfo;
21865                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21866                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21867
21868                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21869                        "unloadPrivatePackagesInner")) {
21870                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21871                            false, null)) {
21872                        unloaded.add(info);
21873                    } else {
21874                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21875                    }
21876                }
21877
21878                // Try very hard to release any references to this package
21879                // so we don't risk the system server being killed due to
21880                // open FDs
21881                AttributeCache.instance().removePackage(ps.name);
21882            }
21883
21884            mSettings.writeLPr();
21885        }
21886        }
21887
21888        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21889        sendResourcesChangedBroadcast(false, false, unloaded, null);
21890
21891        // Try very hard to release any references to this path so we don't risk
21892        // the system server being killed due to open FDs
21893        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21894
21895        for (int i = 0; i < 3; i++) {
21896            System.gc();
21897            System.runFinalization();
21898        }
21899    }
21900
21901    private void assertPackageKnown(String volumeUuid, String packageName)
21902            throws PackageManagerException {
21903        synchronized (mPackages) {
21904            // Normalize package name to handle renamed packages
21905            packageName = normalizePackageNameLPr(packageName);
21906
21907            final PackageSetting ps = mSettings.mPackages.get(packageName);
21908            if (ps == null) {
21909                throw new PackageManagerException("Package " + packageName + " is unknown");
21910            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21911                throw new PackageManagerException(
21912                        "Package " + packageName + " found on unknown volume " + volumeUuid
21913                                + "; expected volume " + ps.volumeUuid);
21914            }
21915        }
21916    }
21917
21918    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21919            throws PackageManagerException {
21920        synchronized (mPackages) {
21921            // Normalize package name to handle renamed packages
21922            packageName = normalizePackageNameLPr(packageName);
21923
21924            final PackageSetting ps = mSettings.mPackages.get(packageName);
21925            if (ps == null) {
21926                throw new PackageManagerException("Package " + packageName + " is unknown");
21927            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21928                throw new PackageManagerException(
21929                        "Package " + packageName + " found on unknown volume " + volumeUuid
21930                                + "; expected volume " + ps.volumeUuid);
21931            } else if (!ps.getInstalled(userId)) {
21932                throw new PackageManagerException(
21933                        "Package " + packageName + " not installed for user " + userId);
21934            }
21935        }
21936    }
21937
21938    private List<String> collectAbsoluteCodePaths() {
21939        synchronized (mPackages) {
21940            List<String> codePaths = new ArrayList<>();
21941            final int packageCount = mSettings.mPackages.size();
21942            for (int i = 0; i < packageCount; i++) {
21943                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21944                codePaths.add(ps.codePath.getAbsolutePath());
21945            }
21946            return codePaths;
21947        }
21948    }
21949
21950    /**
21951     * Examine all apps present on given mounted volume, and destroy apps that
21952     * aren't expected, either due to uninstallation or reinstallation on
21953     * another volume.
21954     */
21955    private void reconcileApps(String volumeUuid) {
21956        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21957        List<File> filesToDelete = null;
21958
21959        final File[] files = FileUtils.listFilesOrEmpty(
21960                Environment.getDataAppDirectory(volumeUuid));
21961        for (File file : files) {
21962            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21963                    && !PackageInstallerService.isStageName(file.getName());
21964            if (!isPackage) {
21965                // Ignore entries which are not packages
21966                continue;
21967            }
21968
21969            String absolutePath = file.getAbsolutePath();
21970
21971            boolean pathValid = false;
21972            final int absoluteCodePathCount = absoluteCodePaths.size();
21973            for (int i = 0; i < absoluteCodePathCount; i++) {
21974                String absoluteCodePath = absoluteCodePaths.get(i);
21975                if (absolutePath.startsWith(absoluteCodePath)) {
21976                    pathValid = true;
21977                    break;
21978                }
21979            }
21980
21981            if (!pathValid) {
21982                if (filesToDelete == null) {
21983                    filesToDelete = new ArrayList<>();
21984                }
21985                filesToDelete.add(file);
21986            }
21987        }
21988
21989        if (filesToDelete != null) {
21990            final int fileToDeleteCount = filesToDelete.size();
21991            for (int i = 0; i < fileToDeleteCount; i++) {
21992                File fileToDelete = filesToDelete.get(i);
21993                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21994                synchronized (mInstallLock) {
21995                    removeCodePathLI(fileToDelete);
21996                }
21997            }
21998        }
21999    }
22000
22001    /**
22002     * Reconcile all app data for the given user.
22003     * <p>
22004     * Verifies that directories exist and that ownership and labeling is
22005     * correct for all installed apps on all mounted volumes.
22006     */
22007    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22008        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22009        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22010            final String volumeUuid = vol.getFsUuid();
22011            synchronized (mInstallLock) {
22012                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22013            }
22014        }
22015    }
22016
22017    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22018            boolean migrateAppData) {
22019        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22020    }
22021
22022    /**
22023     * Reconcile all app data on given mounted volume.
22024     * <p>
22025     * Destroys app data that isn't expected, either due to uninstallation or
22026     * reinstallation on another volume.
22027     * <p>
22028     * Verifies that directories exist and that ownership and labeling is
22029     * correct for all installed apps.
22030     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22031     */
22032    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22033            boolean migrateAppData, boolean onlyCoreApps) {
22034        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22035                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22036        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22037
22038        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22039        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22040
22041        // First look for stale data that doesn't belong, and check if things
22042        // have changed since we did our last restorecon
22043        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22044            if (StorageManager.isFileEncryptedNativeOrEmulated()
22045                    && !StorageManager.isUserKeyUnlocked(userId)) {
22046                throw new RuntimeException(
22047                        "Yikes, someone asked us to reconcile CE storage while " + userId
22048                                + " was still locked; this would have caused massive data loss!");
22049            }
22050
22051            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22052            for (File file : files) {
22053                final String packageName = file.getName();
22054                try {
22055                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22056                } catch (PackageManagerException e) {
22057                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22058                    try {
22059                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22060                                StorageManager.FLAG_STORAGE_CE, 0);
22061                    } catch (InstallerException e2) {
22062                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22063                    }
22064                }
22065            }
22066        }
22067        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22068            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22069            for (File file : files) {
22070                final String packageName = file.getName();
22071                try {
22072                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22073                } catch (PackageManagerException e) {
22074                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22075                    try {
22076                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22077                                StorageManager.FLAG_STORAGE_DE, 0);
22078                    } catch (InstallerException e2) {
22079                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22080                    }
22081                }
22082            }
22083        }
22084
22085        // Ensure that data directories are ready to roll for all packages
22086        // installed for this volume and user
22087        final List<PackageSetting> packages;
22088        synchronized (mPackages) {
22089            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22090        }
22091        int preparedCount = 0;
22092        for (PackageSetting ps : packages) {
22093            final String packageName = ps.name;
22094            if (ps.pkg == null) {
22095                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22096                // TODO: might be due to legacy ASEC apps; we should circle back
22097                // and reconcile again once they're scanned
22098                continue;
22099            }
22100            // Skip non-core apps if requested
22101            if (onlyCoreApps && !ps.pkg.coreApp) {
22102                result.add(packageName);
22103                continue;
22104            }
22105
22106            if (ps.getInstalled(userId)) {
22107                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22108                preparedCount++;
22109            }
22110        }
22111
22112        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22113        return result;
22114    }
22115
22116    /**
22117     * Prepare app data for the given app just after it was installed or
22118     * upgraded. This method carefully only touches users that it's installed
22119     * for, and it forces a restorecon to handle any seinfo changes.
22120     * <p>
22121     * Verifies that directories exist and that ownership and labeling is
22122     * correct for all installed apps. If there is an ownership mismatch, it
22123     * will try recovering system apps by wiping data; third-party app data is
22124     * left intact.
22125     * <p>
22126     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22127     */
22128    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22129        final PackageSetting ps;
22130        synchronized (mPackages) {
22131            ps = mSettings.mPackages.get(pkg.packageName);
22132            mSettings.writeKernelMappingLPr(ps);
22133        }
22134
22135        final UserManager um = mContext.getSystemService(UserManager.class);
22136        UserManagerInternal umInternal = getUserManagerInternal();
22137        for (UserInfo user : um.getUsers()) {
22138            final int flags;
22139            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22140                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22141            } else if (umInternal.isUserRunning(user.id)) {
22142                flags = StorageManager.FLAG_STORAGE_DE;
22143            } else {
22144                continue;
22145            }
22146
22147            if (ps.getInstalled(user.id)) {
22148                // TODO: when user data is locked, mark that we're still dirty
22149                prepareAppDataLIF(pkg, user.id, flags);
22150            }
22151        }
22152    }
22153
22154    /**
22155     * Prepare app data for the given app.
22156     * <p>
22157     * Verifies that directories exist and that ownership and labeling is
22158     * correct for all installed apps. If there is an ownership mismatch, this
22159     * will try recovering system apps by wiping data; third-party app data is
22160     * left intact.
22161     */
22162    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22163        if (pkg == null) {
22164            Slog.wtf(TAG, "Package was null!", new Throwable());
22165            return;
22166        }
22167        prepareAppDataLeafLIF(pkg, userId, flags);
22168        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22169        for (int i = 0; i < childCount; i++) {
22170            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22171        }
22172    }
22173
22174    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22175            boolean maybeMigrateAppData) {
22176        prepareAppDataLIF(pkg, userId, flags);
22177
22178        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22179            // We may have just shuffled around app data directories, so
22180            // prepare them one more time
22181            prepareAppDataLIF(pkg, userId, flags);
22182        }
22183    }
22184
22185    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22186        if (DEBUG_APP_DATA) {
22187            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22188                    + Integer.toHexString(flags));
22189        }
22190
22191        final String volumeUuid = pkg.volumeUuid;
22192        final String packageName = pkg.packageName;
22193        final ApplicationInfo app = pkg.applicationInfo;
22194        final int appId = UserHandle.getAppId(app.uid);
22195
22196        Preconditions.checkNotNull(app.seInfo);
22197
22198        long ceDataInode = -1;
22199        try {
22200            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22201                    appId, app.seInfo, app.targetSdkVersion);
22202        } catch (InstallerException e) {
22203            if (app.isSystemApp()) {
22204                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22205                        + ", but trying to recover: " + e);
22206                destroyAppDataLeafLIF(pkg, userId, flags);
22207                try {
22208                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22209                            appId, app.seInfo, app.targetSdkVersion);
22210                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22211                } catch (InstallerException e2) {
22212                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22213                }
22214            } else {
22215                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22216            }
22217        }
22218
22219        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22220            // TODO: mark this structure as dirty so we persist it!
22221            synchronized (mPackages) {
22222                final PackageSetting ps = mSettings.mPackages.get(packageName);
22223                if (ps != null) {
22224                    ps.setCeDataInode(ceDataInode, userId);
22225                }
22226            }
22227        }
22228
22229        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22230    }
22231
22232    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22233        if (pkg == null) {
22234            Slog.wtf(TAG, "Package was null!", new Throwable());
22235            return;
22236        }
22237        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22238        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22239        for (int i = 0; i < childCount; i++) {
22240            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22241        }
22242    }
22243
22244    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22245        final String volumeUuid = pkg.volumeUuid;
22246        final String packageName = pkg.packageName;
22247        final ApplicationInfo app = pkg.applicationInfo;
22248
22249        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22250            // Create a native library symlink only if we have native libraries
22251            // and if the native libraries are 32 bit libraries. We do not provide
22252            // this symlink for 64 bit libraries.
22253            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22254                final String nativeLibPath = app.nativeLibraryDir;
22255                try {
22256                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22257                            nativeLibPath, userId);
22258                } catch (InstallerException e) {
22259                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22260                }
22261            }
22262        }
22263    }
22264
22265    /**
22266     * For system apps on non-FBE devices, this method migrates any existing
22267     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22268     * requested by the app.
22269     */
22270    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22271        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22272                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22273            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22274                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22275            try {
22276                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22277                        storageTarget);
22278            } catch (InstallerException e) {
22279                logCriticalInfo(Log.WARN,
22280                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22281            }
22282            return true;
22283        } else {
22284            return false;
22285        }
22286    }
22287
22288    public PackageFreezer freezePackage(String packageName, String killReason) {
22289        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22290    }
22291
22292    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22293        return new PackageFreezer(packageName, userId, killReason);
22294    }
22295
22296    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22297            String killReason) {
22298        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22299    }
22300
22301    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22302            String killReason) {
22303        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22304            return new PackageFreezer();
22305        } else {
22306            return freezePackage(packageName, userId, killReason);
22307        }
22308    }
22309
22310    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22311            String killReason) {
22312        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22313    }
22314
22315    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22316            String killReason) {
22317        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22318            return new PackageFreezer();
22319        } else {
22320            return freezePackage(packageName, userId, killReason);
22321        }
22322    }
22323
22324    /**
22325     * Class that freezes and kills the given package upon creation, and
22326     * unfreezes it upon closing. This is typically used when doing surgery on
22327     * app code/data to prevent the app from running while you're working.
22328     */
22329    private class PackageFreezer implements AutoCloseable {
22330        private final String mPackageName;
22331        private final PackageFreezer[] mChildren;
22332
22333        private final boolean mWeFroze;
22334
22335        private final AtomicBoolean mClosed = new AtomicBoolean();
22336        private final CloseGuard mCloseGuard = CloseGuard.get();
22337
22338        /**
22339         * Create and return a stub freezer that doesn't actually do anything,
22340         * typically used when someone requested
22341         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22342         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22343         */
22344        public PackageFreezer() {
22345            mPackageName = null;
22346            mChildren = null;
22347            mWeFroze = false;
22348            mCloseGuard.open("close");
22349        }
22350
22351        public PackageFreezer(String packageName, int userId, String killReason) {
22352            synchronized (mPackages) {
22353                mPackageName = packageName;
22354                mWeFroze = mFrozenPackages.add(mPackageName);
22355
22356                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22357                if (ps != null) {
22358                    killApplication(ps.name, ps.appId, userId, killReason);
22359                }
22360
22361                final PackageParser.Package p = mPackages.get(packageName);
22362                if (p != null && p.childPackages != null) {
22363                    final int N = p.childPackages.size();
22364                    mChildren = new PackageFreezer[N];
22365                    for (int i = 0; i < N; i++) {
22366                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22367                                userId, killReason);
22368                    }
22369                } else {
22370                    mChildren = null;
22371                }
22372            }
22373            mCloseGuard.open("close");
22374        }
22375
22376        @Override
22377        protected void finalize() throws Throwable {
22378            try {
22379                mCloseGuard.warnIfOpen();
22380                close();
22381            } finally {
22382                super.finalize();
22383            }
22384        }
22385
22386        @Override
22387        public void close() {
22388            mCloseGuard.close();
22389            if (mClosed.compareAndSet(false, true)) {
22390                synchronized (mPackages) {
22391                    if (mWeFroze) {
22392                        mFrozenPackages.remove(mPackageName);
22393                    }
22394
22395                    if (mChildren != null) {
22396                        for (PackageFreezer freezer : mChildren) {
22397                            freezer.close();
22398                        }
22399                    }
22400                }
22401            }
22402        }
22403    }
22404
22405    /**
22406     * Verify that given package is currently frozen.
22407     */
22408    private void checkPackageFrozen(String packageName) {
22409        synchronized (mPackages) {
22410            if (!mFrozenPackages.contains(packageName)) {
22411                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22412            }
22413        }
22414    }
22415
22416    @Override
22417    public int movePackage(final String packageName, final String volumeUuid) {
22418        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22419
22420        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22421        final int moveId = mNextMoveId.getAndIncrement();
22422        mHandler.post(new Runnable() {
22423            @Override
22424            public void run() {
22425                try {
22426                    movePackageInternal(packageName, volumeUuid, moveId, user);
22427                } catch (PackageManagerException e) {
22428                    Slog.w(TAG, "Failed to move " + packageName, e);
22429                    mMoveCallbacks.notifyStatusChanged(moveId,
22430                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22431                }
22432            }
22433        });
22434        return moveId;
22435    }
22436
22437    private void movePackageInternal(final String packageName, final String volumeUuid,
22438            final int moveId, UserHandle user) throws PackageManagerException {
22439        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22440        final PackageManager pm = mContext.getPackageManager();
22441
22442        final boolean currentAsec;
22443        final String currentVolumeUuid;
22444        final File codeFile;
22445        final String installerPackageName;
22446        final String packageAbiOverride;
22447        final int appId;
22448        final String seinfo;
22449        final String label;
22450        final int targetSdkVersion;
22451        final PackageFreezer freezer;
22452        final int[] installedUserIds;
22453
22454        // reader
22455        synchronized (mPackages) {
22456            final PackageParser.Package pkg = mPackages.get(packageName);
22457            final PackageSetting ps = mSettings.mPackages.get(packageName);
22458            if (pkg == null || ps == null) {
22459                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22460            }
22461
22462            if (pkg.applicationInfo.isSystemApp()) {
22463                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22464                        "Cannot move system application");
22465            }
22466
22467            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22468            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22469                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22470            if (isInternalStorage && !allow3rdPartyOnInternal) {
22471                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22472                        "3rd party apps are not allowed on internal storage");
22473            }
22474
22475            if (pkg.applicationInfo.isExternalAsec()) {
22476                currentAsec = true;
22477                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22478            } else if (pkg.applicationInfo.isForwardLocked()) {
22479                currentAsec = true;
22480                currentVolumeUuid = "forward_locked";
22481            } else {
22482                currentAsec = false;
22483                currentVolumeUuid = ps.volumeUuid;
22484
22485                final File probe = new File(pkg.codePath);
22486                final File probeOat = new File(probe, "oat");
22487                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22488                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22489                            "Move only supported for modern cluster style installs");
22490                }
22491            }
22492
22493            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22494                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22495                        "Package already moved to " + volumeUuid);
22496            }
22497            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22498                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22499                        "Device admin cannot be moved");
22500            }
22501
22502            if (mFrozenPackages.contains(packageName)) {
22503                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22504                        "Failed to move already frozen package");
22505            }
22506
22507            codeFile = new File(pkg.codePath);
22508            installerPackageName = ps.installerPackageName;
22509            packageAbiOverride = ps.cpuAbiOverrideString;
22510            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22511            seinfo = pkg.applicationInfo.seInfo;
22512            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22513            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22514            freezer = freezePackage(packageName, "movePackageInternal");
22515            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22516        }
22517
22518        final Bundle extras = new Bundle();
22519        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22520        extras.putString(Intent.EXTRA_TITLE, label);
22521        mMoveCallbacks.notifyCreated(moveId, extras);
22522
22523        int installFlags;
22524        final boolean moveCompleteApp;
22525        final File measurePath;
22526
22527        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22528            installFlags = INSTALL_INTERNAL;
22529            moveCompleteApp = !currentAsec;
22530            measurePath = Environment.getDataAppDirectory(volumeUuid);
22531        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22532            installFlags = INSTALL_EXTERNAL;
22533            moveCompleteApp = false;
22534            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22535        } else {
22536            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22537            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22538                    || !volume.isMountedWritable()) {
22539                freezer.close();
22540                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22541                        "Move location not mounted private volume");
22542            }
22543
22544            Preconditions.checkState(!currentAsec);
22545
22546            installFlags = INSTALL_INTERNAL;
22547            moveCompleteApp = true;
22548            measurePath = Environment.getDataAppDirectory(volumeUuid);
22549        }
22550
22551        final PackageStats stats = new PackageStats(null, -1);
22552        synchronized (mInstaller) {
22553            for (int userId : installedUserIds) {
22554                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22555                    freezer.close();
22556                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22557                            "Failed to measure package size");
22558                }
22559            }
22560        }
22561
22562        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22563                + stats.dataSize);
22564
22565        final long startFreeBytes = measurePath.getUsableSpace();
22566        final long sizeBytes;
22567        if (moveCompleteApp) {
22568            sizeBytes = stats.codeSize + stats.dataSize;
22569        } else {
22570            sizeBytes = stats.codeSize;
22571        }
22572
22573        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22574            freezer.close();
22575            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22576                    "Not enough free space to move");
22577        }
22578
22579        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22580
22581        final CountDownLatch installedLatch = new CountDownLatch(1);
22582        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22583            @Override
22584            public void onUserActionRequired(Intent intent) throws RemoteException {
22585                throw new IllegalStateException();
22586            }
22587
22588            @Override
22589            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22590                    Bundle extras) throws RemoteException {
22591                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22592                        + PackageManager.installStatusToString(returnCode, msg));
22593
22594                installedLatch.countDown();
22595                freezer.close();
22596
22597                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22598                switch (status) {
22599                    case PackageInstaller.STATUS_SUCCESS:
22600                        mMoveCallbacks.notifyStatusChanged(moveId,
22601                                PackageManager.MOVE_SUCCEEDED);
22602                        break;
22603                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22604                        mMoveCallbacks.notifyStatusChanged(moveId,
22605                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22606                        break;
22607                    default:
22608                        mMoveCallbacks.notifyStatusChanged(moveId,
22609                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22610                        break;
22611                }
22612            }
22613        };
22614
22615        final MoveInfo move;
22616        if (moveCompleteApp) {
22617            // Kick off a thread to report progress estimates
22618            new Thread() {
22619                @Override
22620                public void run() {
22621                    while (true) {
22622                        try {
22623                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22624                                break;
22625                            }
22626                        } catch (InterruptedException ignored) {
22627                        }
22628
22629                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22630                        final int progress = 10 + (int) MathUtils.constrain(
22631                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22632                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22633                    }
22634                }
22635            }.start();
22636
22637            final String dataAppName = codeFile.getName();
22638            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22639                    dataAppName, appId, seinfo, targetSdkVersion);
22640        } else {
22641            move = null;
22642        }
22643
22644        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22645
22646        final Message msg = mHandler.obtainMessage(INIT_COPY);
22647        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22648        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22649                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22650                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22651                PackageManager.INSTALL_REASON_UNKNOWN);
22652        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22653        msg.obj = params;
22654
22655        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22656                System.identityHashCode(msg.obj));
22657        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22658                System.identityHashCode(msg.obj));
22659
22660        mHandler.sendMessage(msg);
22661    }
22662
22663    @Override
22664    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22665        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22666
22667        final int realMoveId = mNextMoveId.getAndIncrement();
22668        final Bundle extras = new Bundle();
22669        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22670        mMoveCallbacks.notifyCreated(realMoveId, extras);
22671
22672        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22673            @Override
22674            public void onCreated(int moveId, Bundle extras) {
22675                // Ignored
22676            }
22677
22678            @Override
22679            public void onStatusChanged(int moveId, int status, long estMillis) {
22680                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22681            }
22682        };
22683
22684        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22685        storage.setPrimaryStorageUuid(volumeUuid, callback);
22686        return realMoveId;
22687    }
22688
22689    @Override
22690    public int getMoveStatus(int moveId) {
22691        mContext.enforceCallingOrSelfPermission(
22692                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22693        return mMoveCallbacks.mLastStatus.get(moveId);
22694    }
22695
22696    @Override
22697    public void registerMoveCallback(IPackageMoveObserver callback) {
22698        mContext.enforceCallingOrSelfPermission(
22699                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22700        mMoveCallbacks.register(callback);
22701    }
22702
22703    @Override
22704    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22705        mContext.enforceCallingOrSelfPermission(
22706                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22707        mMoveCallbacks.unregister(callback);
22708    }
22709
22710    @Override
22711    public boolean setInstallLocation(int loc) {
22712        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22713                null);
22714        if (getInstallLocation() == loc) {
22715            return true;
22716        }
22717        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22718                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22719            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22720                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22721            return true;
22722        }
22723        return false;
22724   }
22725
22726    @Override
22727    public int getInstallLocation() {
22728        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22729                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22730                PackageHelper.APP_INSTALL_AUTO);
22731    }
22732
22733    /** Called by UserManagerService */
22734    void cleanUpUser(UserManagerService userManager, int userHandle) {
22735        synchronized (mPackages) {
22736            mDirtyUsers.remove(userHandle);
22737            mUserNeedsBadging.delete(userHandle);
22738            mSettings.removeUserLPw(userHandle);
22739            mPendingBroadcasts.remove(userHandle);
22740            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22741            removeUnusedPackagesLPw(userManager, userHandle);
22742        }
22743    }
22744
22745    /**
22746     * We're removing userHandle and would like to remove any downloaded packages
22747     * that are no longer in use by any other user.
22748     * @param userHandle the user being removed
22749     */
22750    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22751        final boolean DEBUG_CLEAN_APKS = false;
22752        int [] users = userManager.getUserIds();
22753        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22754        while (psit.hasNext()) {
22755            PackageSetting ps = psit.next();
22756            if (ps.pkg == null) {
22757                continue;
22758            }
22759            final String packageName = ps.pkg.packageName;
22760            // Skip over if system app
22761            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22762                continue;
22763            }
22764            if (DEBUG_CLEAN_APKS) {
22765                Slog.i(TAG, "Checking package " + packageName);
22766            }
22767            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22768            if (keep) {
22769                if (DEBUG_CLEAN_APKS) {
22770                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22771                }
22772            } else {
22773                for (int i = 0; i < users.length; i++) {
22774                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22775                        keep = true;
22776                        if (DEBUG_CLEAN_APKS) {
22777                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22778                                    + users[i]);
22779                        }
22780                        break;
22781                    }
22782                }
22783            }
22784            if (!keep) {
22785                if (DEBUG_CLEAN_APKS) {
22786                    Slog.i(TAG, "  Removing package " + packageName);
22787                }
22788                mHandler.post(new Runnable() {
22789                    public void run() {
22790                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22791                                userHandle, 0);
22792                    } //end run
22793                });
22794            }
22795        }
22796    }
22797
22798    /** Called by UserManagerService */
22799    void createNewUser(int userId, String[] disallowedPackages) {
22800        synchronized (mInstallLock) {
22801            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22802        }
22803        synchronized (mPackages) {
22804            scheduleWritePackageRestrictionsLocked(userId);
22805            scheduleWritePackageListLocked(userId);
22806            applyFactoryDefaultBrowserLPw(userId);
22807            primeDomainVerificationsLPw(userId);
22808        }
22809    }
22810
22811    void onNewUserCreated(final int userId) {
22812        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22813        // If permission review for legacy apps is required, we represent
22814        // dagerous permissions for such apps as always granted runtime
22815        // permissions to keep per user flag state whether review is needed.
22816        // Hence, if a new user is added we have to propagate dangerous
22817        // permission grants for these legacy apps.
22818        if (mPermissionReviewRequired) {
22819            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22820                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22821        }
22822    }
22823
22824    @Override
22825    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22826        mContext.enforceCallingOrSelfPermission(
22827                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22828                "Only package verification agents can read the verifier device identity");
22829
22830        synchronized (mPackages) {
22831            return mSettings.getVerifierDeviceIdentityLPw();
22832        }
22833    }
22834
22835    @Override
22836    public void setPermissionEnforced(String permission, boolean enforced) {
22837        // TODO: Now that we no longer change GID for storage, this should to away.
22838        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22839                "setPermissionEnforced");
22840        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22841            synchronized (mPackages) {
22842                if (mSettings.mReadExternalStorageEnforced == null
22843                        || mSettings.mReadExternalStorageEnforced != enforced) {
22844                    mSettings.mReadExternalStorageEnforced = enforced;
22845                    mSettings.writeLPr();
22846                }
22847            }
22848            // kill any non-foreground processes so we restart them and
22849            // grant/revoke the GID.
22850            final IActivityManager am = ActivityManager.getService();
22851            if (am != null) {
22852                final long token = Binder.clearCallingIdentity();
22853                try {
22854                    am.killProcessesBelowForeground("setPermissionEnforcement");
22855                } catch (RemoteException e) {
22856                } finally {
22857                    Binder.restoreCallingIdentity(token);
22858                }
22859            }
22860        } else {
22861            throw new IllegalArgumentException("No selective enforcement for " + permission);
22862        }
22863    }
22864
22865    @Override
22866    @Deprecated
22867    public boolean isPermissionEnforced(String permission) {
22868        return true;
22869    }
22870
22871    @Override
22872    public boolean isStorageLow() {
22873        final long token = Binder.clearCallingIdentity();
22874        try {
22875            final DeviceStorageMonitorInternal
22876                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22877            if (dsm != null) {
22878                return dsm.isMemoryLow();
22879            } else {
22880                return false;
22881            }
22882        } finally {
22883            Binder.restoreCallingIdentity(token);
22884        }
22885    }
22886
22887    @Override
22888    public IPackageInstaller getPackageInstaller() {
22889        return mInstallerService;
22890    }
22891
22892    private boolean userNeedsBadging(int userId) {
22893        int index = mUserNeedsBadging.indexOfKey(userId);
22894        if (index < 0) {
22895            final UserInfo userInfo;
22896            final long token = Binder.clearCallingIdentity();
22897            try {
22898                userInfo = sUserManager.getUserInfo(userId);
22899            } finally {
22900                Binder.restoreCallingIdentity(token);
22901            }
22902            final boolean b;
22903            if (userInfo != null && userInfo.isManagedProfile()) {
22904                b = true;
22905            } else {
22906                b = false;
22907            }
22908            mUserNeedsBadging.put(userId, b);
22909            return b;
22910        }
22911        return mUserNeedsBadging.valueAt(index);
22912    }
22913
22914    @Override
22915    public KeySet getKeySetByAlias(String packageName, String alias) {
22916        if (packageName == null || alias == null) {
22917            return null;
22918        }
22919        synchronized(mPackages) {
22920            final PackageParser.Package pkg = mPackages.get(packageName);
22921            if (pkg == null) {
22922                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22923                throw new IllegalArgumentException("Unknown package: " + packageName);
22924            }
22925            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22926            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22927        }
22928    }
22929
22930    @Override
22931    public KeySet getSigningKeySet(String packageName) {
22932        if (packageName == null) {
22933            return null;
22934        }
22935        synchronized(mPackages) {
22936            final PackageParser.Package pkg = mPackages.get(packageName);
22937            if (pkg == null) {
22938                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22939                throw new IllegalArgumentException("Unknown package: " + packageName);
22940            }
22941            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22942                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22943                throw new SecurityException("May not access signing KeySet of other apps.");
22944            }
22945            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22946            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22947        }
22948    }
22949
22950    @Override
22951    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22952        if (packageName == null || ks == null) {
22953            return false;
22954        }
22955        synchronized(mPackages) {
22956            final PackageParser.Package pkg = mPackages.get(packageName);
22957            if (pkg == null) {
22958                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22959                throw new IllegalArgumentException("Unknown package: " + packageName);
22960            }
22961            IBinder ksh = ks.getToken();
22962            if (ksh instanceof KeySetHandle) {
22963                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22964                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22965            }
22966            return false;
22967        }
22968    }
22969
22970    @Override
22971    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22972        if (packageName == null || ks == null) {
22973            return false;
22974        }
22975        synchronized(mPackages) {
22976            final PackageParser.Package pkg = mPackages.get(packageName);
22977            if (pkg == null) {
22978                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22979                throw new IllegalArgumentException("Unknown package: " + packageName);
22980            }
22981            IBinder ksh = ks.getToken();
22982            if (ksh instanceof KeySetHandle) {
22983                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22984                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22985            }
22986            return false;
22987        }
22988    }
22989
22990    private void deletePackageIfUnusedLPr(final String packageName) {
22991        PackageSetting ps = mSettings.mPackages.get(packageName);
22992        if (ps == null) {
22993            return;
22994        }
22995        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22996            // TODO Implement atomic delete if package is unused
22997            // It is currently possible that the package will be deleted even if it is installed
22998            // after this method returns.
22999            mHandler.post(new Runnable() {
23000                public void run() {
23001                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23002                            0, PackageManager.DELETE_ALL_USERS);
23003                }
23004            });
23005        }
23006    }
23007
23008    /**
23009     * Check and throw if the given before/after packages would be considered a
23010     * downgrade.
23011     */
23012    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23013            throws PackageManagerException {
23014        if (after.versionCode < before.mVersionCode) {
23015            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23016                    "Update version code " + after.versionCode + " is older than current "
23017                    + before.mVersionCode);
23018        } else if (after.versionCode == before.mVersionCode) {
23019            if (after.baseRevisionCode < before.baseRevisionCode) {
23020                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23021                        "Update base revision code " + after.baseRevisionCode
23022                        + " is older than current " + before.baseRevisionCode);
23023            }
23024
23025            if (!ArrayUtils.isEmpty(after.splitNames)) {
23026                for (int i = 0; i < after.splitNames.length; i++) {
23027                    final String splitName = after.splitNames[i];
23028                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23029                    if (j != -1) {
23030                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23031                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23032                                    "Update split " + splitName + " revision code "
23033                                    + after.splitRevisionCodes[i] + " is older than current "
23034                                    + before.splitRevisionCodes[j]);
23035                        }
23036                    }
23037                }
23038            }
23039        }
23040    }
23041
23042    private static class MoveCallbacks extends Handler {
23043        private static final int MSG_CREATED = 1;
23044        private static final int MSG_STATUS_CHANGED = 2;
23045
23046        private final RemoteCallbackList<IPackageMoveObserver>
23047                mCallbacks = new RemoteCallbackList<>();
23048
23049        private final SparseIntArray mLastStatus = new SparseIntArray();
23050
23051        public MoveCallbacks(Looper looper) {
23052            super(looper);
23053        }
23054
23055        public void register(IPackageMoveObserver callback) {
23056            mCallbacks.register(callback);
23057        }
23058
23059        public void unregister(IPackageMoveObserver callback) {
23060            mCallbacks.unregister(callback);
23061        }
23062
23063        @Override
23064        public void handleMessage(Message msg) {
23065            final SomeArgs args = (SomeArgs) msg.obj;
23066            final int n = mCallbacks.beginBroadcast();
23067            for (int i = 0; i < n; i++) {
23068                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23069                try {
23070                    invokeCallback(callback, msg.what, args);
23071                } catch (RemoteException ignored) {
23072                }
23073            }
23074            mCallbacks.finishBroadcast();
23075            args.recycle();
23076        }
23077
23078        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23079                throws RemoteException {
23080            switch (what) {
23081                case MSG_CREATED: {
23082                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23083                    break;
23084                }
23085                case MSG_STATUS_CHANGED: {
23086                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23087                    break;
23088                }
23089            }
23090        }
23091
23092        private void notifyCreated(int moveId, Bundle extras) {
23093            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23094
23095            final SomeArgs args = SomeArgs.obtain();
23096            args.argi1 = moveId;
23097            args.arg2 = extras;
23098            obtainMessage(MSG_CREATED, args).sendToTarget();
23099        }
23100
23101        private void notifyStatusChanged(int moveId, int status) {
23102            notifyStatusChanged(moveId, status, -1);
23103        }
23104
23105        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23106            Slog.v(TAG, "Move " + moveId + " status " + status);
23107
23108            final SomeArgs args = SomeArgs.obtain();
23109            args.argi1 = moveId;
23110            args.argi2 = status;
23111            args.arg3 = estMillis;
23112            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23113
23114            synchronized (mLastStatus) {
23115                mLastStatus.put(moveId, status);
23116            }
23117        }
23118    }
23119
23120    private final static class OnPermissionChangeListeners extends Handler {
23121        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23122
23123        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23124                new RemoteCallbackList<>();
23125
23126        public OnPermissionChangeListeners(Looper looper) {
23127            super(looper);
23128        }
23129
23130        @Override
23131        public void handleMessage(Message msg) {
23132            switch (msg.what) {
23133                case MSG_ON_PERMISSIONS_CHANGED: {
23134                    final int uid = msg.arg1;
23135                    handleOnPermissionsChanged(uid);
23136                } break;
23137            }
23138        }
23139
23140        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23141            mPermissionListeners.register(listener);
23142
23143        }
23144
23145        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23146            mPermissionListeners.unregister(listener);
23147        }
23148
23149        public void onPermissionsChanged(int uid) {
23150            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23151                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23152            }
23153        }
23154
23155        private void handleOnPermissionsChanged(int uid) {
23156            final int count = mPermissionListeners.beginBroadcast();
23157            try {
23158                for (int i = 0; i < count; i++) {
23159                    IOnPermissionsChangeListener callback = mPermissionListeners
23160                            .getBroadcastItem(i);
23161                    try {
23162                        callback.onPermissionsChanged(uid);
23163                    } catch (RemoteException e) {
23164                        Log.e(TAG, "Permission listener is dead", e);
23165                    }
23166                }
23167            } finally {
23168                mPermissionListeners.finishBroadcast();
23169            }
23170        }
23171    }
23172
23173    private class PackageManagerInternalImpl extends PackageManagerInternal {
23174        @Override
23175        public void setLocationPackagesProvider(PackagesProvider provider) {
23176            synchronized (mPackages) {
23177                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23178            }
23179        }
23180
23181        @Override
23182        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23183            synchronized (mPackages) {
23184                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23185            }
23186        }
23187
23188        @Override
23189        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23190            synchronized (mPackages) {
23191                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23192            }
23193        }
23194
23195        @Override
23196        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23197            synchronized (mPackages) {
23198                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23199            }
23200        }
23201
23202        @Override
23203        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23204            synchronized (mPackages) {
23205                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23206            }
23207        }
23208
23209        @Override
23210        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23211            synchronized (mPackages) {
23212                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23213            }
23214        }
23215
23216        @Override
23217        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23218            synchronized (mPackages) {
23219                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23220                        packageName, userId);
23221            }
23222        }
23223
23224        @Override
23225        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23226            synchronized (mPackages) {
23227                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23228                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23229                        packageName, userId);
23230            }
23231        }
23232
23233        @Override
23234        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23235            synchronized (mPackages) {
23236                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23237                        packageName, userId);
23238            }
23239        }
23240
23241        @Override
23242        public void setKeepUninstalledPackages(final List<String> packageList) {
23243            Preconditions.checkNotNull(packageList);
23244            List<String> removedFromList = null;
23245            synchronized (mPackages) {
23246                if (mKeepUninstalledPackages != null) {
23247                    final int packagesCount = mKeepUninstalledPackages.size();
23248                    for (int i = 0; i < packagesCount; i++) {
23249                        String oldPackage = mKeepUninstalledPackages.get(i);
23250                        if (packageList != null && packageList.contains(oldPackage)) {
23251                            continue;
23252                        }
23253                        if (removedFromList == null) {
23254                            removedFromList = new ArrayList<>();
23255                        }
23256                        removedFromList.add(oldPackage);
23257                    }
23258                }
23259                mKeepUninstalledPackages = new ArrayList<>(packageList);
23260                if (removedFromList != null) {
23261                    final int removedCount = removedFromList.size();
23262                    for (int i = 0; i < removedCount; i++) {
23263                        deletePackageIfUnusedLPr(removedFromList.get(i));
23264                    }
23265                }
23266            }
23267        }
23268
23269        @Override
23270        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23271            synchronized (mPackages) {
23272                // If we do not support permission review, done.
23273                if (!mPermissionReviewRequired) {
23274                    return false;
23275                }
23276
23277                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23278                if (packageSetting == null) {
23279                    return false;
23280                }
23281
23282                // Permission review applies only to apps not supporting the new permission model.
23283                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23284                    return false;
23285                }
23286
23287                // Legacy apps have the permission and get user consent on launch.
23288                PermissionsState permissionsState = packageSetting.getPermissionsState();
23289                return permissionsState.isPermissionReviewRequired(userId);
23290            }
23291        }
23292
23293        @Override
23294        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23295            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23296        }
23297
23298        @Override
23299        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23300                int userId) {
23301            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23302        }
23303
23304        @Override
23305        public void setDeviceAndProfileOwnerPackages(
23306                int deviceOwnerUserId, String deviceOwnerPackage,
23307                SparseArray<String> profileOwnerPackages) {
23308            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23309                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23310        }
23311
23312        @Override
23313        public boolean isPackageDataProtected(int userId, String packageName) {
23314            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23315        }
23316
23317        @Override
23318        public boolean isPackageEphemeral(int userId, String packageName) {
23319            synchronized (mPackages) {
23320                final PackageSetting ps = mSettings.mPackages.get(packageName);
23321                return ps != null ? ps.getInstantApp(userId) : false;
23322            }
23323        }
23324
23325        @Override
23326        public boolean wasPackageEverLaunched(String packageName, int userId) {
23327            synchronized (mPackages) {
23328                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23329            }
23330        }
23331
23332        @Override
23333        public void grantRuntimePermission(String packageName, String name, int userId,
23334                boolean overridePolicy) {
23335            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23336                    overridePolicy);
23337        }
23338
23339        @Override
23340        public void revokeRuntimePermission(String packageName, String name, int userId,
23341                boolean overridePolicy) {
23342            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23343                    overridePolicy);
23344        }
23345
23346        @Override
23347        public String getNameForUid(int uid) {
23348            return PackageManagerService.this.getNameForUid(uid);
23349        }
23350
23351        @Override
23352        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23353                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23354            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23355                    responseObj, origIntent, resolvedType, callingPackage, userId);
23356        }
23357
23358        @Override
23359        public void grantEphemeralAccess(int userId, Intent intent,
23360                int targetAppId, int ephemeralAppId) {
23361            synchronized (mPackages) {
23362                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23363                        targetAppId, ephemeralAppId);
23364            }
23365        }
23366
23367        @Override
23368        public boolean isInstantAppInstallerComponent(ComponentName component) {
23369            synchronized (mPackages) {
23370                return mInstantAppInstallerActivity != null
23371                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23372            }
23373        }
23374
23375        @Override
23376        public void pruneInstantApps() {
23377            synchronized (mPackages) {
23378                mInstantAppRegistry.pruneInstantAppsLPw();
23379            }
23380        }
23381
23382        @Override
23383        public String getSetupWizardPackageName() {
23384            return mSetupWizardPackage;
23385        }
23386
23387        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23388            if (policy != null) {
23389                mExternalSourcesPolicy = policy;
23390            }
23391        }
23392
23393        @Override
23394        public boolean isPackagePersistent(String packageName) {
23395            synchronized (mPackages) {
23396                PackageParser.Package pkg = mPackages.get(packageName);
23397                return pkg != null
23398                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23399                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23400                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23401                        : false;
23402            }
23403        }
23404
23405        @Override
23406        public List<PackageInfo> getOverlayPackages(int userId) {
23407            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23408            synchronized (mPackages) {
23409                for (PackageParser.Package p : mPackages.values()) {
23410                    if (p.mOverlayTarget != null) {
23411                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23412                        if (pkg != null) {
23413                            overlayPackages.add(pkg);
23414                        }
23415                    }
23416                }
23417            }
23418            return overlayPackages;
23419        }
23420
23421        @Override
23422        public List<String> getTargetPackageNames(int userId) {
23423            List<String> targetPackages = new ArrayList<>();
23424            synchronized (mPackages) {
23425                for (PackageParser.Package p : mPackages.values()) {
23426                    if (p.mOverlayTarget == null) {
23427                        targetPackages.add(p.packageName);
23428                    }
23429                }
23430            }
23431            return targetPackages;
23432        }
23433
23434        @Override
23435        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23436                @Nullable List<String> overlayPackageNames) {
23437            synchronized (mPackages) {
23438                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23439                    Slog.e(TAG, "failed to find package " + targetPackageName);
23440                    return false;
23441                }
23442
23443                ArrayList<String> paths = null;
23444                if (overlayPackageNames != null) {
23445                    final int N = overlayPackageNames.size();
23446                    paths = new ArrayList<>(N);
23447                    for (int i = 0; i < N; i++) {
23448                        final String packageName = overlayPackageNames.get(i);
23449                        final PackageParser.Package pkg = mPackages.get(packageName);
23450                        if (pkg == null) {
23451                            Slog.e(TAG, "failed to find package " + packageName);
23452                            return false;
23453                        }
23454                        paths.add(pkg.baseCodePath);
23455                    }
23456                }
23457
23458                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23459                    mEnabledOverlayPaths.get(userId);
23460                if (userSpecificOverlays == null) {
23461                    userSpecificOverlays = new ArrayMap<>();
23462                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23463                }
23464
23465                if (paths != null && paths.size() > 0) {
23466                    userSpecificOverlays.put(targetPackageName, paths);
23467                } else {
23468                    userSpecificOverlays.remove(targetPackageName);
23469                }
23470                return true;
23471            }
23472        }
23473
23474        @Override
23475        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23476                int flags, int userId) {
23477            return resolveIntentInternal(
23478                    intent, resolvedType, flags, userId, true /*includeInstantApps*/);
23479        }
23480
23481        @Override
23482        public ResolveInfo resolveService(Intent intent, String resolvedType,
23483                int flags, int userId, int callingUid) {
23484            return resolveServiceInternal(
23485                    intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/);
23486        }
23487
23488        @Override
23489        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23490            synchronized (mPackages) {
23491                mIsolatedOwners.put(isolatedUid, ownerUid);
23492            }
23493        }
23494
23495        @Override
23496        public void removeIsolatedUid(int isolatedUid) {
23497            synchronized (mPackages) {
23498                mIsolatedOwners.delete(isolatedUid);
23499            }
23500        }
23501    }
23502
23503    @Override
23504    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23505        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23506        synchronized (mPackages) {
23507            final long identity = Binder.clearCallingIdentity();
23508            try {
23509                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23510                        packageNames, userId);
23511            } finally {
23512                Binder.restoreCallingIdentity(identity);
23513            }
23514        }
23515    }
23516
23517    @Override
23518    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23519        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23520        synchronized (mPackages) {
23521            final long identity = Binder.clearCallingIdentity();
23522            try {
23523                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23524                        packageNames, userId);
23525            } finally {
23526                Binder.restoreCallingIdentity(identity);
23527            }
23528        }
23529    }
23530
23531    private static void enforceSystemOrPhoneCaller(String tag) {
23532        int callingUid = Binder.getCallingUid();
23533        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23534            throw new SecurityException(
23535                    "Cannot call " + tag + " from UID " + callingUid);
23536        }
23537    }
23538
23539    boolean isHistoricalPackageUsageAvailable() {
23540        return mPackageUsage.isHistoricalPackageUsageAvailable();
23541    }
23542
23543    /**
23544     * Return a <b>copy</b> of the collection of packages known to the package manager.
23545     * @return A copy of the values of mPackages.
23546     */
23547    Collection<PackageParser.Package> getPackages() {
23548        synchronized (mPackages) {
23549            return new ArrayList<>(mPackages.values());
23550        }
23551    }
23552
23553    /**
23554     * Logs process start information (including base APK hash) to the security log.
23555     * @hide
23556     */
23557    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23558            String apkFile, int pid) {
23559        if (!SecurityLog.isLoggingEnabled()) {
23560            return;
23561        }
23562        Bundle data = new Bundle();
23563        data.putLong("startTimestamp", System.currentTimeMillis());
23564        data.putString("processName", processName);
23565        data.putInt("uid", uid);
23566        data.putString("seinfo", seinfo);
23567        data.putString("apkFile", apkFile);
23568        data.putInt("pid", pid);
23569        Message msg = mProcessLoggingHandler.obtainMessage(
23570                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23571        msg.setData(data);
23572        mProcessLoggingHandler.sendMessage(msg);
23573    }
23574
23575    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23576        return mCompilerStats.getPackageStats(pkgName);
23577    }
23578
23579    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23580        return getOrCreateCompilerPackageStats(pkg.packageName);
23581    }
23582
23583    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23584        return mCompilerStats.getOrCreatePackageStats(pkgName);
23585    }
23586
23587    public void deleteCompilerPackageStats(String pkgName) {
23588        mCompilerStats.deletePackageStats(pkgName);
23589    }
23590
23591    @Override
23592    public int getInstallReason(String packageName, int userId) {
23593        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23594                true /* requireFullPermission */, false /* checkShell */,
23595                "get install reason");
23596        synchronized (mPackages) {
23597            final PackageSetting ps = mSettings.mPackages.get(packageName);
23598            if (ps != null) {
23599                return ps.getInstallReason(userId);
23600            }
23601        }
23602        return PackageManager.INSTALL_REASON_UNKNOWN;
23603    }
23604
23605    @Override
23606    public boolean canRequestPackageInstalls(String packageName, int userId) {
23607        int callingUid = Binder.getCallingUid();
23608        int uid = getPackageUid(packageName, 0, userId);
23609        if (callingUid != uid && callingUid != Process.ROOT_UID
23610                && callingUid != Process.SYSTEM_UID) {
23611            throw new SecurityException(
23612                    "Caller uid " + callingUid + " does not own package " + packageName);
23613        }
23614        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23615        if (info == null) {
23616            return false;
23617        }
23618        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23619            throw new UnsupportedOperationException(
23620                    "Operation only supported on apps targeting Android O or higher");
23621        }
23622        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23623        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23624        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23625            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23626        }
23627        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23628            return false;
23629        }
23630        if (mExternalSourcesPolicy != null) {
23631            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23632            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23633                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23634            }
23635        }
23636        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23637    }
23638
23639    @Override
23640    public ComponentName getInstantAppResolverSettingsComponent() {
23641        return mInstantAppResolverSettingsComponent;
23642    }
23643
23644    @Override
23645    public ComponentName getInstantAppInstallerComponent() {
23646        return mInstantAppInstallerActivity == null
23647                ? null : mInstantAppInstallerActivity.getComponentName();
23648    }
23649}
23650