PackageManagerService.java revision 801e65905b267014f390439cf8388b6ccc854e18
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                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2808                        mIntentFilterVerifierComponent);
2809                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2810                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2811                        SharedLibraryInfo.VERSION_UNDEFINED);
2812                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2813                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2814                        SharedLibraryInfo.VERSION_UNDEFINED);
2815            } else {
2816                mRequiredVerifierPackage = null;
2817                mRequiredInstallerPackage = null;
2818                mRequiredUninstallerPackage = null;
2819                mIntentFilterVerifierComponent = null;
2820                mIntentFilterVerifier = null;
2821                mServicesSystemSharedLibraryPackageName = null;
2822                mSharedSystemSharedLibraryPackageName = null;
2823            }
2824
2825            mInstallerService = new PackageInstallerService(context, this);
2826            final Pair<ComponentName, String> instantAppResolverComponent =
2827                    getInstantAppResolverLPr();
2828            if (instantAppResolverComponent != null) {
2829                if (DEBUG_EPHEMERAL) {
2830                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2831                }
2832                mInstantAppResolverConnection = new EphemeralResolverConnection(
2833                        mContext, instantAppResolverComponent.first,
2834                        instantAppResolverComponent.second);
2835                mInstantAppResolverSettingsComponent =
2836                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2837            } else {
2838                mInstantAppResolverConnection = null;
2839                mInstantAppResolverSettingsComponent = null;
2840            }
2841            updateInstantAppInstallerLocked(null);
2842
2843            // Read and update the usage of dex files.
2844            // Do this at the end of PM init so that all the packages have their
2845            // data directory reconciled.
2846            // At this point we know the code paths of the packages, so we can validate
2847            // the disk file and build the internal cache.
2848            // The usage file is expected to be small so loading and verifying it
2849            // should take a fairly small time compare to the other activities (e.g. package
2850            // scanning).
2851            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2852            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2853            for (int userId : currentUserIds) {
2854                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2855            }
2856            mDexManager.load(userPackages);
2857        } // synchronized (mPackages)
2858        } // synchronized (mInstallLock)
2859
2860        // Now after opening every single application zip, make sure they
2861        // are all flushed.  Not really needed, but keeps things nice and
2862        // tidy.
2863        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2864        Runtime.getRuntime().gc();
2865        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2866
2867        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2868        FallbackCategoryProvider.loadFallbacks();
2869        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2870
2871        // The initial scanning above does many calls into installd while
2872        // holding the mPackages lock, but we're mostly interested in yelling
2873        // once we have a booted system.
2874        mInstaller.setWarnIfHeld(mPackages);
2875
2876        // Expose private service for system components to use.
2877        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2878        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2879    }
2880
2881    private void updateInstantAppInstallerLocked(String modifiedPackage) {
2882        // we're only interested in updating the installer appliction when 1) it's not
2883        // already set or 2) the modified package is the installer
2884        if (mInstantAppInstallerActivity != null
2885                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
2886                        .equals(modifiedPackage)) {
2887            return;
2888        }
2889        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
2890    }
2891
2892    private static File preparePackageParserCache(boolean isUpgrade) {
2893        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2894            return null;
2895        }
2896
2897        // Disable package parsing on eng builds to allow for faster incremental development.
2898        if ("eng".equals(Build.TYPE)) {
2899            return null;
2900        }
2901
2902        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2903            Slog.i(TAG, "Disabling package parser cache due to system property.");
2904            return null;
2905        }
2906
2907        // The base directory for the package parser cache lives under /data/system/.
2908        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2909                "package_cache");
2910        if (cacheBaseDir == null) {
2911            return null;
2912        }
2913
2914        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2915        // This also serves to "GC" unused entries when the package cache version changes (which
2916        // can only happen during upgrades).
2917        if (isUpgrade) {
2918            FileUtils.deleteContents(cacheBaseDir);
2919        }
2920
2921
2922        // Return the versioned package cache directory. This is something like
2923        // "/data/system/package_cache/1"
2924        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2925
2926        // The following is a workaround to aid development on non-numbered userdebug
2927        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2928        // the system partition is newer.
2929        //
2930        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2931        // that starts with "eng." to signify that this is an engineering build and not
2932        // destined for release.
2933        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2934            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2935
2936            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2937            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2938            // in general and should not be used for production changes. In this specific case,
2939            // we know that they will work.
2940            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2941            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2942                FileUtils.deleteContents(cacheBaseDir);
2943                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2944            }
2945        }
2946
2947        return cacheDir;
2948    }
2949
2950    @Override
2951    public boolean isFirstBoot() {
2952        return mFirstBoot;
2953    }
2954
2955    @Override
2956    public boolean isOnlyCoreApps() {
2957        return mOnlyCore;
2958    }
2959
2960    @Override
2961    public boolean isUpgrade() {
2962        return mIsUpgrade;
2963    }
2964
2965    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2966        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2967
2968        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2969                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2970                UserHandle.USER_SYSTEM);
2971        if (matches.size() == 1) {
2972            return matches.get(0).getComponentInfo().packageName;
2973        } else if (matches.size() == 0) {
2974            Log.e(TAG, "There should probably be a verifier, but, none were found");
2975            return null;
2976        }
2977        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2978    }
2979
2980    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2981        synchronized (mPackages) {
2982            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2983            if (libraryEntry == null) {
2984                throw new IllegalStateException("Missing required shared library:" + name);
2985            }
2986            return libraryEntry.apk;
2987        }
2988    }
2989
2990    private @NonNull String getRequiredInstallerLPr() {
2991        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2992        intent.addCategory(Intent.CATEGORY_DEFAULT);
2993        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2994
2995        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2996                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2997                UserHandle.USER_SYSTEM);
2998        if (matches.size() == 1) {
2999            ResolveInfo resolveInfo = matches.get(0);
3000            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3001                throw new RuntimeException("The installer must be a privileged app");
3002            }
3003            return matches.get(0).getComponentInfo().packageName;
3004        } else {
3005            throw new RuntimeException("There must be exactly one installer; found " + matches);
3006        }
3007    }
3008
3009    private @NonNull String getRequiredUninstallerLPr() {
3010        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3011        intent.addCategory(Intent.CATEGORY_DEFAULT);
3012        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3013
3014        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3015                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3016                UserHandle.USER_SYSTEM);
3017        if (resolveInfo == null ||
3018                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3019            throw new RuntimeException("There must be exactly one uninstaller; found "
3020                    + resolveInfo);
3021        }
3022        return resolveInfo.getComponentInfo().packageName;
3023    }
3024
3025    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3026        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3027
3028        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3029                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3030                UserHandle.USER_SYSTEM);
3031        ResolveInfo best = null;
3032        final int N = matches.size();
3033        for (int i = 0; i < N; i++) {
3034            final ResolveInfo cur = matches.get(i);
3035            final String packageName = cur.getComponentInfo().packageName;
3036            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3037                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3038                continue;
3039            }
3040
3041            if (best == null || cur.priority > best.priority) {
3042                best = cur;
3043            }
3044        }
3045
3046        if (best != null) {
3047            return best.getComponentInfo().getComponentName();
3048        } else {
3049            throw new RuntimeException("There must be at least one intent filter verifier");
3050        }
3051    }
3052
3053    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3054        final String[] packageArray =
3055                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3056        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3057            if (DEBUG_EPHEMERAL) {
3058                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3059            }
3060            return null;
3061        }
3062
3063        final int callingUid = Binder.getCallingUid();
3064        final int resolveFlags =
3065                MATCH_DIRECT_BOOT_AWARE
3066                | MATCH_DIRECT_BOOT_UNAWARE
3067                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3068        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3069        final Intent resolverIntent = new Intent(actionName);
3070        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3071                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3072        // temporarily look for the old action
3073        if (resolvers.size() == 0) {
3074            if (DEBUG_EPHEMERAL) {
3075                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3076            }
3077            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3078            resolverIntent.setAction(actionName);
3079            resolvers = queryIntentServicesInternal(resolverIntent, null,
3080                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3081        }
3082        final int N = resolvers.size();
3083        if (N == 0) {
3084            if (DEBUG_EPHEMERAL) {
3085                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3086            }
3087            return null;
3088        }
3089
3090        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3091        for (int i = 0; i < N; i++) {
3092            final ResolveInfo info = resolvers.get(i);
3093
3094            if (info.serviceInfo == null) {
3095                continue;
3096            }
3097
3098            final String packageName = info.serviceInfo.packageName;
3099            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3100                if (DEBUG_EPHEMERAL) {
3101                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3102                            + " pkg: " + packageName + ", info:" + info);
3103                }
3104                continue;
3105            }
3106
3107            if (DEBUG_EPHEMERAL) {
3108                Slog.v(TAG, "Ephemeral resolver found;"
3109                        + " pkg: " + packageName + ", info:" + info);
3110            }
3111            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3112        }
3113        if (DEBUG_EPHEMERAL) {
3114            Slog.v(TAG, "Ephemeral resolver NOT found");
3115        }
3116        return null;
3117    }
3118
3119    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3120        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3121        intent.addCategory(Intent.CATEGORY_DEFAULT);
3122        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3123
3124        final int resolveFlags =
3125                MATCH_DIRECT_BOOT_AWARE
3126                | MATCH_DIRECT_BOOT_UNAWARE
3127                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3128        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3129                resolveFlags, UserHandle.USER_SYSTEM);
3130        // temporarily look for the old action
3131        if (matches.isEmpty()) {
3132            if (DEBUG_EPHEMERAL) {
3133                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3134            }
3135            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3136            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3137                    resolveFlags, UserHandle.USER_SYSTEM);
3138        }
3139        Iterator<ResolveInfo> iter = matches.iterator();
3140        while (iter.hasNext()) {
3141            final ResolveInfo rInfo = iter.next();
3142            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3143            if (ps != null) {
3144                final PermissionsState permissionsState = ps.getPermissionsState();
3145                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3146                    continue;
3147                }
3148            }
3149            iter.remove();
3150        }
3151        if (matches.size() == 0) {
3152            return null;
3153        } else if (matches.size() == 1) {
3154            return (ActivityInfo) matches.get(0).getComponentInfo();
3155        } else {
3156            throw new RuntimeException(
3157                    "There must be at most one ephemeral installer; found " + matches);
3158        }
3159    }
3160
3161    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3162            @NonNull ComponentName resolver) {
3163        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3164                .addCategory(Intent.CATEGORY_DEFAULT)
3165                .setPackage(resolver.getPackageName());
3166        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3167        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3168                UserHandle.USER_SYSTEM);
3169        // temporarily look for the old action
3170        if (matches.isEmpty()) {
3171            if (DEBUG_EPHEMERAL) {
3172                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3173            }
3174            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3175            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3176                    UserHandle.USER_SYSTEM);
3177        }
3178        if (matches.isEmpty()) {
3179            return null;
3180        }
3181        return matches.get(0).getComponentInfo().getComponentName();
3182    }
3183
3184    private void primeDomainVerificationsLPw(int userId) {
3185        if (DEBUG_DOMAIN_VERIFICATION) {
3186            Slog.d(TAG, "Priming domain verifications in user " + userId);
3187        }
3188
3189        SystemConfig systemConfig = SystemConfig.getInstance();
3190        ArraySet<String> packages = systemConfig.getLinkedApps();
3191
3192        for (String packageName : packages) {
3193            PackageParser.Package pkg = mPackages.get(packageName);
3194            if (pkg != null) {
3195                if (!pkg.isSystemApp()) {
3196                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3197                    continue;
3198                }
3199
3200                ArraySet<String> domains = null;
3201                for (PackageParser.Activity a : pkg.activities) {
3202                    for (ActivityIntentInfo filter : a.intents) {
3203                        if (hasValidDomains(filter)) {
3204                            if (domains == null) {
3205                                domains = new ArraySet<String>();
3206                            }
3207                            domains.addAll(filter.getHostsList());
3208                        }
3209                    }
3210                }
3211
3212                if (domains != null && domains.size() > 0) {
3213                    if (DEBUG_DOMAIN_VERIFICATION) {
3214                        Slog.v(TAG, "      + " + packageName);
3215                    }
3216                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3217                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3218                    // and then 'always' in the per-user state actually used for intent resolution.
3219                    final IntentFilterVerificationInfo ivi;
3220                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3221                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3222                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3223                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3224                } else {
3225                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3226                            + "' does not handle web links");
3227                }
3228            } else {
3229                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3230            }
3231        }
3232
3233        scheduleWritePackageRestrictionsLocked(userId);
3234        scheduleWriteSettingsLocked();
3235    }
3236
3237    private void applyFactoryDefaultBrowserLPw(int userId) {
3238        // The default browser app's package name is stored in a string resource,
3239        // with a product-specific overlay used for vendor customization.
3240        String browserPkg = mContext.getResources().getString(
3241                com.android.internal.R.string.default_browser);
3242        if (!TextUtils.isEmpty(browserPkg)) {
3243            // non-empty string => required to be a known package
3244            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3245            if (ps == null) {
3246                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3247                browserPkg = null;
3248            } else {
3249                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3250            }
3251        }
3252
3253        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3254        // default.  If there's more than one, just leave everything alone.
3255        if (browserPkg == null) {
3256            calculateDefaultBrowserLPw(userId);
3257        }
3258    }
3259
3260    private void calculateDefaultBrowserLPw(int userId) {
3261        List<String> allBrowsers = resolveAllBrowserApps(userId);
3262        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3263        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3264    }
3265
3266    private List<String> resolveAllBrowserApps(int userId) {
3267        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3268        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3269                PackageManager.MATCH_ALL, userId);
3270
3271        final int count = list.size();
3272        List<String> result = new ArrayList<String>(count);
3273        for (int i=0; i<count; i++) {
3274            ResolveInfo info = list.get(i);
3275            if (info.activityInfo == null
3276                    || !info.handleAllWebDataURI
3277                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3278                    || result.contains(info.activityInfo.packageName)) {
3279                continue;
3280            }
3281            result.add(info.activityInfo.packageName);
3282        }
3283
3284        return result;
3285    }
3286
3287    private boolean packageIsBrowser(String packageName, int userId) {
3288        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3289                PackageManager.MATCH_ALL, userId);
3290        final int N = list.size();
3291        for (int i = 0; i < N; i++) {
3292            ResolveInfo info = list.get(i);
3293            if (packageName.equals(info.activityInfo.packageName)) {
3294                return true;
3295            }
3296        }
3297        return false;
3298    }
3299
3300    private void checkDefaultBrowser() {
3301        final int myUserId = UserHandle.myUserId();
3302        final String packageName = getDefaultBrowserPackageName(myUserId);
3303        if (packageName != null) {
3304            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3305            if (info == null) {
3306                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3307                synchronized (mPackages) {
3308                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3309                }
3310            }
3311        }
3312    }
3313
3314    @Override
3315    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3316            throws RemoteException {
3317        try {
3318            return super.onTransact(code, data, reply, flags);
3319        } catch (RuntimeException e) {
3320            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3321                Slog.wtf(TAG, "Package Manager Crash", e);
3322            }
3323            throw e;
3324        }
3325    }
3326
3327    static int[] appendInts(int[] cur, int[] add) {
3328        if (add == null) return cur;
3329        if (cur == null) return add;
3330        final int N = add.length;
3331        for (int i=0; i<N; i++) {
3332            cur = appendInt(cur, add[i]);
3333        }
3334        return cur;
3335    }
3336
3337    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3338        if (!sUserManager.exists(userId)) return null;
3339        if (ps == null) {
3340            return null;
3341        }
3342        final PackageParser.Package p = ps.pkg;
3343        if (p == null) {
3344            return null;
3345        }
3346        // Filter out ephemeral app metadata:
3347        //   * The system/shell/root can see metadata for any app
3348        //   * An installed app can see metadata for 1) other installed apps
3349        //     and 2) ephemeral apps that have explicitly interacted with it
3350        //   * Ephemeral apps can only see their own data and exposed installed apps
3351        //   * Holding a signature permission allows seeing instant apps
3352        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3353        if (callingAppId != Process.SYSTEM_UID
3354                && callingAppId != Process.SHELL_UID
3355                && callingAppId != Process.ROOT_UID
3356                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3357                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3358            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3359            if (instantAppPackageName != null) {
3360                // ephemeral apps can only get information on themselves or
3361                // installed apps that are exposed.
3362                if (!instantAppPackageName.equals(p.packageName)
3363                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3364                    return null;
3365                }
3366            } else {
3367                if (ps.getInstantApp(userId)) {
3368                    // only get access to the ephemeral app if we've been granted access
3369                    if (!mInstantAppRegistry.isInstantAccessGranted(
3370                            userId, callingAppId, ps.appId)) {
3371                        return null;
3372                    }
3373                }
3374            }
3375        }
3376
3377        final PermissionsState permissionsState = ps.getPermissionsState();
3378
3379        // Compute GIDs only if requested
3380        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3381                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3382        // Compute granted permissions only if package has requested permissions
3383        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3384                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3385        final PackageUserState state = ps.readUserState(userId);
3386
3387        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3388                && ps.isSystem()) {
3389            flags |= MATCH_ANY_USER;
3390        }
3391
3392        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3393                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3394
3395        if (packageInfo == null) {
3396            return null;
3397        }
3398
3399        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3400
3401        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3402                resolveExternalPackageNameLPr(p);
3403
3404        return packageInfo;
3405    }
3406
3407    @Override
3408    public void checkPackageStartable(String packageName, int userId) {
3409        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3410
3411        synchronized (mPackages) {
3412            final PackageSetting ps = mSettings.mPackages.get(packageName);
3413            if (ps == null) {
3414                throw new SecurityException("Package " + packageName + " was not found!");
3415            }
3416
3417            if (!ps.getInstalled(userId)) {
3418                throw new SecurityException(
3419                        "Package " + packageName + " was not installed for user " + userId + "!");
3420            }
3421
3422            if (mSafeMode && !ps.isSystem()) {
3423                throw new SecurityException("Package " + packageName + " not a system app!");
3424            }
3425
3426            if (mFrozenPackages.contains(packageName)) {
3427                throw new SecurityException("Package " + packageName + " is currently frozen!");
3428            }
3429
3430            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3431                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3432                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3433            }
3434        }
3435    }
3436
3437    @Override
3438    public boolean isPackageAvailable(String packageName, int userId) {
3439        if (!sUserManager.exists(userId)) return false;
3440        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3441                false /* requireFullPermission */, false /* checkShell */, "is package available");
3442        synchronized (mPackages) {
3443            PackageParser.Package p = mPackages.get(packageName);
3444            if (p != null) {
3445                final PackageSetting ps = (PackageSetting) p.mExtras;
3446                if (ps != null) {
3447                    final PackageUserState state = ps.readUserState(userId);
3448                    if (state != null) {
3449                        return PackageParser.isAvailable(state);
3450                    }
3451                }
3452            }
3453        }
3454        return false;
3455    }
3456
3457    @Override
3458    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3459        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3460                flags, userId);
3461    }
3462
3463    @Override
3464    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3465            int flags, int userId) {
3466        return getPackageInfoInternal(versionedPackage.getPackageName(),
3467                // TODO: We will change version code to long, so in the new API it is long
3468                (int) versionedPackage.getVersionCode(), flags, userId);
3469    }
3470
3471    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3472            int flags, int userId) {
3473        if (!sUserManager.exists(userId)) return null;
3474        flags = updateFlagsForPackage(flags, userId, packageName);
3475        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3476                false /* requireFullPermission */, false /* checkShell */, "get package info");
3477
3478        // reader
3479        synchronized (mPackages) {
3480            // Normalize package name to handle renamed packages and static libs
3481            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3482
3483            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3484            if (matchFactoryOnly) {
3485                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3486                if (ps != null) {
3487                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3488                        return null;
3489                    }
3490                    return generatePackageInfo(ps, flags, userId);
3491                }
3492            }
3493
3494            PackageParser.Package p = mPackages.get(packageName);
3495            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3496                return null;
3497            }
3498            if (DEBUG_PACKAGE_INFO)
3499                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3500            if (p != null) {
3501                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3502                        Binder.getCallingUid(), userId)) {
3503                    return null;
3504                }
3505                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3506            }
3507            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3508                final PackageSetting ps = mSettings.mPackages.get(packageName);
3509                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3510                    return null;
3511                }
3512                return generatePackageInfo(ps, flags, userId);
3513            }
3514        }
3515        return null;
3516    }
3517
3518
3519    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3520        // System/shell/root get to see all static libs
3521        final int appId = UserHandle.getAppId(uid);
3522        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3523                || appId == Process.ROOT_UID) {
3524            return false;
3525        }
3526
3527        // No package means no static lib as it is always on internal storage
3528        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3529            return false;
3530        }
3531
3532        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3533                ps.pkg.staticSharedLibVersion);
3534        if (libEntry == null) {
3535            return false;
3536        }
3537
3538        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3539        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3540        if (uidPackageNames == null) {
3541            return true;
3542        }
3543
3544        for (String uidPackageName : uidPackageNames) {
3545            if (ps.name.equals(uidPackageName)) {
3546                return false;
3547            }
3548            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3549            if (uidPs != null) {
3550                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3551                        libEntry.info.getName());
3552                if (index < 0) {
3553                    continue;
3554                }
3555                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3556                    return false;
3557                }
3558            }
3559        }
3560        return true;
3561    }
3562
3563    @Override
3564    public String[] currentToCanonicalPackageNames(String[] names) {
3565        String[] out = new String[names.length];
3566        // reader
3567        synchronized (mPackages) {
3568            for (int i=names.length-1; i>=0; i--) {
3569                PackageSetting ps = mSettings.mPackages.get(names[i]);
3570                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3571            }
3572        }
3573        return out;
3574    }
3575
3576    @Override
3577    public String[] canonicalToCurrentPackageNames(String[] names) {
3578        String[] out = new String[names.length];
3579        // reader
3580        synchronized (mPackages) {
3581            for (int i=names.length-1; i>=0; i--) {
3582                String cur = mSettings.getRenamedPackageLPr(names[i]);
3583                out[i] = cur != null ? cur : names[i];
3584            }
3585        }
3586        return out;
3587    }
3588
3589    @Override
3590    public int getPackageUid(String packageName, int flags, int userId) {
3591        if (!sUserManager.exists(userId)) return -1;
3592        flags = updateFlagsForPackage(flags, userId, packageName);
3593        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3594                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3595
3596        // reader
3597        synchronized (mPackages) {
3598            final PackageParser.Package p = mPackages.get(packageName);
3599            if (p != null && p.isMatch(flags)) {
3600                return UserHandle.getUid(userId, p.applicationInfo.uid);
3601            }
3602            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3603                final PackageSetting ps = mSettings.mPackages.get(packageName);
3604                if (ps != null && ps.isMatch(flags)) {
3605                    return UserHandle.getUid(userId, ps.appId);
3606                }
3607            }
3608        }
3609
3610        return -1;
3611    }
3612
3613    @Override
3614    public int[] getPackageGids(String packageName, int flags, int userId) {
3615        if (!sUserManager.exists(userId)) return null;
3616        flags = updateFlagsForPackage(flags, userId, packageName);
3617        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3618                false /* requireFullPermission */, false /* checkShell */,
3619                "getPackageGids");
3620
3621        // reader
3622        synchronized (mPackages) {
3623            final PackageParser.Package p = mPackages.get(packageName);
3624            if (p != null && p.isMatch(flags)) {
3625                PackageSetting ps = (PackageSetting) p.mExtras;
3626                // TODO: Shouldn't this be checking for package installed state for userId and
3627                // return null?
3628                return ps.getPermissionsState().computeGids(userId);
3629            }
3630            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3631                final PackageSetting ps = mSettings.mPackages.get(packageName);
3632                if (ps != null && ps.isMatch(flags)) {
3633                    return ps.getPermissionsState().computeGids(userId);
3634                }
3635            }
3636        }
3637
3638        return null;
3639    }
3640
3641    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3642        if (bp.perm != null) {
3643            return PackageParser.generatePermissionInfo(bp.perm, flags);
3644        }
3645        PermissionInfo pi = new PermissionInfo();
3646        pi.name = bp.name;
3647        pi.packageName = bp.sourcePackage;
3648        pi.nonLocalizedLabel = bp.name;
3649        pi.protectionLevel = bp.protectionLevel;
3650        return pi;
3651    }
3652
3653    @Override
3654    public PermissionInfo getPermissionInfo(String name, int flags) {
3655        // reader
3656        synchronized (mPackages) {
3657            final BasePermission p = mSettings.mPermissions.get(name);
3658            if (p != null) {
3659                return generatePermissionInfo(p, flags);
3660            }
3661            return null;
3662        }
3663    }
3664
3665    @Override
3666    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3667            int flags) {
3668        // reader
3669        synchronized (mPackages) {
3670            if (group != null && !mPermissionGroups.containsKey(group)) {
3671                // This is thrown as NameNotFoundException
3672                return null;
3673            }
3674
3675            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3676            for (BasePermission p : mSettings.mPermissions.values()) {
3677                if (group == null) {
3678                    if (p.perm == null || p.perm.info.group == null) {
3679                        out.add(generatePermissionInfo(p, flags));
3680                    }
3681                } else {
3682                    if (p.perm != null && group.equals(p.perm.info.group)) {
3683                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3684                    }
3685                }
3686            }
3687            return new ParceledListSlice<>(out);
3688        }
3689    }
3690
3691    @Override
3692    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3693        // reader
3694        synchronized (mPackages) {
3695            return PackageParser.generatePermissionGroupInfo(
3696                    mPermissionGroups.get(name), flags);
3697        }
3698    }
3699
3700    @Override
3701    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3702        // reader
3703        synchronized (mPackages) {
3704            final int N = mPermissionGroups.size();
3705            ArrayList<PermissionGroupInfo> out
3706                    = new ArrayList<PermissionGroupInfo>(N);
3707            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3708                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3709            }
3710            return new ParceledListSlice<>(out);
3711        }
3712    }
3713
3714    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3715            int uid, int userId) {
3716        if (!sUserManager.exists(userId)) return null;
3717        PackageSetting ps = mSettings.mPackages.get(packageName);
3718        if (ps != null) {
3719            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3720                return null;
3721            }
3722            if (ps.pkg == null) {
3723                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3724                if (pInfo != null) {
3725                    return pInfo.applicationInfo;
3726                }
3727                return null;
3728            }
3729            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3730                    ps.readUserState(userId), userId);
3731            if (ai != null) {
3732                rebaseEnabledOverlays(ai, userId);
3733                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3734            }
3735            return ai;
3736        }
3737        return null;
3738    }
3739
3740    @Override
3741    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3742        if (!sUserManager.exists(userId)) return null;
3743        flags = updateFlagsForApplication(flags, userId, packageName);
3744        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3745                false /* requireFullPermission */, false /* checkShell */, "get application info");
3746
3747        // writer
3748        synchronized (mPackages) {
3749            // Normalize package name to handle renamed packages and static libs
3750            packageName = resolveInternalPackageNameLPr(packageName,
3751                    PackageManager.VERSION_CODE_HIGHEST);
3752
3753            PackageParser.Package p = mPackages.get(packageName);
3754            if (DEBUG_PACKAGE_INFO) Log.v(
3755                    TAG, "getApplicationInfo " + packageName
3756                    + ": " + p);
3757            if (p != null) {
3758                PackageSetting ps = mSettings.mPackages.get(packageName);
3759                if (ps == null) return null;
3760                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3761                    return null;
3762                }
3763                // Note: isEnabledLP() does not apply here - always return info
3764                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3765                        p, flags, ps.readUserState(userId), userId);
3766                if (ai != null) {
3767                    rebaseEnabledOverlays(ai, userId);
3768                    ai.packageName = resolveExternalPackageNameLPr(p);
3769                }
3770                return ai;
3771            }
3772            if ("android".equals(packageName)||"system".equals(packageName)) {
3773                return mAndroidApplication;
3774            }
3775            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3776                // Already generates the external package name
3777                return generateApplicationInfoFromSettingsLPw(packageName,
3778                        Binder.getCallingUid(), flags, userId);
3779            }
3780        }
3781        return null;
3782    }
3783
3784    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3785        List<String> paths = new ArrayList<>();
3786        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3787            mEnabledOverlayPaths.get(userId);
3788        if (userSpecificOverlays != null) {
3789            if (!"android".equals(ai.packageName)) {
3790                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3791                if (frameworkOverlays != null) {
3792                    paths.addAll(frameworkOverlays);
3793                }
3794            }
3795
3796            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3797            if (appOverlays != null) {
3798                paths.addAll(appOverlays);
3799            }
3800        }
3801        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3802    }
3803
3804    private String normalizePackageNameLPr(String packageName) {
3805        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3806        return normalizedPackageName != null ? normalizedPackageName : packageName;
3807    }
3808
3809    @Override
3810    public void deletePreloadsFileCache() {
3811        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3812            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3813        }
3814        File dir = Environment.getDataPreloadsFileCacheDirectory();
3815        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3816        FileUtils.deleteContents(dir);
3817    }
3818
3819    @Override
3820    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3821            final IPackageDataObserver observer) {
3822        mContext.enforceCallingOrSelfPermission(
3823                android.Manifest.permission.CLEAR_APP_CACHE, null);
3824        mHandler.post(() -> {
3825            boolean success = false;
3826            try {
3827                freeStorage(volumeUuid, freeStorageSize, 0);
3828                success = true;
3829            } catch (IOException e) {
3830                Slog.w(TAG, e);
3831            }
3832            if (observer != null) {
3833                try {
3834                    observer.onRemoveCompleted(null, success);
3835                } catch (RemoteException e) {
3836                    Slog.w(TAG, e);
3837                }
3838            }
3839        });
3840    }
3841
3842    @Override
3843    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3844            final IntentSender pi) {
3845        mContext.enforceCallingOrSelfPermission(
3846                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3847        mHandler.post(() -> {
3848            boolean success = false;
3849            try {
3850                freeStorage(volumeUuid, freeStorageSize, 0);
3851                success = true;
3852            } catch (IOException e) {
3853                Slog.w(TAG, e);
3854            }
3855            if (pi != null) {
3856                try {
3857                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3858                } catch (SendIntentException e) {
3859                    Slog.w(TAG, e);
3860                }
3861            }
3862        });
3863    }
3864
3865    /**
3866     * Blocking call to clear various types of cached data across the system
3867     * until the requested bytes are available.
3868     */
3869    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3870        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3871        final File file = storage.findPathForUuid(volumeUuid);
3872        if (file.getUsableSpace() >= bytes) return;
3873
3874        if (ENABLE_FREE_CACHE_V2) {
3875            final boolean aggressive = (storageFlags
3876                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3877            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
3878                    volumeUuid);
3879
3880            // 1. Pre-flight to determine if we have any chance to succeed
3881            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3882            if (internalVolume && (aggressive || SystemProperties
3883                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
3884                deletePreloadsFileCache();
3885                if (file.getUsableSpace() >= bytes) return;
3886            }
3887
3888            // 3. Consider parsed APK data (aggressive only)
3889            if (internalVolume && aggressive) {
3890                FileUtils.deleteContents(mCacheDir);
3891                if (file.getUsableSpace() >= bytes) return;
3892            }
3893
3894            // 4. Consider cached app data (above quotas)
3895            try {
3896                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3897            } catch (InstallerException ignored) {
3898            }
3899            if (file.getUsableSpace() >= bytes) return;
3900
3901            // 5. Consider shared libraries with refcount=0 and age>2h
3902            // 6. Consider dexopt output (aggressive only)
3903            // 7. Consider ephemeral apps not used in last week
3904
3905            // 8. Consider cached app data (below quotas)
3906            try {
3907                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3908                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3909            } catch (InstallerException ignored) {
3910            }
3911            if (file.getUsableSpace() >= bytes) return;
3912
3913            // 9. Consider DropBox entries
3914            // 10. Consider ephemeral cookies
3915
3916        } else {
3917            try {
3918                mInstaller.freeCache(volumeUuid, bytes, 0);
3919            } catch (InstallerException ignored) {
3920            }
3921            if (file.getUsableSpace() >= bytes) return;
3922        }
3923
3924        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3925    }
3926
3927    /**
3928     * Update given flags based on encryption status of current user.
3929     */
3930    private int updateFlags(int flags, int userId) {
3931        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3932                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3933            // Caller expressed an explicit opinion about what encryption
3934            // aware/unaware components they want to see, so fall through and
3935            // give them what they want
3936        } else {
3937            // Caller expressed no opinion, so match based on user state
3938            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3939                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3940            } else {
3941                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3942            }
3943        }
3944        return flags;
3945    }
3946
3947    private UserManagerInternal getUserManagerInternal() {
3948        if (mUserManagerInternal == null) {
3949            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3950        }
3951        return mUserManagerInternal;
3952    }
3953
3954    private DeviceIdleController.LocalService getDeviceIdleController() {
3955        if (mDeviceIdleController == null) {
3956            mDeviceIdleController =
3957                    LocalServices.getService(DeviceIdleController.LocalService.class);
3958        }
3959        return mDeviceIdleController;
3960    }
3961
3962    /**
3963     * Update given flags when being used to request {@link PackageInfo}.
3964     */
3965    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3966        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3967        boolean triaged = true;
3968        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3969                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3970            // Caller is asking for component details, so they'd better be
3971            // asking for specific encryption matching behavior, or be triaged
3972            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3973                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3974                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3975                triaged = false;
3976            }
3977        }
3978        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3979                | PackageManager.MATCH_SYSTEM_ONLY
3980                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3981            triaged = false;
3982        }
3983        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3984            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3985                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3986                    + Debug.getCallers(5));
3987        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3988                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3989            // If the caller wants all packages and has a restricted profile associated with it,
3990            // then match all users. This is to make sure that launchers that need to access work
3991            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3992            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3993            flags |= PackageManager.MATCH_ANY_USER;
3994        }
3995        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3996            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3997                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3998        }
3999        return updateFlags(flags, userId);
4000    }
4001
4002    /**
4003     * Update given flags when being used to request {@link ApplicationInfo}.
4004     */
4005    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4006        return updateFlagsForPackage(flags, userId, cookie);
4007    }
4008
4009    /**
4010     * Update given flags when being used to request {@link ComponentInfo}.
4011     */
4012    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4013        if (cookie instanceof Intent) {
4014            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4015                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4016            }
4017        }
4018
4019        boolean triaged = true;
4020        // Caller is asking for component details, so they'd better be
4021        // asking for specific encryption matching behavior, or be triaged
4022        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4023                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4024                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4025            triaged = false;
4026        }
4027        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4028            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4029                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4030        }
4031
4032        return updateFlags(flags, userId);
4033    }
4034
4035    /**
4036     * Update given intent when being used to request {@link ResolveInfo}.
4037     */
4038    private Intent updateIntentForResolve(Intent intent) {
4039        if (intent.getSelector() != null) {
4040            intent = intent.getSelector();
4041        }
4042        if (DEBUG_PREFERRED) {
4043            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4044        }
4045        return intent;
4046    }
4047
4048    /**
4049     * Update given flags when being used to request {@link ResolveInfo}.
4050     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4051     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4052     * flag set. However, this flag is only honoured in three circumstances:
4053     * <ul>
4054     * <li>when called from a system process</li>
4055     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4056     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4057     * action and a {@code android.intent.category.BROWSABLE} category</li>
4058     * </ul>
4059     */
4060    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4061            boolean includeInstantApps) {
4062        // Safe mode means we shouldn't match any third-party components
4063        if (mSafeMode) {
4064            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4065        }
4066        if (getInstantAppPackageName(callingUid) != null) {
4067            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4068            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4069            flags |= PackageManager.MATCH_INSTANT;
4070        } else {
4071            // Otherwise, prevent leaking ephemeral components
4072            final boolean isSpecialProcess =
4073                    callingUid == Process.SYSTEM_UID
4074                    || callingUid == Process.SHELL_UID
4075                    || callingUid == 0;
4076            final boolean allowMatchInstant =
4077                    (includeInstantApps
4078                            && Intent.ACTION_VIEW.equals(intent.getAction())
4079                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4080                            && hasWebURI(intent))
4081                    || isSpecialProcess
4082                    || mContext.checkCallingOrSelfPermission(
4083                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4084            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4085            if (!allowMatchInstant) {
4086                flags &= ~PackageManager.MATCH_INSTANT;
4087            }
4088        }
4089        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4090    }
4091
4092    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4093            int userId) {
4094        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4095        if (ret != null) {
4096            rebaseEnabledOverlays(ret.applicationInfo, userId);
4097        }
4098        return ret;
4099    }
4100
4101    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4102            PackageUserState state, int userId) {
4103        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4104        if (ai != null) {
4105            rebaseEnabledOverlays(ai.applicationInfo, userId);
4106        }
4107        return ai;
4108    }
4109
4110    @Override
4111    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4112        if (!sUserManager.exists(userId)) return null;
4113        flags = updateFlagsForComponent(flags, userId, component);
4114        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4115                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4116        synchronized (mPackages) {
4117            PackageParser.Activity a = mActivities.mActivities.get(component);
4118
4119            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4120            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4121                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4122                if (ps == null) return null;
4123                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4124            }
4125            if (mResolveComponentName.equals(component)) {
4126                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4127                        userId);
4128            }
4129        }
4130        return null;
4131    }
4132
4133    @Override
4134    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4135            String resolvedType) {
4136        synchronized (mPackages) {
4137            if (component.equals(mResolveComponentName)) {
4138                // The resolver supports EVERYTHING!
4139                return true;
4140            }
4141            PackageParser.Activity a = mActivities.mActivities.get(component);
4142            if (a == null) {
4143                return false;
4144            }
4145            for (int i=0; i<a.intents.size(); i++) {
4146                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4147                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4148                    return true;
4149                }
4150            }
4151            return false;
4152        }
4153    }
4154
4155    @Override
4156    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4157        if (!sUserManager.exists(userId)) return null;
4158        flags = updateFlagsForComponent(flags, userId, component);
4159        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4160                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4161        synchronized (mPackages) {
4162            PackageParser.Activity a = mReceivers.mActivities.get(component);
4163            if (DEBUG_PACKAGE_INFO) Log.v(
4164                TAG, "getReceiverInfo " + component + ": " + a);
4165            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4166                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4167                if (ps == null) return null;
4168                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4169            }
4170        }
4171        return null;
4172    }
4173
4174    @Override
4175    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4176        if (!sUserManager.exists(userId)) return null;
4177        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4178
4179        flags = updateFlagsForPackage(flags, userId, null);
4180
4181        final boolean canSeeStaticLibraries =
4182                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4183                        == PERMISSION_GRANTED
4184                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4185                        == PERMISSION_GRANTED
4186                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4187                        == PERMISSION_GRANTED
4188                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4189                        == PERMISSION_GRANTED;
4190
4191        synchronized (mPackages) {
4192            List<SharedLibraryInfo> result = null;
4193
4194            final int libCount = mSharedLibraries.size();
4195            for (int i = 0; i < libCount; i++) {
4196                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4197                if (versionedLib == null) {
4198                    continue;
4199                }
4200
4201                final int versionCount = versionedLib.size();
4202                for (int j = 0; j < versionCount; j++) {
4203                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4204                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4205                        break;
4206                    }
4207                    final long identity = Binder.clearCallingIdentity();
4208                    try {
4209                        // TODO: We will change version code to long, so in the new API it is long
4210                        PackageInfo packageInfo = getPackageInfoVersioned(
4211                                libInfo.getDeclaringPackage(), flags, userId);
4212                        if (packageInfo == null) {
4213                            continue;
4214                        }
4215                    } finally {
4216                        Binder.restoreCallingIdentity(identity);
4217                    }
4218
4219                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4220                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4221                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4222
4223                    if (result == null) {
4224                        result = new ArrayList<>();
4225                    }
4226                    result.add(resLibInfo);
4227                }
4228            }
4229
4230            return result != null ? new ParceledListSlice<>(result) : null;
4231        }
4232    }
4233
4234    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4235            SharedLibraryInfo libInfo, int flags, int userId) {
4236        List<VersionedPackage> versionedPackages = null;
4237        final int packageCount = mSettings.mPackages.size();
4238        for (int i = 0; i < packageCount; i++) {
4239            PackageSetting ps = mSettings.mPackages.valueAt(i);
4240
4241            if (ps == null) {
4242                continue;
4243            }
4244
4245            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4246                continue;
4247            }
4248
4249            final String libName = libInfo.getName();
4250            if (libInfo.isStatic()) {
4251                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4252                if (libIdx < 0) {
4253                    continue;
4254                }
4255                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4256                    continue;
4257                }
4258                if (versionedPackages == null) {
4259                    versionedPackages = new ArrayList<>();
4260                }
4261                // If the dependent is a static shared lib, use the public package name
4262                String dependentPackageName = ps.name;
4263                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4264                    dependentPackageName = ps.pkg.manifestPackageName;
4265                }
4266                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4267            } else if (ps.pkg != null) {
4268                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4269                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4270                    if (versionedPackages == null) {
4271                        versionedPackages = new ArrayList<>();
4272                    }
4273                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4274                }
4275            }
4276        }
4277
4278        return versionedPackages;
4279    }
4280
4281    @Override
4282    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4283        if (!sUserManager.exists(userId)) return null;
4284        flags = updateFlagsForComponent(flags, userId, component);
4285        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4286                false /* requireFullPermission */, false /* checkShell */, "get service info");
4287        synchronized (mPackages) {
4288            PackageParser.Service s = mServices.mServices.get(component);
4289            if (DEBUG_PACKAGE_INFO) Log.v(
4290                TAG, "getServiceInfo " + component + ": " + s);
4291            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4292                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4293                if (ps == null) return null;
4294                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4295                        ps.readUserState(userId), userId);
4296                if (si != null) {
4297                    rebaseEnabledOverlays(si.applicationInfo, userId);
4298                }
4299                return si;
4300            }
4301        }
4302        return null;
4303    }
4304
4305    @Override
4306    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4307        if (!sUserManager.exists(userId)) return null;
4308        flags = updateFlagsForComponent(flags, userId, component);
4309        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4310                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4311        synchronized (mPackages) {
4312            PackageParser.Provider p = mProviders.mProviders.get(component);
4313            if (DEBUG_PACKAGE_INFO) Log.v(
4314                TAG, "getProviderInfo " + component + ": " + p);
4315            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4316                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4317                if (ps == null) return null;
4318                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4319                        ps.readUserState(userId), userId);
4320                if (pi != null) {
4321                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4322                }
4323                return pi;
4324            }
4325        }
4326        return null;
4327    }
4328
4329    @Override
4330    public String[] getSystemSharedLibraryNames() {
4331        synchronized (mPackages) {
4332            Set<String> libs = null;
4333            final int libCount = mSharedLibraries.size();
4334            for (int i = 0; i < libCount; i++) {
4335                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4336                if (versionedLib == null) {
4337                    continue;
4338                }
4339                final int versionCount = versionedLib.size();
4340                for (int j = 0; j < versionCount; j++) {
4341                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4342                    if (!libEntry.info.isStatic()) {
4343                        if (libs == null) {
4344                            libs = new ArraySet<>();
4345                        }
4346                        libs.add(libEntry.info.getName());
4347                        break;
4348                    }
4349                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4350                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4351                            UserHandle.getUserId(Binder.getCallingUid()))) {
4352                        if (libs == null) {
4353                            libs = new ArraySet<>();
4354                        }
4355                        libs.add(libEntry.info.getName());
4356                        break;
4357                    }
4358                }
4359            }
4360
4361            if (libs != null) {
4362                String[] libsArray = new String[libs.size()];
4363                libs.toArray(libsArray);
4364                return libsArray;
4365            }
4366
4367            return null;
4368        }
4369    }
4370
4371    @Override
4372    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4373        synchronized (mPackages) {
4374            return mServicesSystemSharedLibraryPackageName;
4375        }
4376    }
4377
4378    @Override
4379    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4380        synchronized (mPackages) {
4381            return mSharedSystemSharedLibraryPackageName;
4382        }
4383    }
4384
4385    private void updateSequenceNumberLP(String packageName, int[] userList) {
4386        for (int i = userList.length - 1; i >= 0; --i) {
4387            final int userId = userList[i];
4388            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4389            if (changedPackages == null) {
4390                changedPackages = new SparseArray<>();
4391                mChangedPackages.put(userId, changedPackages);
4392            }
4393            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4394            if (sequenceNumbers == null) {
4395                sequenceNumbers = new HashMap<>();
4396                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4397            }
4398            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4399            if (sequenceNumber != null) {
4400                changedPackages.remove(sequenceNumber);
4401            }
4402            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4403            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4404        }
4405        mChangedPackagesSequenceNumber++;
4406    }
4407
4408    @Override
4409    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4410        synchronized (mPackages) {
4411            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4412                return null;
4413            }
4414            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4415            if (changedPackages == null) {
4416                return null;
4417            }
4418            final List<String> packageNames =
4419                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4420            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4421                final String packageName = changedPackages.get(i);
4422                if (packageName != null) {
4423                    packageNames.add(packageName);
4424                }
4425            }
4426            return packageNames.isEmpty()
4427                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4428        }
4429    }
4430
4431    @Override
4432    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4433        ArrayList<FeatureInfo> res;
4434        synchronized (mAvailableFeatures) {
4435            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4436            res.addAll(mAvailableFeatures.values());
4437        }
4438        final FeatureInfo fi = new FeatureInfo();
4439        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4440                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4441        res.add(fi);
4442
4443        return new ParceledListSlice<>(res);
4444    }
4445
4446    @Override
4447    public boolean hasSystemFeature(String name, int version) {
4448        synchronized (mAvailableFeatures) {
4449            final FeatureInfo feat = mAvailableFeatures.get(name);
4450            if (feat == null) {
4451                return false;
4452            } else {
4453                return feat.version >= version;
4454            }
4455        }
4456    }
4457
4458    @Override
4459    public int checkPermission(String permName, String pkgName, int userId) {
4460        if (!sUserManager.exists(userId)) {
4461            return PackageManager.PERMISSION_DENIED;
4462        }
4463
4464        synchronized (mPackages) {
4465            final PackageParser.Package p = mPackages.get(pkgName);
4466            if (p != null && p.mExtras != null) {
4467                final PackageSetting ps = (PackageSetting) p.mExtras;
4468                final PermissionsState permissionsState = ps.getPermissionsState();
4469                if (permissionsState.hasPermission(permName, userId)) {
4470                    return PackageManager.PERMISSION_GRANTED;
4471                }
4472                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4473                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4474                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4475                    return PackageManager.PERMISSION_GRANTED;
4476                }
4477            }
4478        }
4479
4480        return PackageManager.PERMISSION_DENIED;
4481    }
4482
4483    @Override
4484    public int checkUidPermission(String permName, int uid) {
4485        final int userId = UserHandle.getUserId(uid);
4486
4487        if (!sUserManager.exists(userId)) {
4488            return PackageManager.PERMISSION_DENIED;
4489        }
4490
4491        synchronized (mPackages) {
4492            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4493            if (obj != null) {
4494                final SettingBase ps = (SettingBase) obj;
4495                final PermissionsState permissionsState = ps.getPermissionsState();
4496                if (permissionsState.hasPermission(permName, userId)) {
4497                    return PackageManager.PERMISSION_GRANTED;
4498                }
4499                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4500                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4501                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4502                    return PackageManager.PERMISSION_GRANTED;
4503                }
4504            } else {
4505                ArraySet<String> perms = mSystemPermissions.get(uid);
4506                if (perms != null) {
4507                    if (perms.contains(permName)) {
4508                        return PackageManager.PERMISSION_GRANTED;
4509                    }
4510                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4511                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4512                        return PackageManager.PERMISSION_GRANTED;
4513                    }
4514                }
4515            }
4516        }
4517
4518        return PackageManager.PERMISSION_DENIED;
4519    }
4520
4521    @Override
4522    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4523        if (UserHandle.getCallingUserId() != userId) {
4524            mContext.enforceCallingPermission(
4525                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4526                    "isPermissionRevokedByPolicy for user " + userId);
4527        }
4528
4529        if (checkPermission(permission, packageName, userId)
4530                == PackageManager.PERMISSION_GRANTED) {
4531            return false;
4532        }
4533
4534        final long identity = Binder.clearCallingIdentity();
4535        try {
4536            final int flags = getPermissionFlags(permission, packageName, userId);
4537            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4538        } finally {
4539            Binder.restoreCallingIdentity(identity);
4540        }
4541    }
4542
4543    @Override
4544    public String getPermissionControllerPackageName() {
4545        synchronized (mPackages) {
4546            return mRequiredInstallerPackage;
4547        }
4548    }
4549
4550    /**
4551     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4552     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4553     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4554     * @param message the message to log on security exception
4555     */
4556    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4557            boolean checkShell, String message) {
4558        if (userId < 0) {
4559            throw new IllegalArgumentException("Invalid userId " + userId);
4560        }
4561        if (checkShell) {
4562            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4563        }
4564        if (userId == UserHandle.getUserId(callingUid)) return;
4565        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4566            if (requireFullPermission) {
4567                mContext.enforceCallingOrSelfPermission(
4568                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4569            } else {
4570                try {
4571                    mContext.enforceCallingOrSelfPermission(
4572                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4573                } catch (SecurityException se) {
4574                    mContext.enforceCallingOrSelfPermission(
4575                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4576                }
4577            }
4578        }
4579    }
4580
4581    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4582        if (callingUid == Process.SHELL_UID) {
4583            if (userHandle >= 0
4584                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4585                throw new SecurityException("Shell does not have permission to access user "
4586                        + userHandle);
4587            } else if (userHandle < 0) {
4588                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4589                        + Debug.getCallers(3));
4590            }
4591        }
4592    }
4593
4594    private BasePermission findPermissionTreeLP(String permName) {
4595        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4596            if (permName.startsWith(bp.name) &&
4597                    permName.length() > bp.name.length() &&
4598                    permName.charAt(bp.name.length()) == '.') {
4599                return bp;
4600            }
4601        }
4602        return null;
4603    }
4604
4605    private BasePermission checkPermissionTreeLP(String permName) {
4606        if (permName != null) {
4607            BasePermission bp = findPermissionTreeLP(permName);
4608            if (bp != null) {
4609                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4610                    return bp;
4611                }
4612                throw new SecurityException("Calling uid "
4613                        + Binder.getCallingUid()
4614                        + " is not allowed to add to permission tree "
4615                        + bp.name + " owned by uid " + bp.uid);
4616            }
4617        }
4618        throw new SecurityException("No permission tree found for " + permName);
4619    }
4620
4621    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4622        if (s1 == null) {
4623            return s2 == null;
4624        }
4625        if (s2 == null) {
4626            return false;
4627        }
4628        if (s1.getClass() != s2.getClass()) {
4629            return false;
4630        }
4631        return s1.equals(s2);
4632    }
4633
4634    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4635        if (pi1.icon != pi2.icon) return false;
4636        if (pi1.logo != pi2.logo) return false;
4637        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4638        if (!compareStrings(pi1.name, pi2.name)) return false;
4639        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4640        // We'll take care of setting this one.
4641        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4642        // These are not currently stored in settings.
4643        //if (!compareStrings(pi1.group, pi2.group)) return false;
4644        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4645        //if (pi1.labelRes != pi2.labelRes) return false;
4646        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4647        return true;
4648    }
4649
4650    int permissionInfoFootprint(PermissionInfo info) {
4651        int size = info.name.length();
4652        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4653        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4654        return size;
4655    }
4656
4657    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4658        int size = 0;
4659        for (BasePermission perm : mSettings.mPermissions.values()) {
4660            if (perm.uid == tree.uid) {
4661                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4662            }
4663        }
4664        return size;
4665    }
4666
4667    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4668        // We calculate the max size of permissions defined by this uid and throw
4669        // if that plus the size of 'info' would exceed our stated maximum.
4670        if (tree.uid != Process.SYSTEM_UID) {
4671            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4672            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4673                throw new SecurityException("Permission tree size cap exceeded");
4674            }
4675        }
4676    }
4677
4678    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4679        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4680            throw new SecurityException("Label must be specified in permission");
4681        }
4682        BasePermission tree = checkPermissionTreeLP(info.name);
4683        BasePermission bp = mSettings.mPermissions.get(info.name);
4684        boolean added = bp == null;
4685        boolean changed = true;
4686        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4687        if (added) {
4688            enforcePermissionCapLocked(info, tree);
4689            bp = new BasePermission(info.name, tree.sourcePackage,
4690                    BasePermission.TYPE_DYNAMIC);
4691        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4692            throw new SecurityException(
4693                    "Not allowed to modify non-dynamic permission "
4694                    + info.name);
4695        } else {
4696            if (bp.protectionLevel == fixedLevel
4697                    && bp.perm.owner.equals(tree.perm.owner)
4698                    && bp.uid == tree.uid
4699                    && comparePermissionInfos(bp.perm.info, info)) {
4700                changed = false;
4701            }
4702        }
4703        bp.protectionLevel = fixedLevel;
4704        info = new PermissionInfo(info);
4705        info.protectionLevel = fixedLevel;
4706        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4707        bp.perm.info.packageName = tree.perm.info.packageName;
4708        bp.uid = tree.uid;
4709        if (added) {
4710            mSettings.mPermissions.put(info.name, bp);
4711        }
4712        if (changed) {
4713            if (!async) {
4714                mSettings.writeLPr();
4715            } else {
4716                scheduleWriteSettingsLocked();
4717            }
4718        }
4719        return added;
4720    }
4721
4722    @Override
4723    public boolean addPermission(PermissionInfo info) {
4724        synchronized (mPackages) {
4725            return addPermissionLocked(info, false);
4726        }
4727    }
4728
4729    @Override
4730    public boolean addPermissionAsync(PermissionInfo info) {
4731        synchronized (mPackages) {
4732            return addPermissionLocked(info, true);
4733        }
4734    }
4735
4736    @Override
4737    public void removePermission(String name) {
4738        synchronized (mPackages) {
4739            checkPermissionTreeLP(name);
4740            BasePermission bp = mSettings.mPermissions.get(name);
4741            if (bp != null) {
4742                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4743                    throw new SecurityException(
4744                            "Not allowed to modify non-dynamic permission "
4745                            + name);
4746                }
4747                mSettings.mPermissions.remove(name);
4748                mSettings.writeLPr();
4749            }
4750        }
4751    }
4752
4753    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4754            BasePermission bp) {
4755        int index = pkg.requestedPermissions.indexOf(bp.name);
4756        if (index == -1) {
4757            throw new SecurityException("Package " + pkg.packageName
4758                    + " has not requested permission " + bp.name);
4759        }
4760        if (!bp.isRuntime() && !bp.isDevelopment()) {
4761            throw new SecurityException("Permission " + bp.name
4762                    + " is not a changeable permission type");
4763        }
4764    }
4765
4766    @Override
4767    public void grantRuntimePermission(String packageName, String name, final int userId) {
4768        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4769    }
4770
4771    private void grantRuntimePermission(String packageName, String name, final int userId,
4772            boolean overridePolicy) {
4773        if (!sUserManager.exists(userId)) {
4774            Log.e(TAG, "No such user:" + userId);
4775            return;
4776        }
4777
4778        mContext.enforceCallingOrSelfPermission(
4779                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4780                "grantRuntimePermission");
4781
4782        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4783                true /* requireFullPermission */, true /* checkShell */,
4784                "grantRuntimePermission");
4785
4786        final int uid;
4787        final SettingBase sb;
4788
4789        synchronized (mPackages) {
4790            final PackageParser.Package pkg = mPackages.get(packageName);
4791            if (pkg == null) {
4792                throw new IllegalArgumentException("Unknown package: " + packageName);
4793            }
4794
4795            final BasePermission bp = mSettings.mPermissions.get(name);
4796            if (bp == null) {
4797                throw new IllegalArgumentException("Unknown permission: " + name);
4798            }
4799
4800            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4801
4802            // If a permission review is required for legacy apps we represent
4803            // their permissions as always granted runtime ones since we need
4804            // to keep the review required permission flag per user while an
4805            // install permission's state is shared across all users.
4806            if (mPermissionReviewRequired
4807                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4808                    && bp.isRuntime()) {
4809                return;
4810            }
4811
4812            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4813            sb = (SettingBase) pkg.mExtras;
4814            if (sb == null) {
4815                throw new IllegalArgumentException("Unknown package: " + packageName);
4816            }
4817
4818            final PermissionsState permissionsState = sb.getPermissionsState();
4819
4820            final int flags = permissionsState.getPermissionFlags(name, userId);
4821            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4822                throw new SecurityException("Cannot grant system fixed permission "
4823                        + name + " for package " + packageName);
4824            }
4825            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4826                throw new SecurityException("Cannot grant policy fixed permission "
4827                        + name + " for package " + packageName);
4828            }
4829
4830            if (bp.isDevelopment()) {
4831                // Development permissions must be handled specially, since they are not
4832                // normal runtime permissions.  For now they apply to all users.
4833                if (permissionsState.grantInstallPermission(bp) !=
4834                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4835                    scheduleWriteSettingsLocked();
4836                }
4837                return;
4838            }
4839
4840            final PackageSetting ps = mSettings.mPackages.get(packageName);
4841            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4842                throw new SecurityException("Cannot grant non-ephemeral permission"
4843                        + name + " for package " + packageName);
4844            }
4845
4846            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4847                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4848                return;
4849            }
4850
4851            final int result = permissionsState.grantRuntimePermission(bp, userId);
4852            switch (result) {
4853                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4854                    return;
4855                }
4856
4857                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4858                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4859                    mHandler.post(new Runnable() {
4860                        @Override
4861                        public void run() {
4862                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4863                        }
4864                    });
4865                }
4866                break;
4867            }
4868
4869            if (bp.isRuntime()) {
4870                logPermissionGranted(mContext, name, packageName);
4871            }
4872
4873            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4874
4875            // Not critical if that is lost - app has to request again.
4876            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4877        }
4878
4879        // Only need to do this if user is initialized. Otherwise it's a new user
4880        // and there are no processes running as the user yet and there's no need
4881        // to make an expensive call to remount processes for the changed permissions.
4882        if (READ_EXTERNAL_STORAGE.equals(name)
4883                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4884            final long token = Binder.clearCallingIdentity();
4885            try {
4886                if (sUserManager.isInitialized(userId)) {
4887                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4888                            StorageManagerInternal.class);
4889                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4890                }
4891            } finally {
4892                Binder.restoreCallingIdentity(token);
4893            }
4894        }
4895    }
4896
4897    @Override
4898    public void revokeRuntimePermission(String packageName, String name, int userId) {
4899        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4900    }
4901
4902    private void revokeRuntimePermission(String packageName, String name, int userId,
4903            boolean overridePolicy) {
4904        if (!sUserManager.exists(userId)) {
4905            Log.e(TAG, "No such user:" + userId);
4906            return;
4907        }
4908
4909        mContext.enforceCallingOrSelfPermission(
4910                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4911                "revokeRuntimePermission");
4912
4913        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4914                true /* requireFullPermission */, true /* checkShell */,
4915                "revokeRuntimePermission");
4916
4917        final int appId;
4918
4919        synchronized (mPackages) {
4920            final PackageParser.Package pkg = mPackages.get(packageName);
4921            if (pkg == null) {
4922                throw new IllegalArgumentException("Unknown package: " + packageName);
4923            }
4924
4925            final BasePermission bp = mSettings.mPermissions.get(name);
4926            if (bp == null) {
4927                throw new IllegalArgumentException("Unknown permission: " + name);
4928            }
4929
4930            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4931
4932            // If a permission review is required for legacy apps we represent
4933            // their permissions as always granted runtime ones since we need
4934            // to keep the review required permission flag per user while an
4935            // install permission's state is shared across all users.
4936            if (mPermissionReviewRequired
4937                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4938                    && bp.isRuntime()) {
4939                return;
4940            }
4941
4942            SettingBase sb = (SettingBase) pkg.mExtras;
4943            if (sb == null) {
4944                throw new IllegalArgumentException("Unknown package: " + packageName);
4945            }
4946
4947            final PermissionsState permissionsState = sb.getPermissionsState();
4948
4949            final int flags = permissionsState.getPermissionFlags(name, userId);
4950            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4951                throw new SecurityException("Cannot revoke system fixed permission "
4952                        + name + " for package " + packageName);
4953            }
4954            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4955                throw new SecurityException("Cannot revoke policy fixed permission "
4956                        + name + " for package " + packageName);
4957            }
4958
4959            if (bp.isDevelopment()) {
4960                // Development permissions must be handled specially, since they are not
4961                // normal runtime permissions.  For now they apply to all users.
4962                if (permissionsState.revokeInstallPermission(bp) !=
4963                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4964                    scheduleWriteSettingsLocked();
4965                }
4966                return;
4967            }
4968
4969            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4970                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4971                return;
4972            }
4973
4974            if (bp.isRuntime()) {
4975                logPermissionRevoked(mContext, name, packageName);
4976            }
4977
4978            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4979
4980            // Critical, after this call app should never have the permission.
4981            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4982
4983            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4984        }
4985
4986        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4987    }
4988
4989    /**
4990     * Get the first event id for the permission.
4991     *
4992     * <p>There are four events for each permission: <ul>
4993     *     <li>Request permission: first id + 0</li>
4994     *     <li>Grant permission: first id + 1</li>
4995     *     <li>Request for permission denied: first id + 2</li>
4996     *     <li>Revoke permission: first id + 3</li>
4997     * </ul></p>
4998     *
4999     * @param name name of the permission
5000     *
5001     * @return The first event id for the permission
5002     */
5003    private static int getBaseEventId(@NonNull String name) {
5004        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5005
5006        if (eventIdIndex == -1) {
5007            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5008                    || "user".equals(Build.TYPE)) {
5009                Log.i(TAG, "Unknown permission " + name);
5010
5011                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5012            } else {
5013                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5014                //
5015                // Also update
5016                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5017                // - metrics_constants.proto
5018                throw new IllegalStateException("Unknown permission " + name);
5019            }
5020        }
5021
5022        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5023    }
5024
5025    /**
5026     * Log that a permission was revoked.
5027     *
5028     * @param context Context of the caller
5029     * @param name name of the permission
5030     * @param packageName package permission if for
5031     */
5032    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5033            @NonNull String packageName) {
5034        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5035    }
5036
5037    /**
5038     * Log that a permission request was granted.
5039     *
5040     * @param context Context of the caller
5041     * @param name name of the permission
5042     * @param packageName package permission if for
5043     */
5044    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5045            @NonNull String packageName) {
5046        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5047    }
5048
5049    @Override
5050    public void resetRuntimePermissions() {
5051        mContext.enforceCallingOrSelfPermission(
5052                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5053                "revokeRuntimePermission");
5054
5055        int callingUid = Binder.getCallingUid();
5056        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5057            mContext.enforceCallingOrSelfPermission(
5058                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5059                    "resetRuntimePermissions");
5060        }
5061
5062        synchronized (mPackages) {
5063            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5064            for (int userId : UserManagerService.getInstance().getUserIds()) {
5065                final int packageCount = mPackages.size();
5066                for (int i = 0; i < packageCount; i++) {
5067                    PackageParser.Package pkg = mPackages.valueAt(i);
5068                    if (!(pkg.mExtras instanceof PackageSetting)) {
5069                        continue;
5070                    }
5071                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5072                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5073                }
5074            }
5075        }
5076    }
5077
5078    @Override
5079    public int getPermissionFlags(String name, String packageName, int userId) {
5080        if (!sUserManager.exists(userId)) {
5081            return 0;
5082        }
5083
5084        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5085
5086        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5087                true /* requireFullPermission */, false /* checkShell */,
5088                "getPermissionFlags");
5089
5090        synchronized (mPackages) {
5091            final PackageParser.Package pkg = mPackages.get(packageName);
5092            if (pkg == null) {
5093                return 0;
5094            }
5095
5096            final BasePermission bp = mSettings.mPermissions.get(name);
5097            if (bp == null) {
5098                return 0;
5099            }
5100
5101            SettingBase sb = (SettingBase) pkg.mExtras;
5102            if (sb == null) {
5103                return 0;
5104            }
5105
5106            PermissionsState permissionsState = sb.getPermissionsState();
5107            return permissionsState.getPermissionFlags(name, userId);
5108        }
5109    }
5110
5111    @Override
5112    public void updatePermissionFlags(String name, String packageName, int flagMask,
5113            int flagValues, int userId) {
5114        if (!sUserManager.exists(userId)) {
5115            return;
5116        }
5117
5118        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5119
5120        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5121                true /* requireFullPermission */, true /* checkShell */,
5122                "updatePermissionFlags");
5123
5124        // Only the system can change these flags and nothing else.
5125        if (getCallingUid() != Process.SYSTEM_UID) {
5126            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5127            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5128            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5129            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5130            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5131        }
5132
5133        synchronized (mPackages) {
5134            final PackageParser.Package pkg = mPackages.get(packageName);
5135            if (pkg == null) {
5136                throw new IllegalArgumentException("Unknown package: " + packageName);
5137            }
5138
5139            final BasePermission bp = mSettings.mPermissions.get(name);
5140            if (bp == null) {
5141                throw new IllegalArgumentException("Unknown permission: " + name);
5142            }
5143
5144            SettingBase sb = (SettingBase) pkg.mExtras;
5145            if (sb == null) {
5146                throw new IllegalArgumentException("Unknown package: " + packageName);
5147            }
5148
5149            PermissionsState permissionsState = sb.getPermissionsState();
5150
5151            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5152
5153            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5154                // Install and runtime permissions are stored in different places,
5155                // so figure out what permission changed and persist the change.
5156                if (permissionsState.getInstallPermissionState(name) != null) {
5157                    scheduleWriteSettingsLocked();
5158                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5159                        || hadState) {
5160                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5161                }
5162            }
5163        }
5164    }
5165
5166    /**
5167     * Update the permission flags for all packages and runtime permissions of a user in order
5168     * to allow device or profile owner to remove POLICY_FIXED.
5169     */
5170    @Override
5171    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5172        if (!sUserManager.exists(userId)) {
5173            return;
5174        }
5175
5176        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5177
5178        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5179                true /* requireFullPermission */, true /* checkShell */,
5180                "updatePermissionFlagsForAllApps");
5181
5182        // Only the system can change system fixed flags.
5183        if (getCallingUid() != Process.SYSTEM_UID) {
5184            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5185            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5186        }
5187
5188        synchronized (mPackages) {
5189            boolean changed = false;
5190            final int packageCount = mPackages.size();
5191            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5192                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5193                SettingBase sb = (SettingBase) pkg.mExtras;
5194                if (sb == null) {
5195                    continue;
5196                }
5197                PermissionsState permissionsState = sb.getPermissionsState();
5198                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5199                        userId, flagMask, flagValues);
5200            }
5201            if (changed) {
5202                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5203            }
5204        }
5205    }
5206
5207    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5208        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5209                != PackageManager.PERMISSION_GRANTED
5210            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5211                != PackageManager.PERMISSION_GRANTED) {
5212            throw new SecurityException(message + " requires "
5213                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5214                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5215        }
5216    }
5217
5218    @Override
5219    public boolean shouldShowRequestPermissionRationale(String permissionName,
5220            String packageName, int userId) {
5221        if (UserHandle.getCallingUserId() != userId) {
5222            mContext.enforceCallingPermission(
5223                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5224                    "canShowRequestPermissionRationale for user " + userId);
5225        }
5226
5227        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5228        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5229            return false;
5230        }
5231
5232        if (checkPermission(permissionName, packageName, userId)
5233                == PackageManager.PERMISSION_GRANTED) {
5234            return false;
5235        }
5236
5237        final int flags;
5238
5239        final long identity = Binder.clearCallingIdentity();
5240        try {
5241            flags = getPermissionFlags(permissionName,
5242                    packageName, userId);
5243        } finally {
5244            Binder.restoreCallingIdentity(identity);
5245        }
5246
5247        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5248                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5249                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5250
5251        if ((flags & fixedFlags) != 0) {
5252            return false;
5253        }
5254
5255        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5256    }
5257
5258    @Override
5259    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5260        mContext.enforceCallingOrSelfPermission(
5261                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5262                "addOnPermissionsChangeListener");
5263
5264        synchronized (mPackages) {
5265            mOnPermissionChangeListeners.addListenerLocked(listener);
5266        }
5267    }
5268
5269    @Override
5270    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5271        synchronized (mPackages) {
5272            mOnPermissionChangeListeners.removeListenerLocked(listener);
5273        }
5274    }
5275
5276    @Override
5277    public boolean isProtectedBroadcast(String actionName) {
5278        synchronized (mPackages) {
5279            if (mProtectedBroadcasts.contains(actionName)) {
5280                return true;
5281            } else if (actionName != null) {
5282                // TODO: remove these terrible hacks
5283                if (actionName.startsWith("android.net.netmon.lingerExpired")
5284                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5285                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5286                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5287                    return true;
5288                }
5289            }
5290        }
5291        return false;
5292    }
5293
5294    @Override
5295    public int checkSignatures(String pkg1, String pkg2) {
5296        synchronized (mPackages) {
5297            final PackageParser.Package p1 = mPackages.get(pkg1);
5298            final PackageParser.Package p2 = mPackages.get(pkg2);
5299            if (p1 == null || p1.mExtras == null
5300                    || p2 == null || p2.mExtras == null) {
5301                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5302            }
5303            return compareSignatures(p1.mSignatures, p2.mSignatures);
5304        }
5305    }
5306
5307    @Override
5308    public int checkUidSignatures(int uid1, int uid2) {
5309        // Map to base uids.
5310        uid1 = UserHandle.getAppId(uid1);
5311        uid2 = UserHandle.getAppId(uid2);
5312        // reader
5313        synchronized (mPackages) {
5314            Signature[] s1;
5315            Signature[] s2;
5316            Object obj = mSettings.getUserIdLPr(uid1);
5317            if (obj != null) {
5318                if (obj instanceof SharedUserSetting) {
5319                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5320                } else if (obj instanceof PackageSetting) {
5321                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5322                } else {
5323                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5324                }
5325            } else {
5326                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5327            }
5328            obj = mSettings.getUserIdLPr(uid2);
5329            if (obj != null) {
5330                if (obj instanceof SharedUserSetting) {
5331                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5332                } else if (obj instanceof PackageSetting) {
5333                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5334                } else {
5335                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5336                }
5337            } else {
5338                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5339            }
5340            return compareSignatures(s1, s2);
5341        }
5342    }
5343
5344    /**
5345     * This method should typically only be used when granting or revoking
5346     * permissions, since the app may immediately restart after this call.
5347     * <p>
5348     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5349     * guard your work against the app being relaunched.
5350     */
5351    private void killUid(int appId, int userId, String reason) {
5352        final long identity = Binder.clearCallingIdentity();
5353        try {
5354            IActivityManager am = ActivityManager.getService();
5355            if (am != null) {
5356                try {
5357                    am.killUid(appId, userId, reason);
5358                } catch (RemoteException e) {
5359                    /* ignore - same process */
5360                }
5361            }
5362        } finally {
5363            Binder.restoreCallingIdentity(identity);
5364        }
5365    }
5366
5367    /**
5368     * Compares two sets of signatures. Returns:
5369     * <br />
5370     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5371     * <br />
5372     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5373     * <br />
5374     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5375     * <br />
5376     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5377     * <br />
5378     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5379     */
5380    static int compareSignatures(Signature[] s1, Signature[] s2) {
5381        if (s1 == null) {
5382            return s2 == null
5383                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5384                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5385        }
5386
5387        if (s2 == null) {
5388            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5389        }
5390
5391        if (s1.length != s2.length) {
5392            return PackageManager.SIGNATURE_NO_MATCH;
5393        }
5394
5395        // Since both signature sets are of size 1, we can compare without HashSets.
5396        if (s1.length == 1) {
5397            return s1[0].equals(s2[0]) ?
5398                    PackageManager.SIGNATURE_MATCH :
5399                    PackageManager.SIGNATURE_NO_MATCH;
5400        }
5401
5402        ArraySet<Signature> set1 = new ArraySet<Signature>();
5403        for (Signature sig : s1) {
5404            set1.add(sig);
5405        }
5406        ArraySet<Signature> set2 = new ArraySet<Signature>();
5407        for (Signature sig : s2) {
5408            set2.add(sig);
5409        }
5410        // Make sure s2 contains all signatures in s1.
5411        if (set1.equals(set2)) {
5412            return PackageManager.SIGNATURE_MATCH;
5413        }
5414        return PackageManager.SIGNATURE_NO_MATCH;
5415    }
5416
5417    /**
5418     * If the database version for this type of package (internal storage or
5419     * external storage) is less than the version where package signatures
5420     * were updated, return true.
5421     */
5422    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5423        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5424        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5425    }
5426
5427    /**
5428     * Used for backward compatibility to make sure any packages with
5429     * certificate chains get upgraded to the new style. {@code existingSigs}
5430     * will be in the old format (since they were stored on disk from before the
5431     * system upgrade) and {@code scannedSigs} will be in the newer format.
5432     */
5433    private int compareSignaturesCompat(PackageSignatures existingSigs,
5434            PackageParser.Package scannedPkg) {
5435        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5436            return PackageManager.SIGNATURE_NO_MATCH;
5437        }
5438
5439        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5440        for (Signature sig : existingSigs.mSignatures) {
5441            existingSet.add(sig);
5442        }
5443        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5444        for (Signature sig : scannedPkg.mSignatures) {
5445            try {
5446                Signature[] chainSignatures = sig.getChainSignatures();
5447                for (Signature chainSig : chainSignatures) {
5448                    scannedCompatSet.add(chainSig);
5449                }
5450            } catch (CertificateEncodingException e) {
5451                scannedCompatSet.add(sig);
5452            }
5453        }
5454        /*
5455         * Make sure the expanded scanned set contains all signatures in the
5456         * existing one.
5457         */
5458        if (scannedCompatSet.equals(existingSet)) {
5459            // Migrate the old signatures to the new scheme.
5460            existingSigs.assignSignatures(scannedPkg.mSignatures);
5461            // The new KeySets will be re-added later in the scanning process.
5462            synchronized (mPackages) {
5463                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5464            }
5465            return PackageManager.SIGNATURE_MATCH;
5466        }
5467        return PackageManager.SIGNATURE_NO_MATCH;
5468    }
5469
5470    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5471        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5472        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5473    }
5474
5475    private int compareSignaturesRecover(PackageSignatures existingSigs,
5476            PackageParser.Package scannedPkg) {
5477        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5478            return PackageManager.SIGNATURE_NO_MATCH;
5479        }
5480
5481        String msg = null;
5482        try {
5483            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5484                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5485                        + scannedPkg.packageName);
5486                return PackageManager.SIGNATURE_MATCH;
5487            }
5488        } catch (CertificateException e) {
5489            msg = e.getMessage();
5490        }
5491
5492        logCriticalInfo(Log.INFO,
5493                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5494        return PackageManager.SIGNATURE_NO_MATCH;
5495    }
5496
5497    @Override
5498    public List<String> getAllPackages() {
5499        synchronized (mPackages) {
5500            return new ArrayList<String>(mPackages.keySet());
5501        }
5502    }
5503
5504    @Override
5505    public String[] getPackagesForUid(int uid) {
5506        final int userId = UserHandle.getUserId(uid);
5507        uid = UserHandle.getAppId(uid);
5508        // reader
5509        synchronized (mPackages) {
5510            Object obj = mSettings.getUserIdLPr(uid);
5511            if (obj instanceof SharedUserSetting) {
5512                final SharedUserSetting sus = (SharedUserSetting) obj;
5513                final int N = sus.packages.size();
5514                String[] res = new String[N];
5515                final Iterator<PackageSetting> it = sus.packages.iterator();
5516                int i = 0;
5517                while (it.hasNext()) {
5518                    PackageSetting ps = it.next();
5519                    if (ps.getInstalled(userId)) {
5520                        res[i++] = ps.name;
5521                    } else {
5522                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5523                    }
5524                }
5525                return res;
5526            } else if (obj instanceof PackageSetting) {
5527                final PackageSetting ps = (PackageSetting) obj;
5528                if (ps.getInstalled(userId)) {
5529                    return new String[]{ps.name};
5530                }
5531            }
5532        }
5533        return null;
5534    }
5535
5536    @Override
5537    public String getNameForUid(int uid) {
5538        // reader
5539        synchronized (mPackages) {
5540            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5541            if (obj instanceof SharedUserSetting) {
5542                final SharedUserSetting sus = (SharedUserSetting) obj;
5543                return sus.name + ":" + sus.userId;
5544            } else if (obj instanceof PackageSetting) {
5545                final PackageSetting ps = (PackageSetting) obj;
5546                return ps.name;
5547            }
5548        }
5549        return null;
5550    }
5551
5552    @Override
5553    public int getUidForSharedUser(String sharedUserName) {
5554        if(sharedUserName == null) {
5555            return -1;
5556        }
5557        // reader
5558        synchronized (mPackages) {
5559            SharedUserSetting suid;
5560            try {
5561                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5562                if (suid != null) {
5563                    return suid.userId;
5564                }
5565            } catch (PackageManagerException ignore) {
5566                // can't happen, but, still need to catch it
5567            }
5568            return -1;
5569        }
5570    }
5571
5572    @Override
5573    public int getFlagsForUid(int uid) {
5574        synchronized (mPackages) {
5575            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5576            if (obj instanceof SharedUserSetting) {
5577                final SharedUserSetting sus = (SharedUserSetting) obj;
5578                return sus.pkgFlags;
5579            } else if (obj instanceof PackageSetting) {
5580                final PackageSetting ps = (PackageSetting) obj;
5581                return ps.pkgFlags;
5582            }
5583        }
5584        return 0;
5585    }
5586
5587    @Override
5588    public int getPrivateFlagsForUid(int uid) {
5589        synchronized (mPackages) {
5590            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5591            if (obj instanceof SharedUserSetting) {
5592                final SharedUserSetting sus = (SharedUserSetting) obj;
5593                return sus.pkgPrivateFlags;
5594            } else if (obj instanceof PackageSetting) {
5595                final PackageSetting ps = (PackageSetting) obj;
5596                return ps.pkgPrivateFlags;
5597            }
5598        }
5599        return 0;
5600    }
5601
5602    @Override
5603    public boolean isUidPrivileged(int uid) {
5604        uid = UserHandle.getAppId(uid);
5605        // reader
5606        synchronized (mPackages) {
5607            Object obj = mSettings.getUserIdLPr(uid);
5608            if (obj instanceof SharedUserSetting) {
5609                final SharedUserSetting sus = (SharedUserSetting) obj;
5610                final Iterator<PackageSetting> it = sus.packages.iterator();
5611                while (it.hasNext()) {
5612                    if (it.next().isPrivileged()) {
5613                        return true;
5614                    }
5615                }
5616            } else if (obj instanceof PackageSetting) {
5617                final PackageSetting ps = (PackageSetting) obj;
5618                return ps.isPrivileged();
5619            }
5620        }
5621        return false;
5622    }
5623
5624    @Override
5625    public String[] getAppOpPermissionPackages(String permissionName) {
5626        synchronized (mPackages) {
5627            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5628            if (pkgs == null) {
5629                return null;
5630            }
5631            return pkgs.toArray(new String[pkgs.size()]);
5632        }
5633    }
5634
5635    @Override
5636    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5637            int flags, int userId) {
5638        return resolveIntentInternal(
5639                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
5640    }
5641
5642    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5643            int flags, int userId, boolean includeInstantApps) {
5644        try {
5645            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5646
5647            if (!sUserManager.exists(userId)) return null;
5648            final int callingUid = Binder.getCallingUid();
5649            flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
5650            enforceCrossUserPermission(callingUid, userId,
5651                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5652
5653            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5654            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5655                    flags, userId, includeInstantApps);
5656            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5657
5658            final ResolveInfo bestChoice =
5659                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5660            return bestChoice;
5661        } finally {
5662            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5663        }
5664    }
5665
5666    @Override
5667    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5668        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5669            throw new SecurityException(
5670                    "findPersistentPreferredActivity can only be run by the system");
5671        }
5672        if (!sUserManager.exists(userId)) {
5673            return null;
5674        }
5675        final int callingUid = Binder.getCallingUid();
5676        intent = updateIntentForResolve(intent);
5677        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5678        final int flags = updateFlagsForResolve(
5679                0, userId, intent, callingUid, false /*includeInstantApps*/);
5680        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5681                userId);
5682        synchronized (mPackages) {
5683            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5684                    userId);
5685        }
5686    }
5687
5688    @Override
5689    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5690            IntentFilter filter, int match, ComponentName activity) {
5691        final int userId = UserHandle.getCallingUserId();
5692        if (DEBUG_PREFERRED) {
5693            Log.v(TAG, "setLastChosenActivity intent=" + intent
5694                + " resolvedType=" + resolvedType
5695                + " flags=" + flags
5696                + " filter=" + filter
5697                + " match=" + match
5698                + " activity=" + activity);
5699            filter.dump(new PrintStreamPrinter(System.out), "    ");
5700        }
5701        intent.setComponent(null);
5702        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5703                userId);
5704        // Find any earlier preferred or last chosen entries and nuke them
5705        findPreferredActivity(intent, resolvedType,
5706                flags, query, 0, false, true, false, userId);
5707        // Add the new activity as the last chosen for this filter
5708        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5709                "Setting last chosen");
5710    }
5711
5712    @Override
5713    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5714        final int userId = UserHandle.getCallingUserId();
5715        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5716        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5717                userId);
5718        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5719                false, false, false, userId);
5720    }
5721
5722    /**
5723     * Returns whether or not instant apps have been disabled remotely.
5724     */
5725    private boolean isEphemeralDisabled() {
5726        return mEphemeralAppsDisabled;
5727    }
5728
5729    private boolean isEphemeralAllowed(
5730            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5731            boolean skipPackageCheck) {
5732        final int callingUser = UserHandle.getCallingUserId();
5733        if (mInstantAppResolverConnection == null) {
5734            return false;
5735        }
5736        if (mInstantAppInstallerActivity == null) {
5737            return false;
5738        }
5739        if (intent.getComponent() != null) {
5740            return false;
5741        }
5742        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5743            return false;
5744        }
5745        if (!skipPackageCheck && intent.getPackage() != null) {
5746            return false;
5747        }
5748        final boolean isWebUri = hasWebURI(intent);
5749        if (!isWebUri || intent.getData().getHost() == null) {
5750            return false;
5751        }
5752        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5753        // Or if there's already an ephemeral app installed that handles the action
5754        synchronized (mPackages) {
5755            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5756            for (int n = 0; n < count; n++) {
5757                final ResolveInfo info = resolvedActivities.get(n);
5758                final String packageName = info.activityInfo.packageName;
5759                final PackageSetting ps = mSettings.mPackages.get(packageName);
5760                if (ps != null) {
5761                    // only check domain verification status if the app is not a browser
5762                    if (!info.handleAllWebDataURI) {
5763                        // Try to get the status from User settings first
5764                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5765                        final int status = (int) (packedStatus >> 32);
5766                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5767                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5768                            if (DEBUG_EPHEMERAL) {
5769                                Slog.v(TAG, "DENY instant app;"
5770                                    + " pkg: " + packageName + ", status: " + status);
5771                            }
5772                            return false;
5773                        }
5774                    }
5775                    if (ps.getInstantApp(userId)) {
5776                        if (DEBUG_EPHEMERAL) {
5777                            Slog.v(TAG, "DENY instant app installed;"
5778                                    + " pkg: " + packageName);
5779                        }
5780                        return false;
5781                    }
5782                }
5783            }
5784        }
5785        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5786        return true;
5787    }
5788
5789    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5790            Intent origIntent, String resolvedType, String callingPackage,
5791            int userId) {
5792        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5793                new InstantAppRequest(responseObj, origIntent, resolvedType,
5794                        callingPackage, userId));
5795        mHandler.sendMessage(msg);
5796    }
5797
5798    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5799            int flags, List<ResolveInfo> query, int userId) {
5800        if (query != null) {
5801            final int N = query.size();
5802            if (N == 1) {
5803                return query.get(0);
5804            } else if (N > 1) {
5805                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5806                // If there is more than one activity with the same priority,
5807                // then let the user decide between them.
5808                ResolveInfo r0 = query.get(0);
5809                ResolveInfo r1 = query.get(1);
5810                if (DEBUG_INTENT_MATCHING || debug) {
5811                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5812                            + r1.activityInfo.name + "=" + r1.priority);
5813                }
5814                // If the first activity has a higher priority, or a different
5815                // default, then it is always desirable to pick it.
5816                if (r0.priority != r1.priority
5817                        || r0.preferredOrder != r1.preferredOrder
5818                        || r0.isDefault != r1.isDefault) {
5819                    return query.get(0);
5820                }
5821                // If we have saved a preference for a preferred activity for
5822                // this Intent, use that.
5823                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5824                        flags, query, r0.priority, true, false, debug, userId);
5825                if (ri != null) {
5826                    return ri;
5827                }
5828                // If we have an ephemeral app, use it
5829                for (int i = 0; i < N; i++) {
5830                    ri = query.get(i);
5831                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5832                        return ri;
5833                    }
5834                }
5835                ri = new ResolveInfo(mResolveInfo);
5836                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5837                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5838                // If all of the options come from the same package, show the application's
5839                // label and icon instead of the generic resolver's.
5840                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5841                // and then throw away the ResolveInfo itself, meaning that the caller loses
5842                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5843                // a fallback for this case; we only set the target package's resources on
5844                // the ResolveInfo, not the ActivityInfo.
5845                final String intentPackage = intent.getPackage();
5846                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5847                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5848                    ri.resolvePackageName = intentPackage;
5849                    if (userNeedsBadging(userId)) {
5850                        ri.noResourceId = true;
5851                    } else {
5852                        ri.icon = appi.icon;
5853                    }
5854                    ri.iconResourceId = appi.icon;
5855                    ri.labelRes = appi.labelRes;
5856                }
5857                ri.activityInfo.applicationInfo = new ApplicationInfo(
5858                        ri.activityInfo.applicationInfo);
5859                if (userId != 0) {
5860                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5861                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5862                }
5863                // Make sure that the resolver is displayable in car mode
5864                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5865                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5866                return ri;
5867            }
5868        }
5869        return null;
5870    }
5871
5872    /**
5873     * Return true if the given list is not empty and all of its contents have
5874     * an activityInfo with the given package name.
5875     */
5876    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5877        if (ArrayUtils.isEmpty(list)) {
5878            return false;
5879        }
5880        for (int i = 0, N = list.size(); i < N; i++) {
5881            final ResolveInfo ri = list.get(i);
5882            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5883            if (ai == null || !packageName.equals(ai.packageName)) {
5884                return false;
5885            }
5886        }
5887        return true;
5888    }
5889
5890    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5891            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5892        final int N = query.size();
5893        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5894                .get(userId);
5895        // Get the list of persistent preferred activities that handle the intent
5896        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5897        List<PersistentPreferredActivity> pprefs = ppir != null
5898                ? ppir.queryIntent(intent, resolvedType,
5899                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5900                        userId)
5901                : null;
5902        if (pprefs != null && pprefs.size() > 0) {
5903            final int M = pprefs.size();
5904            for (int i=0; i<M; i++) {
5905                final PersistentPreferredActivity ppa = pprefs.get(i);
5906                if (DEBUG_PREFERRED || debug) {
5907                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5908                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5909                            + "\n  component=" + ppa.mComponent);
5910                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5911                }
5912                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5913                        flags | MATCH_DISABLED_COMPONENTS, userId);
5914                if (DEBUG_PREFERRED || debug) {
5915                    Slog.v(TAG, "Found persistent preferred activity:");
5916                    if (ai != null) {
5917                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5918                    } else {
5919                        Slog.v(TAG, "  null");
5920                    }
5921                }
5922                if (ai == null) {
5923                    // This previously registered persistent preferred activity
5924                    // component is no longer known. Ignore it and do NOT remove it.
5925                    continue;
5926                }
5927                for (int j=0; j<N; j++) {
5928                    final ResolveInfo ri = query.get(j);
5929                    if (!ri.activityInfo.applicationInfo.packageName
5930                            .equals(ai.applicationInfo.packageName)) {
5931                        continue;
5932                    }
5933                    if (!ri.activityInfo.name.equals(ai.name)) {
5934                        continue;
5935                    }
5936                    //  Found a persistent preference that can handle the intent.
5937                    if (DEBUG_PREFERRED || debug) {
5938                        Slog.v(TAG, "Returning persistent preferred activity: " +
5939                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5940                    }
5941                    return ri;
5942                }
5943            }
5944        }
5945        return null;
5946    }
5947
5948    // TODO: handle preferred activities missing while user has amnesia
5949    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5950            List<ResolveInfo> query, int priority, boolean always,
5951            boolean removeMatches, boolean debug, int userId) {
5952        if (!sUserManager.exists(userId)) return null;
5953        final int callingUid = Binder.getCallingUid();
5954        flags = updateFlagsForResolve(
5955                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5956        intent = updateIntentForResolve(intent);
5957        // writer
5958        synchronized (mPackages) {
5959            // Try to find a matching persistent preferred activity.
5960            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5961                    debug, userId);
5962
5963            // If a persistent preferred activity matched, use it.
5964            if (pri != null) {
5965                return pri;
5966            }
5967
5968            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5969            // Get the list of preferred activities that handle the intent
5970            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5971            List<PreferredActivity> prefs = pir != null
5972                    ? pir.queryIntent(intent, resolvedType,
5973                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5974                            userId)
5975                    : null;
5976            if (prefs != null && prefs.size() > 0) {
5977                boolean changed = false;
5978                try {
5979                    // First figure out how good the original match set is.
5980                    // We will only allow preferred activities that came
5981                    // from the same match quality.
5982                    int match = 0;
5983
5984                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5985
5986                    final int N = query.size();
5987                    for (int j=0; j<N; j++) {
5988                        final ResolveInfo ri = query.get(j);
5989                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5990                                + ": 0x" + Integer.toHexString(match));
5991                        if (ri.match > match) {
5992                            match = ri.match;
5993                        }
5994                    }
5995
5996                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5997                            + Integer.toHexString(match));
5998
5999                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6000                    final int M = prefs.size();
6001                    for (int i=0; i<M; i++) {
6002                        final PreferredActivity pa = prefs.get(i);
6003                        if (DEBUG_PREFERRED || debug) {
6004                            Slog.v(TAG, "Checking PreferredActivity ds="
6005                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6006                                    + "\n  component=" + pa.mPref.mComponent);
6007                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6008                        }
6009                        if (pa.mPref.mMatch != match) {
6010                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6011                                    + Integer.toHexString(pa.mPref.mMatch));
6012                            continue;
6013                        }
6014                        // If it's not an "always" type preferred activity and that's what we're
6015                        // looking for, skip it.
6016                        if (always && !pa.mPref.mAlways) {
6017                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6018                            continue;
6019                        }
6020                        final ActivityInfo ai = getActivityInfo(
6021                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6022                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6023                                userId);
6024                        if (DEBUG_PREFERRED || debug) {
6025                            Slog.v(TAG, "Found preferred activity:");
6026                            if (ai != null) {
6027                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6028                            } else {
6029                                Slog.v(TAG, "  null");
6030                            }
6031                        }
6032                        if (ai == null) {
6033                            // This previously registered preferred activity
6034                            // component is no longer known.  Most likely an update
6035                            // to the app was installed and in the new version this
6036                            // component no longer exists.  Clean it up by removing
6037                            // it from the preferred activities list, and skip it.
6038                            Slog.w(TAG, "Removing dangling preferred activity: "
6039                                    + pa.mPref.mComponent);
6040                            pir.removeFilter(pa);
6041                            changed = true;
6042                            continue;
6043                        }
6044                        for (int j=0; j<N; j++) {
6045                            final ResolveInfo ri = query.get(j);
6046                            if (!ri.activityInfo.applicationInfo.packageName
6047                                    .equals(ai.applicationInfo.packageName)) {
6048                                continue;
6049                            }
6050                            if (!ri.activityInfo.name.equals(ai.name)) {
6051                                continue;
6052                            }
6053
6054                            if (removeMatches) {
6055                                pir.removeFilter(pa);
6056                                changed = true;
6057                                if (DEBUG_PREFERRED) {
6058                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6059                                }
6060                                break;
6061                            }
6062
6063                            // Okay we found a previously set preferred or last chosen app.
6064                            // If the result set is different from when this
6065                            // was created, we need to clear it and re-ask the
6066                            // user their preference, if we're looking for an "always" type entry.
6067                            if (always && !pa.mPref.sameSet(query)) {
6068                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6069                                        + intent + " type " + resolvedType);
6070                                if (DEBUG_PREFERRED) {
6071                                    Slog.v(TAG, "Removing preferred activity since set changed "
6072                                            + pa.mPref.mComponent);
6073                                }
6074                                pir.removeFilter(pa);
6075                                // Re-add the filter as a "last chosen" entry (!always)
6076                                PreferredActivity lastChosen = new PreferredActivity(
6077                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6078                                pir.addFilter(lastChosen);
6079                                changed = true;
6080                                return null;
6081                            }
6082
6083                            // Yay! Either the set matched or we're looking for the last chosen
6084                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6085                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6086                            return ri;
6087                        }
6088                    }
6089                } finally {
6090                    if (changed) {
6091                        if (DEBUG_PREFERRED) {
6092                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6093                        }
6094                        scheduleWritePackageRestrictionsLocked(userId);
6095                    }
6096                }
6097            }
6098        }
6099        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6100        return null;
6101    }
6102
6103    /*
6104     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6105     */
6106    @Override
6107    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6108            int targetUserId) {
6109        mContext.enforceCallingOrSelfPermission(
6110                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6111        List<CrossProfileIntentFilter> matches =
6112                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6113        if (matches != null) {
6114            int size = matches.size();
6115            for (int i = 0; i < size; i++) {
6116                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6117            }
6118        }
6119        if (hasWebURI(intent)) {
6120            // cross-profile app linking works only towards the parent.
6121            final int callingUid = Binder.getCallingUid();
6122            final UserInfo parent = getProfileParent(sourceUserId);
6123            synchronized(mPackages) {
6124                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6125                        false /*includeInstantApps*/);
6126                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6127                        intent, resolvedType, flags, sourceUserId, parent.id);
6128                return xpDomainInfo != null;
6129            }
6130        }
6131        return false;
6132    }
6133
6134    private UserInfo getProfileParent(int userId) {
6135        final long identity = Binder.clearCallingIdentity();
6136        try {
6137            return sUserManager.getProfileParent(userId);
6138        } finally {
6139            Binder.restoreCallingIdentity(identity);
6140        }
6141    }
6142
6143    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6144            String resolvedType, int userId) {
6145        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6146        if (resolver != null) {
6147            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6148        }
6149        return null;
6150    }
6151
6152    @Override
6153    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6154            String resolvedType, int flags, int userId) {
6155        try {
6156            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6157
6158            return new ParceledListSlice<>(
6159                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6160        } finally {
6161            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6162        }
6163    }
6164
6165    /**
6166     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6167     * instant, returns {@code null}.
6168     */
6169    private String getInstantAppPackageName(int callingUid) {
6170        // If the caller is an isolated app use the owner's uid for the lookup.
6171        if (Process.isIsolated(callingUid)) {
6172            callingUid = mIsolatedOwners.get(callingUid);
6173        }
6174        final int appId = UserHandle.getAppId(callingUid);
6175        synchronized (mPackages) {
6176            final Object obj = mSettings.getUserIdLPr(appId);
6177            if (obj instanceof PackageSetting) {
6178                final PackageSetting ps = (PackageSetting) obj;
6179                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6180                return isInstantApp ? ps.pkg.packageName : null;
6181            }
6182        }
6183        return null;
6184    }
6185
6186    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6187            String resolvedType, int flags, int userId) {
6188        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6189    }
6190
6191    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6192            String resolvedType, int flags, int userId, boolean includeInstantApps) {
6193        if (!sUserManager.exists(userId)) return Collections.emptyList();
6194        final int callingUid = Binder.getCallingUid();
6195        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6196        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
6197        enforceCrossUserPermission(callingUid, userId,
6198                false /* requireFullPermission */, false /* checkShell */,
6199                "query intent activities");
6200        ComponentName comp = intent.getComponent();
6201        if (comp == null) {
6202            if (intent.getSelector() != null) {
6203                intent = intent.getSelector();
6204                comp = intent.getComponent();
6205            }
6206        }
6207
6208        if (comp != null) {
6209            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6210            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6211            if (ai != null) {
6212                // When specifying an explicit component, we prevent the activity from being
6213                // used when either 1) the calling package is normal and the activity is within
6214                // an ephemeral application or 2) the calling package is ephemeral and the
6215                // activity is not visible to ephemeral applications.
6216                final boolean matchInstantApp =
6217                        (flags & PackageManager.MATCH_INSTANT) != 0;
6218                final boolean matchVisibleToInstantAppOnly =
6219                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6220                final boolean isCallerInstantApp =
6221                        instantAppPkgName != null;
6222                final boolean isTargetSameInstantApp =
6223                        comp.getPackageName().equals(instantAppPkgName);
6224                final boolean isTargetInstantApp =
6225                        (ai.applicationInfo.privateFlags
6226                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6227                final boolean isTargetHiddenFromInstantApp =
6228                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6229                final boolean blockResolution =
6230                        !isTargetSameInstantApp
6231                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6232                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6233                                        && isTargetHiddenFromInstantApp));
6234                if (!blockResolution) {
6235                    final ResolveInfo ri = new ResolveInfo();
6236                    ri.activityInfo = ai;
6237                    list.add(ri);
6238                }
6239            }
6240            return applyPostResolutionFilter(list, instantAppPkgName);
6241        }
6242
6243        // reader
6244        boolean sortResult = false;
6245        boolean addEphemeral = false;
6246        List<ResolveInfo> result;
6247        final String pkgName = intent.getPackage();
6248        final boolean ephemeralDisabled = isEphemeralDisabled();
6249        synchronized (mPackages) {
6250            if (pkgName == null) {
6251                List<CrossProfileIntentFilter> matchingFilters =
6252                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6253                // Check for results that need to skip the current profile.
6254                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6255                        resolvedType, flags, userId);
6256                if (xpResolveInfo != null) {
6257                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6258                    xpResult.add(xpResolveInfo);
6259                    return applyPostResolutionFilter(
6260                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6261                }
6262
6263                // Check for results in the current profile.
6264                result = filterIfNotSystemUser(mActivities.queryIntent(
6265                        intent, resolvedType, flags, userId), userId);
6266                addEphemeral = !ephemeralDisabled
6267                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6268                // Check for cross profile results.
6269                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6270                xpResolveInfo = queryCrossProfileIntents(
6271                        matchingFilters, intent, resolvedType, flags, userId,
6272                        hasNonNegativePriorityResult);
6273                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6274                    boolean isVisibleToUser = filterIfNotSystemUser(
6275                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6276                    if (isVisibleToUser) {
6277                        result.add(xpResolveInfo);
6278                        sortResult = true;
6279                    }
6280                }
6281                if (hasWebURI(intent)) {
6282                    CrossProfileDomainInfo xpDomainInfo = null;
6283                    final UserInfo parent = getProfileParent(userId);
6284                    if (parent != null) {
6285                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6286                                flags, userId, parent.id);
6287                    }
6288                    if (xpDomainInfo != null) {
6289                        if (xpResolveInfo != null) {
6290                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6291                            // in the result.
6292                            result.remove(xpResolveInfo);
6293                        }
6294                        if (result.size() == 0 && !addEphemeral) {
6295                            // No result in current profile, but found candidate in parent user.
6296                            // And we are not going to add emphemeral app, so we can return the
6297                            // result straight away.
6298                            result.add(xpDomainInfo.resolveInfo);
6299                            return applyPostResolutionFilter(result, instantAppPkgName);
6300                        }
6301                    } else if (result.size() <= 1 && !addEphemeral) {
6302                        // No result in parent user and <= 1 result in current profile, and we
6303                        // are not going to add emphemeral app, so we can return the result without
6304                        // further processing.
6305                        return applyPostResolutionFilter(result, instantAppPkgName);
6306                    }
6307                    // We have more than one candidate (combining results from current and parent
6308                    // profile), so we need filtering and sorting.
6309                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6310                            intent, flags, result, xpDomainInfo, userId);
6311                    sortResult = true;
6312                }
6313            } else {
6314                final PackageParser.Package pkg = mPackages.get(pkgName);
6315                if (pkg != null) {
6316                    return applyPostResolutionFilter(filterIfNotSystemUser(
6317                            mActivities.queryIntentForPackage(
6318                                    intent, resolvedType, flags, pkg.activities, userId),
6319                            userId), instantAppPkgName);
6320                } else {
6321                    // the caller wants to resolve for a particular package; however, there
6322                    // were no installed results, so, try to find an ephemeral result
6323                    addEphemeral = !ephemeralDisabled
6324                            && isEphemeralAllowed(
6325                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6326                    result = new ArrayList<ResolveInfo>();
6327                }
6328            }
6329        }
6330        if (addEphemeral) {
6331            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6332            final InstantAppRequest requestObject = new InstantAppRequest(
6333                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6334                    null /*callingPackage*/, userId);
6335            final AuxiliaryResolveInfo auxiliaryResponse =
6336                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6337                            mContext, mInstantAppResolverConnection, requestObject);
6338            if (auxiliaryResponse != null) {
6339                if (DEBUG_EPHEMERAL) {
6340                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6341                }
6342                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6343                final PackageSetting ps =
6344                        mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6345                if (ps != null) {
6346                    ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6347                            mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6348                    ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6349                    ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6350                    // make sure this resolver is the default
6351                    ephemeralInstaller.isDefault = true;
6352                    ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6353                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6354                    // add a non-generic filter
6355                    ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6356                    ephemeralInstaller.filter.addDataPath(
6357                            intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6358                    ephemeralInstaller.instantAppAvailable = true;
6359                    result.add(ephemeralInstaller);
6360                }
6361            }
6362            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6363        }
6364        if (sortResult) {
6365            Collections.sort(result, mResolvePrioritySorter);
6366        }
6367        return applyPostResolutionFilter(result, instantAppPkgName);
6368    }
6369
6370    private static class CrossProfileDomainInfo {
6371        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6372        ResolveInfo resolveInfo;
6373        /* Best domain verification status of the activities found in the other profile */
6374        int bestDomainVerificationStatus;
6375    }
6376
6377    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6378            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6379        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6380                sourceUserId)) {
6381            return null;
6382        }
6383        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6384                resolvedType, flags, parentUserId);
6385
6386        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6387            return null;
6388        }
6389        CrossProfileDomainInfo result = null;
6390        int size = resultTargetUser.size();
6391        for (int i = 0; i < size; i++) {
6392            ResolveInfo riTargetUser = resultTargetUser.get(i);
6393            // Intent filter verification is only for filters that specify a host. So don't return
6394            // those that handle all web uris.
6395            if (riTargetUser.handleAllWebDataURI) {
6396                continue;
6397            }
6398            String packageName = riTargetUser.activityInfo.packageName;
6399            PackageSetting ps = mSettings.mPackages.get(packageName);
6400            if (ps == null) {
6401                continue;
6402            }
6403            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6404            int status = (int)(verificationState >> 32);
6405            if (result == null) {
6406                result = new CrossProfileDomainInfo();
6407                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6408                        sourceUserId, parentUserId);
6409                result.bestDomainVerificationStatus = status;
6410            } else {
6411                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6412                        result.bestDomainVerificationStatus);
6413            }
6414        }
6415        // Don't consider matches with status NEVER across profiles.
6416        if (result != null && result.bestDomainVerificationStatus
6417                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6418            return null;
6419        }
6420        return result;
6421    }
6422
6423    /**
6424     * Verification statuses are ordered from the worse to the best, except for
6425     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6426     */
6427    private int bestDomainVerificationStatus(int status1, int status2) {
6428        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6429            return status2;
6430        }
6431        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6432            return status1;
6433        }
6434        return (int) MathUtils.max(status1, status2);
6435    }
6436
6437    private boolean isUserEnabled(int userId) {
6438        long callingId = Binder.clearCallingIdentity();
6439        try {
6440            UserInfo userInfo = sUserManager.getUserInfo(userId);
6441            return userInfo != null && userInfo.isEnabled();
6442        } finally {
6443            Binder.restoreCallingIdentity(callingId);
6444        }
6445    }
6446
6447    /**
6448     * Filter out activities with systemUserOnly flag set, when current user is not System.
6449     *
6450     * @return filtered list
6451     */
6452    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6453        if (userId == UserHandle.USER_SYSTEM) {
6454            return resolveInfos;
6455        }
6456        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6457            ResolveInfo info = resolveInfos.get(i);
6458            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6459                resolveInfos.remove(i);
6460            }
6461        }
6462        return resolveInfos;
6463    }
6464
6465    /**
6466     * Filters out ephemeral activities.
6467     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6468     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6469     *
6470     * @param resolveInfos The pre-filtered list of resolved activities
6471     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6472     *          is performed.
6473     * @return A filtered list of resolved activities.
6474     */
6475    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6476            String ephemeralPkgName) {
6477        // TODO: When adding on-demand split support for non-instant apps, remove this check
6478        // and always apply post filtering
6479        if (ephemeralPkgName == null) {
6480            return resolveInfos;
6481        }
6482        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6483            final ResolveInfo info = resolveInfos.get(i);
6484            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6485            // allow activities that are defined in the provided package
6486            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6487                if (info.activityInfo.splitName != null
6488                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6489                                info.activityInfo.splitName)) {
6490                    // requested activity is defined in a split that hasn't been installed yet.
6491                    // add the installer to the resolve list
6492                    if (DEBUG_EPHEMERAL) {
6493                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6494                    }
6495                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6496                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6497                            info.activityInfo.packageName, info.activityInfo.splitName,
6498                            info.activityInfo.applicationInfo.versionCode);
6499                    // make sure this resolver is the default
6500                    installerInfo.isDefault = true;
6501                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6502                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6503                    // add a non-generic filter
6504                    installerInfo.filter = new IntentFilter();
6505                    // load resources from the correct package
6506                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6507                    resolveInfos.set(i, installerInfo);
6508                }
6509                continue;
6510            }
6511            // allow activities that have been explicitly exposed to ephemeral apps
6512            if (!isEphemeralApp
6513                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6514                continue;
6515            }
6516            resolveInfos.remove(i);
6517        }
6518        return resolveInfos;
6519    }
6520
6521    /**
6522     * @param resolveInfos list of resolve infos in descending priority order
6523     * @return if the list contains a resolve info with non-negative priority
6524     */
6525    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6526        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6527    }
6528
6529    private static boolean hasWebURI(Intent intent) {
6530        if (intent.getData() == null) {
6531            return false;
6532        }
6533        final String scheme = intent.getScheme();
6534        if (TextUtils.isEmpty(scheme)) {
6535            return false;
6536        }
6537        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6538    }
6539
6540    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6541            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6542            int userId) {
6543        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6544
6545        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6546            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6547                    candidates.size());
6548        }
6549
6550        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6551        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6552        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6553        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6554        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6555        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6556
6557        synchronized (mPackages) {
6558            final int count = candidates.size();
6559            // First, try to use linked apps. Partition the candidates into four lists:
6560            // one for the final results, one for the "do not use ever", one for "undefined status"
6561            // and finally one for "browser app type".
6562            for (int n=0; n<count; n++) {
6563                ResolveInfo info = candidates.get(n);
6564                String packageName = info.activityInfo.packageName;
6565                PackageSetting ps = mSettings.mPackages.get(packageName);
6566                if (ps != null) {
6567                    // Add to the special match all list (Browser use case)
6568                    if (info.handleAllWebDataURI) {
6569                        matchAllList.add(info);
6570                        continue;
6571                    }
6572                    // Try to get the status from User settings first
6573                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6574                    int status = (int)(packedStatus >> 32);
6575                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6576                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6577                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6578                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6579                                    + " : linkgen=" + linkGeneration);
6580                        }
6581                        // Use link-enabled generation as preferredOrder, i.e.
6582                        // prefer newly-enabled over earlier-enabled.
6583                        info.preferredOrder = linkGeneration;
6584                        alwaysList.add(info);
6585                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6586                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6587                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6588                        }
6589                        neverList.add(info);
6590                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6591                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6592                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6593                        }
6594                        alwaysAskList.add(info);
6595                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6596                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6597                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6598                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6599                        }
6600                        undefinedList.add(info);
6601                    }
6602                }
6603            }
6604
6605            // We'll want to include browser possibilities in a few cases
6606            boolean includeBrowser = false;
6607
6608            // First try to add the "always" resolution(s) for the current user, if any
6609            if (alwaysList.size() > 0) {
6610                result.addAll(alwaysList);
6611            } else {
6612                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6613                result.addAll(undefinedList);
6614                // Maybe add one for the other profile.
6615                if (xpDomainInfo != null && (
6616                        xpDomainInfo.bestDomainVerificationStatus
6617                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6618                    result.add(xpDomainInfo.resolveInfo);
6619                }
6620                includeBrowser = true;
6621            }
6622
6623            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6624            // If there were 'always' entries their preferred order has been set, so we also
6625            // back that off to make the alternatives equivalent
6626            if (alwaysAskList.size() > 0) {
6627                for (ResolveInfo i : result) {
6628                    i.preferredOrder = 0;
6629                }
6630                result.addAll(alwaysAskList);
6631                includeBrowser = true;
6632            }
6633
6634            if (includeBrowser) {
6635                // Also add browsers (all of them or only the default one)
6636                if (DEBUG_DOMAIN_VERIFICATION) {
6637                    Slog.v(TAG, "   ...including browsers in candidate set");
6638                }
6639                if ((matchFlags & MATCH_ALL) != 0) {
6640                    result.addAll(matchAllList);
6641                } else {
6642                    // Browser/generic handling case.  If there's a default browser, go straight
6643                    // to that (but only if there is no other higher-priority match).
6644                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6645                    int maxMatchPrio = 0;
6646                    ResolveInfo defaultBrowserMatch = null;
6647                    final int numCandidates = matchAllList.size();
6648                    for (int n = 0; n < numCandidates; n++) {
6649                        ResolveInfo info = matchAllList.get(n);
6650                        // track the highest overall match priority...
6651                        if (info.priority > maxMatchPrio) {
6652                            maxMatchPrio = info.priority;
6653                        }
6654                        // ...and the highest-priority default browser match
6655                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6656                            if (defaultBrowserMatch == null
6657                                    || (defaultBrowserMatch.priority < info.priority)) {
6658                                if (debug) {
6659                                    Slog.v(TAG, "Considering default browser match " + info);
6660                                }
6661                                defaultBrowserMatch = info;
6662                            }
6663                        }
6664                    }
6665                    if (defaultBrowserMatch != null
6666                            && defaultBrowserMatch.priority >= maxMatchPrio
6667                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6668                    {
6669                        if (debug) {
6670                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6671                        }
6672                        result.add(defaultBrowserMatch);
6673                    } else {
6674                        result.addAll(matchAllList);
6675                    }
6676                }
6677
6678                // If there is nothing selected, add all candidates and remove the ones that the user
6679                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6680                if (result.size() == 0) {
6681                    result.addAll(candidates);
6682                    result.removeAll(neverList);
6683                }
6684            }
6685        }
6686        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6687            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6688                    result.size());
6689            for (ResolveInfo info : result) {
6690                Slog.v(TAG, "  + " + info.activityInfo);
6691            }
6692        }
6693        return result;
6694    }
6695
6696    // Returns a packed value as a long:
6697    //
6698    // high 'int'-sized word: link status: undefined/ask/never/always.
6699    // low 'int'-sized word: relative priority among 'always' results.
6700    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6701        long result = ps.getDomainVerificationStatusForUser(userId);
6702        // if none available, get the master status
6703        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6704            if (ps.getIntentFilterVerificationInfo() != null) {
6705                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6706            }
6707        }
6708        return result;
6709    }
6710
6711    private ResolveInfo querySkipCurrentProfileIntents(
6712            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6713            int flags, int sourceUserId) {
6714        if (matchingFilters != null) {
6715            int size = matchingFilters.size();
6716            for (int i = 0; i < size; i ++) {
6717                CrossProfileIntentFilter filter = matchingFilters.get(i);
6718                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6719                    // Checking if there are activities in the target user that can handle the
6720                    // intent.
6721                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6722                            resolvedType, flags, sourceUserId);
6723                    if (resolveInfo != null) {
6724                        return resolveInfo;
6725                    }
6726                }
6727            }
6728        }
6729        return null;
6730    }
6731
6732    // Return matching ResolveInfo in target user if any.
6733    private ResolveInfo queryCrossProfileIntents(
6734            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6735            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6736        if (matchingFilters != null) {
6737            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6738            // match the same intent. For performance reasons, it is better not to
6739            // run queryIntent twice for the same userId
6740            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6741            int size = matchingFilters.size();
6742            for (int i = 0; i < size; i++) {
6743                CrossProfileIntentFilter filter = matchingFilters.get(i);
6744                int targetUserId = filter.getTargetUserId();
6745                boolean skipCurrentProfile =
6746                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6747                boolean skipCurrentProfileIfNoMatchFound =
6748                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6749                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6750                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6751                    // Checking if there are activities in the target user that can handle the
6752                    // intent.
6753                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6754                            resolvedType, flags, sourceUserId);
6755                    if (resolveInfo != null) return resolveInfo;
6756                    alreadyTriedUserIds.put(targetUserId, true);
6757                }
6758            }
6759        }
6760        return null;
6761    }
6762
6763    /**
6764     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6765     * will forward the intent to the filter's target user.
6766     * Otherwise, returns null.
6767     */
6768    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6769            String resolvedType, int flags, int sourceUserId) {
6770        int targetUserId = filter.getTargetUserId();
6771        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6772                resolvedType, flags, targetUserId);
6773        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6774            // If all the matches in the target profile are suspended, return null.
6775            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6776                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6777                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6778                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6779                            targetUserId);
6780                }
6781            }
6782        }
6783        return null;
6784    }
6785
6786    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6787            int sourceUserId, int targetUserId) {
6788        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6789        long ident = Binder.clearCallingIdentity();
6790        boolean targetIsProfile;
6791        try {
6792            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6793        } finally {
6794            Binder.restoreCallingIdentity(ident);
6795        }
6796        String className;
6797        if (targetIsProfile) {
6798            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6799        } else {
6800            className = FORWARD_INTENT_TO_PARENT;
6801        }
6802        ComponentName forwardingActivityComponentName = new ComponentName(
6803                mAndroidApplication.packageName, className);
6804        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6805                sourceUserId);
6806        if (!targetIsProfile) {
6807            forwardingActivityInfo.showUserIcon = targetUserId;
6808            forwardingResolveInfo.noResourceId = true;
6809        }
6810        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6811        forwardingResolveInfo.priority = 0;
6812        forwardingResolveInfo.preferredOrder = 0;
6813        forwardingResolveInfo.match = 0;
6814        forwardingResolveInfo.isDefault = true;
6815        forwardingResolveInfo.filter = filter;
6816        forwardingResolveInfo.targetUserId = targetUserId;
6817        return forwardingResolveInfo;
6818    }
6819
6820    @Override
6821    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6822            Intent[] specifics, String[] specificTypes, Intent intent,
6823            String resolvedType, int flags, int userId) {
6824        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6825                specificTypes, intent, resolvedType, flags, userId));
6826    }
6827
6828    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6829            Intent[] specifics, String[] specificTypes, Intent intent,
6830            String resolvedType, int flags, int userId) {
6831        if (!sUserManager.exists(userId)) return Collections.emptyList();
6832        final int callingUid = Binder.getCallingUid();
6833        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
6834                false /*includeInstantApps*/);
6835        enforceCrossUserPermission(callingUid, userId,
6836                false /*requireFullPermission*/, false /*checkShell*/,
6837                "query intent activity options");
6838        final String resultsAction = intent.getAction();
6839
6840        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6841                | PackageManager.GET_RESOLVED_FILTER, userId);
6842
6843        if (DEBUG_INTENT_MATCHING) {
6844            Log.v(TAG, "Query " + intent + ": " + results);
6845        }
6846
6847        int specificsPos = 0;
6848        int N;
6849
6850        // todo: note that the algorithm used here is O(N^2).  This
6851        // isn't a problem in our current environment, but if we start running
6852        // into situations where we have more than 5 or 10 matches then this
6853        // should probably be changed to something smarter...
6854
6855        // First we go through and resolve each of the specific items
6856        // that were supplied, taking care of removing any corresponding
6857        // duplicate items in the generic resolve list.
6858        if (specifics != null) {
6859            for (int i=0; i<specifics.length; i++) {
6860                final Intent sintent = specifics[i];
6861                if (sintent == null) {
6862                    continue;
6863                }
6864
6865                if (DEBUG_INTENT_MATCHING) {
6866                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6867                }
6868
6869                String action = sintent.getAction();
6870                if (resultsAction != null && resultsAction.equals(action)) {
6871                    // If this action was explicitly requested, then don't
6872                    // remove things that have it.
6873                    action = null;
6874                }
6875
6876                ResolveInfo ri = null;
6877                ActivityInfo ai = null;
6878
6879                ComponentName comp = sintent.getComponent();
6880                if (comp == null) {
6881                    ri = resolveIntent(
6882                        sintent,
6883                        specificTypes != null ? specificTypes[i] : null,
6884                            flags, userId);
6885                    if (ri == null) {
6886                        continue;
6887                    }
6888                    if (ri == mResolveInfo) {
6889                        // ACK!  Must do something better with this.
6890                    }
6891                    ai = ri.activityInfo;
6892                    comp = new ComponentName(ai.applicationInfo.packageName,
6893                            ai.name);
6894                } else {
6895                    ai = getActivityInfo(comp, flags, userId);
6896                    if (ai == null) {
6897                        continue;
6898                    }
6899                }
6900
6901                // Look for any generic query activities that are duplicates
6902                // of this specific one, and remove them from the results.
6903                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6904                N = results.size();
6905                int j;
6906                for (j=specificsPos; j<N; j++) {
6907                    ResolveInfo sri = results.get(j);
6908                    if ((sri.activityInfo.name.equals(comp.getClassName())
6909                            && sri.activityInfo.applicationInfo.packageName.equals(
6910                                    comp.getPackageName()))
6911                        || (action != null && sri.filter.matchAction(action))) {
6912                        results.remove(j);
6913                        if (DEBUG_INTENT_MATCHING) Log.v(
6914                            TAG, "Removing duplicate item from " + j
6915                            + " due to specific " + specificsPos);
6916                        if (ri == null) {
6917                            ri = sri;
6918                        }
6919                        j--;
6920                        N--;
6921                    }
6922                }
6923
6924                // Add this specific item to its proper place.
6925                if (ri == null) {
6926                    ri = new ResolveInfo();
6927                    ri.activityInfo = ai;
6928                }
6929                results.add(specificsPos, ri);
6930                ri.specificIndex = i;
6931                specificsPos++;
6932            }
6933        }
6934
6935        // Now we go through the remaining generic results and remove any
6936        // duplicate actions that are found here.
6937        N = results.size();
6938        for (int i=specificsPos; i<N-1; i++) {
6939            final ResolveInfo rii = results.get(i);
6940            if (rii.filter == null) {
6941                continue;
6942            }
6943
6944            // Iterate over all of the actions of this result's intent
6945            // filter...  typically this should be just one.
6946            final Iterator<String> it = rii.filter.actionsIterator();
6947            if (it == null) {
6948                continue;
6949            }
6950            while (it.hasNext()) {
6951                final String action = it.next();
6952                if (resultsAction != null && resultsAction.equals(action)) {
6953                    // If this action was explicitly requested, then don't
6954                    // remove things that have it.
6955                    continue;
6956                }
6957                for (int j=i+1; j<N; j++) {
6958                    final ResolveInfo rij = results.get(j);
6959                    if (rij.filter != null && rij.filter.hasAction(action)) {
6960                        results.remove(j);
6961                        if (DEBUG_INTENT_MATCHING) Log.v(
6962                            TAG, "Removing duplicate item from " + j
6963                            + " due to action " + action + " at " + i);
6964                        j--;
6965                        N--;
6966                    }
6967                }
6968            }
6969
6970            // If the caller didn't request filter information, drop it now
6971            // so we don't have to marshall/unmarshall it.
6972            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6973                rii.filter = null;
6974            }
6975        }
6976
6977        // Filter out the caller activity if so requested.
6978        if (caller != null) {
6979            N = results.size();
6980            for (int i=0; i<N; i++) {
6981                ActivityInfo ainfo = results.get(i).activityInfo;
6982                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6983                        && caller.getClassName().equals(ainfo.name)) {
6984                    results.remove(i);
6985                    break;
6986                }
6987            }
6988        }
6989
6990        // If the caller didn't request filter information,
6991        // drop them now so we don't have to
6992        // marshall/unmarshall it.
6993        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6994            N = results.size();
6995            for (int i=0; i<N; i++) {
6996                results.get(i).filter = null;
6997            }
6998        }
6999
7000        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7001        return results;
7002    }
7003
7004    @Override
7005    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7006            String resolvedType, int flags, int userId) {
7007        return new ParceledListSlice<>(
7008                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7009    }
7010
7011    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7012            String resolvedType, int flags, int userId) {
7013        if (!sUserManager.exists(userId)) return Collections.emptyList();
7014        final int callingUid = Binder.getCallingUid();
7015        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7016                false /*includeInstantApps*/);
7017        ComponentName comp = intent.getComponent();
7018        if (comp == null) {
7019            if (intent.getSelector() != null) {
7020                intent = intent.getSelector();
7021                comp = intent.getComponent();
7022            }
7023        }
7024        if (comp != null) {
7025            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7026            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7027            if (ai != null) {
7028                ResolveInfo ri = new ResolveInfo();
7029                ri.activityInfo = ai;
7030                list.add(ri);
7031            }
7032            return list;
7033        }
7034
7035        // reader
7036        synchronized (mPackages) {
7037            String pkgName = intent.getPackage();
7038            if (pkgName == null) {
7039                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7040            }
7041            final PackageParser.Package pkg = mPackages.get(pkgName);
7042            if (pkg != null) {
7043                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7044                        userId);
7045            }
7046            return Collections.emptyList();
7047        }
7048    }
7049
7050    @Override
7051    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7052        final int callingUid = Binder.getCallingUid();
7053        return resolveServiceInternal(
7054                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7055    }
7056
7057    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7058            int userId, int callingUid, boolean includeInstantApps) {
7059        if (!sUserManager.exists(userId)) return null;
7060        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7061        List<ResolveInfo> query = queryIntentServicesInternal(
7062                intent, resolvedType, flags, userId, callingUid, includeInstantApps);
7063        if (query != null) {
7064            if (query.size() >= 1) {
7065                // If there is more than one service with the same priority,
7066                // just arbitrarily pick the first one.
7067                return query.get(0);
7068            }
7069        }
7070        return null;
7071    }
7072
7073    @Override
7074    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7075            String resolvedType, int flags, int userId) {
7076        final int callingUid = Binder.getCallingUid();
7077        return new ParceledListSlice<>(queryIntentServicesInternal(
7078                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7079    }
7080
7081    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7082            String resolvedType, int flags, int userId, int callingUid,
7083            boolean includeInstantApps) {
7084        if (!sUserManager.exists(userId)) return Collections.emptyList();
7085        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7086        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7087        ComponentName comp = intent.getComponent();
7088        if (comp == null) {
7089            if (intent.getSelector() != null) {
7090                intent = intent.getSelector();
7091                comp = intent.getComponent();
7092            }
7093        }
7094        if (comp != null) {
7095            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7096            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7097            if (si != null) {
7098                // When specifying an explicit component, we prevent the service from being
7099                // used when either 1) the service is in an instant application and the
7100                // caller is not the same instant application or 2) the calling package is
7101                // ephemeral and the activity is not visible to ephemeral applications.
7102                final boolean matchInstantApp =
7103                        (flags & PackageManager.MATCH_INSTANT) != 0;
7104                final boolean matchVisibleToInstantAppOnly =
7105                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7106                final boolean isCallerInstantApp =
7107                        instantAppPkgName != null;
7108                final boolean isTargetSameInstantApp =
7109                        comp.getPackageName().equals(instantAppPkgName);
7110                final boolean isTargetInstantApp =
7111                        (si.applicationInfo.privateFlags
7112                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7113                final boolean isTargetHiddenFromInstantApp =
7114                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
7115                final boolean blockResolution =
7116                        !isTargetSameInstantApp
7117                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7118                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7119                                        && isTargetHiddenFromInstantApp));
7120                if (!blockResolution) {
7121                    final ResolveInfo ri = new ResolveInfo();
7122                    ri.serviceInfo = si;
7123                    list.add(ri);
7124                }
7125            }
7126            return list;
7127        }
7128
7129        // reader
7130        synchronized (mPackages) {
7131            String pkgName = intent.getPackage();
7132            if (pkgName == null) {
7133                return applyPostServiceResolutionFilter(
7134                        mServices.queryIntent(intent, resolvedType, flags, userId),
7135                        instantAppPkgName);
7136            }
7137            final PackageParser.Package pkg = mPackages.get(pkgName);
7138            if (pkg != null) {
7139                return applyPostServiceResolutionFilter(
7140                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7141                                userId),
7142                        instantAppPkgName);
7143            }
7144            return Collections.emptyList();
7145        }
7146    }
7147
7148    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7149            String instantAppPkgName) {
7150        // TODO: When adding on-demand split support for non-instant apps, remove this check
7151        // and always apply post filtering
7152        if (instantAppPkgName == null) {
7153            return resolveInfos;
7154        }
7155        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7156            final ResolveInfo info = resolveInfos.get(i);
7157            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7158            // allow services that are defined in the provided package
7159            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7160                if (info.serviceInfo.splitName != null
7161                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7162                                info.serviceInfo.splitName)) {
7163                    // requested service is defined in a split that hasn't been installed yet.
7164                    // add the installer to the resolve list
7165                    if (DEBUG_EPHEMERAL) {
7166                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7167                    }
7168                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7169                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7170                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7171                            info.serviceInfo.applicationInfo.versionCode);
7172                    // make sure this resolver is the default
7173                    installerInfo.isDefault = true;
7174                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7175                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7176                    // add a non-generic filter
7177                    installerInfo.filter = new IntentFilter();
7178                    // load resources from the correct package
7179                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7180                    resolveInfos.set(i, installerInfo);
7181                }
7182                continue;
7183            }
7184            // allow services that have been explicitly exposed to ephemeral apps
7185            if (!isEphemeralApp
7186                    && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
7187                continue;
7188            }
7189            resolveInfos.remove(i);
7190        }
7191        return resolveInfos;
7192    }
7193
7194    @Override
7195    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7196            String resolvedType, int flags, int userId) {
7197        return new ParceledListSlice<>(
7198                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7199    }
7200
7201    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7202            Intent intent, String resolvedType, int flags, int userId) {
7203        if (!sUserManager.exists(userId)) return Collections.emptyList();
7204        final int callingUid = Binder.getCallingUid();
7205        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7206        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7207                false /*includeInstantApps*/);
7208        ComponentName comp = intent.getComponent();
7209        if (comp == null) {
7210            if (intent.getSelector() != null) {
7211                intent = intent.getSelector();
7212                comp = intent.getComponent();
7213            }
7214        }
7215        if (comp != null) {
7216            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7217            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7218            if (pi != null) {
7219                // When specifying an explicit component, we prevent the provider from being
7220                // used when either 1) the provider is in an instant application and the
7221                // caller is not the same instant application or 2) the calling package is an
7222                // instant application and the provider is not visible to instant applications.
7223                final boolean matchInstantApp =
7224                        (flags & PackageManager.MATCH_INSTANT) != 0;
7225                final boolean matchVisibleToInstantAppOnly =
7226                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7227                final boolean isCallerInstantApp =
7228                        instantAppPkgName != null;
7229                final boolean isTargetSameInstantApp =
7230                        comp.getPackageName().equals(instantAppPkgName);
7231                final boolean isTargetInstantApp =
7232                        (pi.applicationInfo.privateFlags
7233                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7234                final boolean isTargetHiddenFromInstantApp =
7235                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
7236                final boolean blockResolution =
7237                        !isTargetSameInstantApp
7238                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7239                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7240                                        && isTargetHiddenFromInstantApp));
7241                if (!blockResolution) {
7242                    final ResolveInfo ri = new ResolveInfo();
7243                    ri.providerInfo = pi;
7244                    list.add(ri);
7245                }
7246            }
7247            return list;
7248        }
7249
7250        // reader
7251        synchronized (mPackages) {
7252            String pkgName = intent.getPackage();
7253            if (pkgName == null) {
7254                return applyPostContentProviderResolutionFilter(
7255                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7256                        instantAppPkgName);
7257            }
7258            final PackageParser.Package pkg = mPackages.get(pkgName);
7259            if (pkg != null) {
7260                return applyPostContentProviderResolutionFilter(
7261                        mProviders.queryIntentForPackage(
7262                        intent, resolvedType, flags, pkg.providers, userId),
7263                        instantAppPkgName);
7264            }
7265            return Collections.emptyList();
7266        }
7267    }
7268
7269    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7270            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7271        // TODO: When adding on-demand split support for non-instant applications, remove
7272        // this check and always apply post filtering
7273        if (instantAppPkgName == null) {
7274            return resolveInfos;
7275        }
7276        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7277            final ResolveInfo info = resolveInfos.get(i);
7278            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7279            // allow providers that are defined in the provided package
7280            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7281                if (info.providerInfo.splitName != null
7282                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7283                                info.providerInfo.splitName)) {
7284                    // requested provider is defined in a split that hasn't been installed yet.
7285                    // add the installer to the resolve list
7286                    if (DEBUG_EPHEMERAL) {
7287                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7288                    }
7289                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7290                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7291                            info.providerInfo.packageName, info.providerInfo.splitName,
7292                            info.providerInfo.applicationInfo.versionCode);
7293                    // make sure this resolver is the default
7294                    installerInfo.isDefault = true;
7295                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7296                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7297                    // add a non-generic filter
7298                    installerInfo.filter = new IntentFilter();
7299                    // load resources from the correct package
7300                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7301                    resolveInfos.set(i, installerInfo);
7302                }
7303                continue;
7304            }
7305            // allow providers that have been explicitly exposed to instant applications
7306            if (!isEphemeralApp
7307                    && ((info.providerInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
7308                continue;
7309            }
7310            resolveInfos.remove(i);
7311        }
7312        return resolveInfos;
7313    }
7314
7315    @Override
7316    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7317        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7318        flags = updateFlagsForPackage(flags, userId, null);
7319        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7320        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7321                true /* requireFullPermission */, false /* checkShell */,
7322                "get installed packages");
7323
7324        // writer
7325        synchronized (mPackages) {
7326            ArrayList<PackageInfo> list;
7327            if (listUninstalled) {
7328                list = new ArrayList<>(mSettings.mPackages.size());
7329                for (PackageSetting ps : mSettings.mPackages.values()) {
7330                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7331                        continue;
7332                    }
7333                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7334                    if (pi != null) {
7335                        list.add(pi);
7336                    }
7337                }
7338            } else {
7339                list = new ArrayList<>(mPackages.size());
7340                for (PackageParser.Package p : mPackages.values()) {
7341                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7342                            Binder.getCallingUid(), userId)) {
7343                        continue;
7344                    }
7345                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7346                            p.mExtras, flags, userId);
7347                    if (pi != null) {
7348                        list.add(pi);
7349                    }
7350                }
7351            }
7352
7353            return new ParceledListSlice<>(list);
7354        }
7355    }
7356
7357    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7358            String[] permissions, boolean[] tmp, int flags, int userId) {
7359        int numMatch = 0;
7360        final PermissionsState permissionsState = ps.getPermissionsState();
7361        for (int i=0; i<permissions.length; i++) {
7362            final String permission = permissions[i];
7363            if (permissionsState.hasPermission(permission, userId)) {
7364                tmp[i] = true;
7365                numMatch++;
7366            } else {
7367                tmp[i] = false;
7368            }
7369        }
7370        if (numMatch == 0) {
7371            return;
7372        }
7373        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7374
7375        // The above might return null in cases of uninstalled apps or install-state
7376        // skew across users/profiles.
7377        if (pi != null) {
7378            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7379                if (numMatch == permissions.length) {
7380                    pi.requestedPermissions = permissions;
7381                } else {
7382                    pi.requestedPermissions = new String[numMatch];
7383                    numMatch = 0;
7384                    for (int i=0; i<permissions.length; i++) {
7385                        if (tmp[i]) {
7386                            pi.requestedPermissions[numMatch] = permissions[i];
7387                            numMatch++;
7388                        }
7389                    }
7390                }
7391            }
7392            list.add(pi);
7393        }
7394    }
7395
7396    @Override
7397    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7398            String[] permissions, int flags, int userId) {
7399        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7400        flags = updateFlagsForPackage(flags, userId, permissions);
7401        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7402                true /* requireFullPermission */, false /* checkShell */,
7403                "get packages holding permissions");
7404        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7405
7406        // writer
7407        synchronized (mPackages) {
7408            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7409            boolean[] tmpBools = new boolean[permissions.length];
7410            if (listUninstalled) {
7411                for (PackageSetting ps : mSettings.mPackages.values()) {
7412                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7413                            userId);
7414                }
7415            } else {
7416                for (PackageParser.Package pkg : mPackages.values()) {
7417                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7418                    if (ps != null) {
7419                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7420                                userId);
7421                    }
7422                }
7423            }
7424
7425            return new ParceledListSlice<PackageInfo>(list);
7426        }
7427    }
7428
7429    @Override
7430    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7431        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7432        flags = updateFlagsForApplication(flags, userId, null);
7433        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7434
7435        // writer
7436        synchronized (mPackages) {
7437            ArrayList<ApplicationInfo> list;
7438            if (listUninstalled) {
7439                list = new ArrayList<>(mSettings.mPackages.size());
7440                for (PackageSetting ps : mSettings.mPackages.values()) {
7441                    ApplicationInfo ai;
7442                    int effectiveFlags = flags;
7443                    if (ps.isSystem()) {
7444                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7445                    }
7446                    if (ps.pkg != null) {
7447                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7448                            continue;
7449                        }
7450                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7451                                ps.readUserState(userId), userId);
7452                        if (ai != null) {
7453                            rebaseEnabledOverlays(ai, userId);
7454                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7455                        }
7456                    } else {
7457                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7458                        // and already converts to externally visible package name
7459                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7460                                Binder.getCallingUid(), effectiveFlags, userId);
7461                    }
7462                    if (ai != null) {
7463                        list.add(ai);
7464                    }
7465                }
7466            } else {
7467                list = new ArrayList<>(mPackages.size());
7468                for (PackageParser.Package p : mPackages.values()) {
7469                    if (p.mExtras != null) {
7470                        PackageSetting ps = (PackageSetting) p.mExtras;
7471                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7472                            continue;
7473                        }
7474                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7475                                ps.readUserState(userId), userId);
7476                        if (ai != null) {
7477                            rebaseEnabledOverlays(ai, userId);
7478                            ai.packageName = resolveExternalPackageNameLPr(p);
7479                            list.add(ai);
7480                        }
7481                    }
7482                }
7483            }
7484
7485            return new ParceledListSlice<>(list);
7486        }
7487    }
7488
7489    @Override
7490    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7491        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7492            return null;
7493        }
7494
7495        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7496                "getEphemeralApplications");
7497        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7498                true /* requireFullPermission */, false /* checkShell */,
7499                "getEphemeralApplications");
7500        synchronized (mPackages) {
7501            List<InstantAppInfo> instantApps = mInstantAppRegistry
7502                    .getInstantAppsLPr(userId);
7503            if (instantApps != null) {
7504                return new ParceledListSlice<>(instantApps);
7505            }
7506        }
7507        return null;
7508    }
7509
7510    @Override
7511    public boolean isInstantApp(String packageName, int userId) {
7512        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7513                true /* requireFullPermission */, false /* checkShell */,
7514                "isInstantApp");
7515        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7516            return false;
7517        }
7518        int uid = Binder.getCallingUid();
7519        if (Process.isIsolated(uid)) {
7520            uid = mIsolatedOwners.get(uid);
7521        }
7522
7523        synchronized (mPackages) {
7524            final PackageSetting ps = mSettings.mPackages.get(packageName);
7525            PackageParser.Package pkg = mPackages.get(packageName);
7526            final boolean returnAllowed =
7527                    ps != null
7528                    && (isCallerSameApp(packageName, uid)
7529                            || mContext.checkCallingOrSelfPermission(
7530                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7531                                            == PERMISSION_GRANTED
7532                            || mInstantAppRegistry.isInstantAccessGranted(
7533                                    userId, UserHandle.getAppId(uid), ps.appId));
7534            if (returnAllowed) {
7535                return ps.getInstantApp(userId);
7536            }
7537        }
7538        return false;
7539    }
7540
7541    @Override
7542    public byte[] getInstantAppCookie(String packageName, int userId) {
7543        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7544            return null;
7545        }
7546
7547        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7548                true /* requireFullPermission */, false /* checkShell */,
7549                "getInstantAppCookie");
7550        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7551            return null;
7552        }
7553        synchronized (mPackages) {
7554            return mInstantAppRegistry.getInstantAppCookieLPw(
7555                    packageName, userId);
7556        }
7557    }
7558
7559    @Override
7560    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7561        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7562            return true;
7563        }
7564
7565        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7566                true /* requireFullPermission */, true /* checkShell */,
7567                "setInstantAppCookie");
7568        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7569            return false;
7570        }
7571        synchronized (mPackages) {
7572            return mInstantAppRegistry.setInstantAppCookieLPw(
7573                    packageName, cookie, userId);
7574        }
7575    }
7576
7577    @Override
7578    public Bitmap getInstantAppIcon(String packageName, int userId) {
7579        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7580            return null;
7581        }
7582
7583        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7584                "getInstantAppIcon");
7585
7586        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7587                true /* requireFullPermission */, false /* checkShell */,
7588                "getInstantAppIcon");
7589
7590        synchronized (mPackages) {
7591            return mInstantAppRegistry.getInstantAppIconLPw(
7592                    packageName, userId);
7593        }
7594    }
7595
7596    private boolean isCallerSameApp(String packageName, int uid) {
7597        PackageParser.Package pkg = mPackages.get(packageName);
7598        return pkg != null
7599                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7600    }
7601
7602    @Override
7603    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7604        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7605    }
7606
7607    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7608        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7609
7610        // reader
7611        synchronized (mPackages) {
7612            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7613            final int userId = UserHandle.getCallingUserId();
7614            while (i.hasNext()) {
7615                final PackageParser.Package p = i.next();
7616                if (p.applicationInfo == null) continue;
7617
7618                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7619                        && !p.applicationInfo.isDirectBootAware();
7620                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7621                        && p.applicationInfo.isDirectBootAware();
7622
7623                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7624                        && (!mSafeMode || isSystemApp(p))
7625                        && (matchesUnaware || matchesAware)) {
7626                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7627                    if (ps != null) {
7628                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7629                                ps.readUserState(userId), userId);
7630                        if (ai != null) {
7631                            rebaseEnabledOverlays(ai, userId);
7632                            finalList.add(ai);
7633                        }
7634                    }
7635                }
7636            }
7637        }
7638
7639        return finalList;
7640    }
7641
7642    @Override
7643    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7644        if (!sUserManager.exists(userId)) return null;
7645        flags = updateFlagsForComponent(flags, userId, name);
7646        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7647        // reader
7648        synchronized (mPackages) {
7649            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7650            PackageSetting ps = provider != null
7651                    ? mSettings.mPackages.get(provider.owner.packageName)
7652                    : null;
7653            if (ps != null) {
7654                final boolean isInstantApp = ps.getInstantApp(userId);
7655                // normal application; filter out instant application provider
7656                if (instantAppPkgName == null && isInstantApp) {
7657                    return null;
7658                }
7659                // instant application; filter out other instant applications
7660                if (instantAppPkgName != null
7661                        && isInstantApp
7662                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7663                    return null;
7664                }
7665                // instant application; filter out non-exposed provider
7666                if (instantAppPkgName != null
7667                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0) {
7668                    return null;
7669                }
7670                // provider not enabled
7671                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7672                    return null;
7673                }
7674                return PackageParser.generateProviderInfo(
7675                        provider, flags, ps.readUserState(userId), userId);
7676            }
7677            return null;
7678        }
7679    }
7680
7681    /**
7682     * @deprecated
7683     */
7684    @Deprecated
7685    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7686        // reader
7687        synchronized (mPackages) {
7688            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7689                    .entrySet().iterator();
7690            final int userId = UserHandle.getCallingUserId();
7691            while (i.hasNext()) {
7692                Map.Entry<String, PackageParser.Provider> entry = i.next();
7693                PackageParser.Provider p = entry.getValue();
7694                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7695
7696                if (ps != null && p.syncable
7697                        && (!mSafeMode || (p.info.applicationInfo.flags
7698                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7699                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7700                            ps.readUserState(userId), userId);
7701                    if (info != null) {
7702                        outNames.add(entry.getKey());
7703                        outInfo.add(info);
7704                    }
7705                }
7706            }
7707        }
7708    }
7709
7710    @Override
7711    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7712            int uid, int flags, String metaDataKey) {
7713        final int userId = processName != null ? UserHandle.getUserId(uid)
7714                : UserHandle.getCallingUserId();
7715        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7716        flags = updateFlagsForComponent(flags, userId, processName);
7717
7718        ArrayList<ProviderInfo> finalList = null;
7719        // reader
7720        synchronized (mPackages) {
7721            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7722            while (i.hasNext()) {
7723                final PackageParser.Provider p = i.next();
7724                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7725                if (ps != null && p.info.authority != null
7726                        && (processName == null
7727                                || (p.info.processName.equals(processName)
7728                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7729                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7730
7731                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7732                    // parameter.
7733                    if (metaDataKey != null
7734                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7735                        continue;
7736                    }
7737
7738                    if (finalList == null) {
7739                        finalList = new ArrayList<ProviderInfo>(3);
7740                    }
7741                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7742                            ps.readUserState(userId), userId);
7743                    if (info != null) {
7744                        finalList.add(info);
7745                    }
7746                }
7747            }
7748        }
7749
7750        if (finalList != null) {
7751            Collections.sort(finalList, mProviderInitOrderSorter);
7752            return new ParceledListSlice<ProviderInfo>(finalList);
7753        }
7754
7755        return ParceledListSlice.emptyList();
7756    }
7757
7758    @Override
7759    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7760        // reader
7761        synchronized (mPackages) {
7762            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7763            return PackageParser.generateInstrumentationInfo(i, flags);
7764        }
7765    }
7766
7767    @Override
7768    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7769            String targetPackage, int flags) {
7770        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7771    }
7772
7773    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7774            int flags) {
7775        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7776
7777        // reader
7778        synchronized (mPackages) {
7779            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7780            while (i.hasNext()) {
7781                final PackageParser.Instrumentation p = i.next();
7782                if (targetPackage == null
7783                        || targetPackage.equals(p.info.targetPackage)) {
7784                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7785                            flags);
7786                    if (ii != null) {
7787                        finalList.add(ii);
7788                    }
7789                }
7790            }
7791        }
7792
7793        return finalList;
7794    }
7795
7796    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7797        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7798        try {
7799            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7800        } finally {
7801            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7802        }
7803    }
7804
7805    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7806        final File[] files = dir.listFiles();
7807        if (ArrayUtils.isEmpty(files)) {
7808            Log.d(TAG, "No files in app dir " + dir);
7809            return;
7810        }
7811
7812        if (DEBUG_PACKAGE_SCANNING) {
7813            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7814                    + " flags=0x" + Integer.toHexString(parseFlags));
7815        }
7816        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7817                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7818
7819        // Submit files for parsing in parallel
7820        int fileCount = 0;
7821        for (File file : files) {
7822            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7823                    && !PackageInstallerService.isStageName(file.getName());
7824            if (!isPackage) {
7825                // Ignore entries which are not packages
7826                continue;
7827            }
7828            parallelPackageParser.submit(file, parseFlags);
7829            fileCount++;
7830        }
7831
7832        // Process results one by one
7833        for (; fileCount > 0; fileCount--) {
7834            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7835            Throwable throwable = parseResult.throwable;
7836            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7837
7838            if (throwable == null) {
7839                // Static shared libraries have synthetic package names
7840                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7841                    renameStaticSharedLibraryPackage(parseResult.pkg);
7842                }
7843                try {
7844                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7845                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7846                                currentTime, null);
7847                    }
7848                } catch (PackageManagerException e) {
7849                    errorCode = e.error;
7850                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7851                }
7852            } else if (throwable instanceof PackageParser.PackageParserException) {
7853                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7854                        throwable;
7855                errorCode = e.error;
7856                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7857            } else {
7858                throw new IllegalStateException("Unexpected exception occurred while parsing "
7859                        + parseResult.scanFile, throwable);
7860            }
7861
7862            // Delete invalid userdata apps
7863            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7864                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7865                logCriticalInfo(Log.WARN,
7866                        "Deleting invalid package at " + parseResult.scanFile);
7867                removeCodePathLI(parseResult.scanFile);
7868            }
7869        }
7870        parallelPackageParser.close();
7871    }
7872
7873    private static File getSettingsProblemFile() {
7874        File dataDir = Environment.getDataDirectory();
7875        File systemDir = new File(dataDir, "system");
7876        File fname = new File(systemDir, "uiderrors.txt");
7877        return fname;
7878    }
7879
7880    static void reportSettingsProblem(int priority, String msg) {
7881        logCriticalInfo(priority, msg);
7882    }
7883
7884    public static void logCriticalInfo(int priority, String msg) {
7885        Slog.println(priority, TAG, msg);
7886        EventLogTags.writePmCriticalInfo(msg);
7887        try {
7888            File fname = getSettingsProblemFile();
7889            FileOutputStream out = new FileOutputStream(fname, true);
7890            PrintWriter pw = new FastPrintWriter(out);
7891            SimpleDateFormat formatter = new SimpleDateFormat();
7892            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7893            pw.println(dateString + ": " + msg);
7894            pw.close();
7895            FileUtils.setPermissions(
7896                    fname.toString(),
7897                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7898                    -1, -1);
7899        } catch (java.io.IOException e) {
7900        }
7901    }
7902
7903    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7904        if (srcFile.isDirectory()) {
7905            final File baseFile = new File(pkg.baseCodePath);
7906            long maxModifiedTime = baseFile.lastModified();
7907            if (pkg.splitCodePaths != null) {
7908                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7909                    final File splitFile = new File(pkg.splitCodePaths[i]);
7910                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7911                }
7912            }
7913            return maxModifiedTime;
7914        }
7915        return srcFile.lastModified();
7916    }
7917
7918    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7919            final int policyFlags) throws PackageManagerException {
7920        // When upgrading from pre-N MR1, verify the package time stamp using the package
7921        // directory and not the APK file.
7922        final long lastModifiedTime = mIsPreNMR1Upgrade
7923                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7924        if (ps != null
7925                && ps.codePath.equals(srcFile)
7926                && ps.timeStamp == lastModifiedTime
7927                && !isCompatSignatureUpdateNeeded(pkg)
7928                && !isRecoverSignatureUpdateNeeded(pkg)) {
7929            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7930            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7931            ArraySet<PublicKey> signingKs;
7932            synchronized (mPackages) {
7933                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7934            }
7935            if (ps.signatures.mSignatures != null
7936                    && ps.signatures.mSignatures.length != 0
7937                    && signingKs != null) {
7938                // Optimization: reuse the existing cached certificates
7939                // if the package appears to be unchanged.
7940                pkg.mSignatures = ps.signatures.mSignatures;
7941                pkg.mSigningKeys = signingKs;
7942                return;
7943            }
7944
7945            Slog.w(TAG, "PackageSetting for " + ps.name
7946                    + " is missing signatures.  Collecting certs again to recover them.");
7947        } else {
7948            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7949        }
7950
7951        try {
7952            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7953            PackageParser.collectCertificates(pkg, policyFlags);
7954        } catch (PackageParserException e) {
7955            throw PackageManagerException.from(e);
7956        } finally {
7957            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7958        }
7959    }
7960
7961    /**
7962     *  Traces a package scan.
7963     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7964     */
7965    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7966            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7967        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7968        try {
7969            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7970        } finally {
7971            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7972        }
7973    }
7974
7975    /**
7976     *  Scans a package and returns the newly parsed package.
7977     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7978     */
7979    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7980            long currentTime, UserHandle user) throws PackageManagerException {
7981        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7982        PackageParser pp = new PackageParser();
7983        pp.setSeparateProcesses(mSeparateProcesses);
7984        pp.setOnlyCoreApps(mOnlyCore);
7985        pp.setDisplayMetrics(mMetrics);
7986        pp.setCallback(mPackageParserCallback);
7987
7988        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7989            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7990        }
7991
7992        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7993        final PackageParser.Package pkg;
7994        try {
7995            pkg = pp.parsePackage(scanFile, parseFlags);
7996        } catch (PackageParserException e) {
7997            throw PackageManagerException.from(e);
7998        } finally {
7999            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8000        }
8001
8002        // Static shared libraries have synthetic package names
8003        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8004            renameStaticSharedLibraryPackage(pkg);
8005        }
8006
8007        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8008    }
8009
8010    /**
8011     *  Scans a package and returns the newly parsed package.
8012     *  @throws PackageManagerException on a parse error.
8013     */
8014    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8015            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8016            throws PackageManagerException {
8017        // If the package has children and this is the first dive in the function
8018        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8019        // packages (parent and children) would be successfully scanned before the
8020        // actual scan since scanning mutates internal state and we want to atomically
8021        // install the package and its children.
8022        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8023            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8024                scanFlags |= SCAN_CHECK_ONLY;
8025            }
8026        } else {
8027            scanFlags &= ~SCAN_CHECK_ONLY;
8028        }
8029
8030        // Scan the parent
8031        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8032                scanFlags, currentTime, user);
8033
8034        // Scan the children
8035        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8036        for (int i = 0; i < childCount; i++) {
8037            PackageParser.Package childPackage = pkg.childPackages.get(i);
8038            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8039                    currentTime, user);
8040        }
8041
8042
8043        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8044            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8045        }
8046
8047        return scannedPkg;
8048    }
8049
8050    /**
8051     *  Scans a package and returns the newly parsed package.
8052     *  @throws PackageManagerException on a parse error.
8053     */
8054    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8055            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8056            throws PackageManagerException {
8057        PackageSetting ps = null;
8058        PackageSetting updatedPkg;
8059        // reader
8060        synchronized (mPackages) {
8061            // Look to see if we already know about this package.
8062            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8063            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8064                // This package has been renamed to its original name.  Let's
8065                // use that.
8066                ps = mSettings.getPackageLPr(oldName);
8067            }
8068            // If there was no original package, see one for the real package name.
8069            if (ps == null) {
8070                ps = mSettings.getPackageLPr(pkg.packageName);
8071            }
8072            // Check to see if this package could be hiding/updating a system
8073            // package.  Must look for it either under the original or real
8074            // package name depending on our state.
8075            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8076            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8077
8078            // If this is a package we don't know about on the system partition, we
8079            // may need to remove disabled child packages on the system partition
8080            // or may need to not add child packages if the parent apk is updated
8081            // on the data partition and no longer defines this child package.
8082            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8083                // If this is a parent package for an updated system app and this system
8084                // app got an OTA update which no longer defines some of the child packages
8085                // we have to prune them from the disabled system packages.
8086                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8087                if (disabledPs != null) {
8088                    final int scannedChildCount = (pkg.childPackages != null)
8089                            ? pkg.childPackages.size() : 0;
8090                    final int disabledChildCount = disabledPs.childPackageNames != null
8091                            ? disabledPs.childPackageNames.size() : 0;
8092                    for (int i = 0; i < disabledChildCount; i++) {
8093                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8094                        boolean disabledPackageAvailable = false;
8095                        for (int j = 0; j < scannedChildCount; j++) {
8096                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8097                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8098                                disabledPackageAvailable = true;
8099                                break;
8100                            }
8101                         }
8102                         if (!disabledPackageAvailable) {
8103                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8104                         }
8105                    }
8106                }
8107            }
8108        }
8109
8110        boolean updatedPkgBetter = false;
8111        // First check if this is a system package that may involve an update
8112        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8113            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8114            // it needs to drop FLAG_PRIVILEGED.
8115            if (locationIsPrivileged(scanFile)) {
8116                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8117            } else {
8118                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8119            }
8120
8121            if (ps != null && !ps.codePath.equals(scanFile)) {
8122                // The path has changed from what was last scanned...  check the
8123                // version of the new path against what we have stored to determine
8124                // what to do.
8125                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8126                if (pkg.mVersionCode <= ps.versionCode) {
8127                    // The system package has been updated and the code path does not match
8128                    // Ignore entry. Skip it.
8129                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8130                            + " ignored: updated version " + ps.versionCode
8131                            + " better than this " + pkg.mVersionCode);
8132                    if (!updatedPkg.codePath.equals(scanFile)) {
8133                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8134                                + ps.name + " changing from " + updatedPkg.codePathString
8135                                + " to " + scanFile);
8136                        updatedPkg.codePath = scanFile;
8137                        updatedPkg.codePathString = scanFile.toString();
8138                        updatedPkg.resourcePath = scanFile;
8139                        updatedPkg.resourcePathString = scanFile.toString();
8140                    }
8141                    updatedPkg.pkg = pkg;
8142                    updatedPkg.versionCode = pkg.mVersionCode;
8143
8144                    // Update the disabled system child packages to point to the package too.
8145                    final int childCount = updatedPkg.childPackageNames != null
8146                            ? updatedPkg.childPackageNames.size() : 0;
8147                    for (int i = 0; i < childCount; i++) {
8148                        String childPackageName = updatedPkg.childPackageNames.get(i);
8149                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8150                                childPackageName);
8151                        if (updatedChildPkg != null) {
8152                            updatedChildPkg.pkg = pkg;
8153                            updatedChildPkg.versionCode = pkg.mVersionCode;
8154                        }
8155                    }
8156
8157                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8158                            + scanFile + " ignored: updated version " + ps.versionCode
8159                            + " better than this " + pkg.mVersionCode);
8160                } else {
8161                    // The current app on the system partition is better than
8162                    // what we have updated to on the data partition; switch
8163                    // back to the system partition version.
8164                    // At this point, its safely assumed that package installation for
8165                    // apps in system partition will go through. If not there won't be a working
8166                    // version of the app
8167                    // writer
8168                    synchronized (mPackages) {
8169                        // Just remove the loaded entries from package lists.
8170                        mPackages.remove(ps.name);
8171                    }
8172
8173                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8174                            + " reverting from " + ps.codePathString
8175                            + ": new version " + pkg.mVersionCode
8176                            + " better than installed " + ps.versionCode);
8177
8178                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8179                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8180                    synchronized (mInstallLock) {
8181                        args.cleanUpResourcesLI();
8182                    }
8183                    synchronized (mPackages) {
8184                        mSettings.enableSystemPackageLPw(ps.name);
8185                    }
8186                    updatedPkgBetter = true;
8187                }
8188            }
8189        }
8190
8191        if (updatedPkg != null) {
8192            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8193            // initially
8194            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8195
8196            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8197            // flag set initially
8198            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8199                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8200            }
8201        }
8202
8203        // Verify certificates against what was last scanned
8204        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8205
8206        /*
8207         * A new system app appeared, but we already had a non-system one of the
8208         * same name installed earlier.
8209         */
8210        boolean shouldHideSystemApp = false;
8211        if (updatedPkg == null && ps != null
8212                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8213            /*
8214             * Check to make sure the signatures match first. If they don't,
8215             * wipe the installed application and its data.
8216             */
8217            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8218                    != PackageManager.SIGNATURE_MATCH) {
8219                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8220                        + " signatures don't match existing userdata copy; removing");
8221                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8222                        "scanPackageInternalLI")) {
8223                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8224                }
8225                ps = null;
8226            } else {
8227                /*
8228                 * If the newly-added system app is an older version than the
8229                 * already installed version, hide it. It will be scanned later
8230                 * and re-added like an update.
8231                 */
8232                if (pkg.mVersionCode <= ps.versionCode) {
8233                    shouldHideSystemApp = true;
8234                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8235                            + " but new version " + pkg.mVersionCode + " better than installed "
8236                            + ps.versionCode + "; hiding system");
8237                } else {
8238                    /*
8239                     * The newly found system app is a newer version that the
8240                     * one previously installed. Simply remove the
8241                     * already-installed application and replace it with our own
8242                     * while keeping the application data.
8243                     */
8244                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8245                            + " reverting from " + ps.codePathString + ": new version "
8246                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8247                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8248                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8249                    synchronized (mInstallLock) {
8250                        args.cleanUpResourcesLI();
8251                    }
8252                }
8253            }
8254        }
8255
8256        // The apk is forward locked (not public) if its code and resources
8257        // are kept in different files. (except for app in either system or
8258        // vendor path).
8259        // TODO grab this value from PackageSettings
8260        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8261            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8262                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8263            }
8264        }
8265
8266        // TODO: extend to support forward-locked splits
8267        String resourcePath = null;
8268        String baseResourcePath = null;
8269        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8270            if (ps != null && ps.resourcePathString != null) {
8271                resourcePath = ps.resourcePathString;
8272                baseResourcePath = ps.resourcePathString;
8273            } else {
8274                // Should not happen at all. Just log an error.
8275                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8276            }
8277        } else {
8278            resourcePath = pkg.codePath;
8279            baseResourcePath = pkg.baseCodePath;
8280        }
8281
8282        // Set application objects path explicitly.
8283        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8284        pkg.setApplicationInfoCodePath(pkg.codePath);
8285        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8286        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8287        pkg.setApplicationInfoResourcePath(resourcePath);
8288        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8289        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8290
8291        final int userId = ((user == null) ? 0 : user.getIdentifier());
8292        if (ps != null && ps.getInstantApp(userId)) {
8293            scanFlags |= SCAN_AS_INSTANT_APP;
8294        }
8295
8296        // Note that we invoke the following method only if we are about to unpack an application
8297        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8298                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8299
8300        /*
8301         * If the system app should be overridden by a previously installed
8302         * data, hide the system app now and let the /data/app scan pick it up
8303         * again.
8304         */
8305        if (shouldHideSystemApp) {
8306            synchronized (mPackages) {
8307                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8308            }
8309        }
8310
8311        return scannedPkg;
8312    }
8313
8314    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8315        // Derive the new package synthetic package name
8316        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8317                + pkg.staticSharedLibVersion);
8318    }
8319
8320    private static String fixProcessName(String defProcessName,
8321            String processName) {
8322        if (processName == null) {
8323            return defProcessName;
8324        }
8325        return processName;
8326    }
8327
8328    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8329            throws PackageManagerException {
8330        if (pkgSetting.signatures.mSignatures != null) {
8331            // Already existing package. Make sure signatures match
8332            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8333                    == PackageManager.SIGNATURE_MATCH;
8334            if (!match) {
8335                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8336                        == PackageManager.SIGNATURE_MATCH;
8337            }
8338            if (!match) {
8339                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8340                        == PackageManager.SIGNATURE_MATCH;
8341            }
8342            if (!match) {
8343                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8344                        + pkg.packageName + " signatures do not match the "
8345                        + "previously installed version; ignoring!");
8346            }
8347        }
8348
8349        // Check for shared user signatures
8350        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8351            // Already existing package. Make sure signatures match
8352            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8353                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8354            if (!match) {
8355                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8356                        == PackageManager.SIGNATURE_MATCH;
8357            }
8358            if (!match) {
8359                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8360                        == PackageManager.SIGNATURE_MATCH;
8361            }
8362            if (!match) {
8363                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8364                        "Package " + pkg.packageName
8365                        + " has no signatures that match those in shared user "
8366                        + pkgSetting.sharedUser.name + "; ignoring!");
8367            }
8368        }
8369    }
8370
8371    /**
8372     * Enforces that only the system UID or root's UID can call a method exposed
8373     * via Binder.
8374     *
8375     * @param message used as message if SecurityException is thrown
8376     * @throws SecurityException if the caller is not system or root
8377     */
8378    private static final void enforceSystemOrRoot(String message) {
8379        final int uid = Binder.getCallingUid();
8380        if (uid != Process.SYSTEM_UID && uid != 0) {
8381            throw new SecurityException(message);
8382        }
8383    }
8384
8385    @Override
8386    public void performFstrimIfNeeded() {
8387        enforceSystemOrRoot("Only the system can request fstrim");
8388
8389        // Before everything else, see whether we need to fstrim.
8390        try {
8391            IStorageManager sm = PackageHelper.getStorageManager();
8392            if (sm != null) {
8393                boolean doTrim = false;
8394                final long interval = android.provider.Settings.Global.getLong(
8395                        mContext.getContentResolver(),
8396                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8397                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8398                if (interval > 0) {
8399                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8400                    if (timeSinceLast > interval) {
8401                        doTrim = true;
8402                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8403                                + "; running immediately");
8404                    }
8405                }
8406                if (doTrim) {
8407                    final boolean dexOptDialogShown;
8408                    synchronized (mPackages) {
8409                        dexOptDialogShown = mDexOptDialogShown;
8410                    }
8411                    if (!isFirstBoot() && dexOptDialogShown) {
8412                        try {
8413                            ActivityManager.getService().showBootMessage(
8414                                    mContext.getResources().getString(
8415                                            R.string.android_upgrading_fstrim), true);
8416                        } catch (RemoteException e) {
8417                        }
8418                    }
8419                    sm.runMaintenance();
8420                }
8421            } else {
8422                Slog.e(TAG, "storageManager service unavailable!");
8423            }
8424        } catch (RemoteException e) {
8425            // Can't happen; StorageManagerService is local
8426        }
8427    }
8428
8429    @Override
8430    public void updatePackagesIfNeeded() {
8431        enforceSystemOrRoot("Only the system can request package update");
8432
8433        // We need to re-extract after an OTA.
8434        boolean causeUpgrade = isUpgrade();
8435
8436        // First boot or factory reset.
8437        // Note: we also handle devices that are upgrading to N right now as if it is their
8438        //       first boot, as they do not have profile data.
8439        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8440
8441        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8442        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8443
8444        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8445            return;
8446        }
8447
8448        List<PackageParser.Package> pkgs;
8449        synchronized (mPackages) {
8450            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8451        }
8452
8453        final long startTime = System.nanoTime();
8454        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8455                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8456
8457        final int elapsedTimeSeconds =
8458                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8459
8460        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8461        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8462        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8463        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8464        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8465    }
8466
8467    /**
8468     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8469     * containing statistics about the invocation. The array consists of three elements,
8470     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8471     * and {@code numberOfPackagesFailed}.
8472     */
8473    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8474            String compilerFilter) {
8475
8476        int numberOfPackagesVisited = 0;
8477        int numberOfPackagesOptimized = 0;
8478        int numberOfPackagesSkipped = 0;
8479        int numberOfPackagesFailed = 0;
8480        final int numberOfPackagesToDexopt = pkgs.size();
8481
8482        for (PackageParser.Package pkg : pkgs) {
8483            numberOfPackagesVisited++;
8484
8485            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8486                if (DEBUG_DEXOPT) {
8487                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8488                }
8489                numberOfPackagesSkipped++;
8490                continue;
8491            }
8492
8493            if (DEBUG_DEXOPT) {
8494                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8495                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8496            }
8497
8498            if (showDialog) {
8499                try {
8500                    ActivityManager.getService().showBootMessage(
8501                            mContext.getResources().getString(R.string.android_upgrading_apk,
8502                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8503                } catch (RemoteException e) {
8504                }
8505                synchronized (mPackages) {
8506                    mDexOptDialogShown = true;
8507                }
8508            }
8509
8510            // If the OTA updates a system app which was previously preopted to a non-preopted state
8511            // the app might end up being verified at runtime. That's because by default the apps
8512            // are verify-profile but for preopted apps there's no profile.
8513            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8514            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8515            // filter (by default interpret-only).
8516            // Note that at this stage unused apps are already filtered.
8517            if (isSystemApp(pkg) &&
8518                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8519                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8520                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8521            }
8522
8523            // checkProfiles is false to avoid merging profiles during boot which
8524            // might interfere with background compilation (b/28612421).
8525            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8526            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8527            // trade-off worth doing to save boot time work.
8528            int dexOptStatus = performDexOptTraced(pkg.packageName,
8529                    false /* checkProfiles */,
8530                    compilerFilter,
8531                    false /* force */);
8532            switch (dexOptStatus) {
8533                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8534                    numberOfPackagesOptimized++;
8535                    break;
8536                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8537                    numberOfPackagesSkipped++;
8538                    break;
8539                case PackageDexOptimizer.DEX_OPT_FAILED:
8540                    numberOfPackagesFailed++;
8541                    break;
8542                default:
8543                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8544                    break;
8545            }
8546        }
8547
8548        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8549                numberOfPackagesFailed };
8550    }
8551
8552    @Override
8553    public void notifyPackageUse(String packageName, int reason) {
8554        synchronized (mPackages) {
8555            PackageParser.Package p = mPackages.get(packageName);
8556            if (p == null) {
8557                return;
8558            }
8559            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8560        }
8561    }
8562
8563    @Override
8564    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8565        int userId = UserHandle.getCallingUserId();
8566        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8567        if (ai == null) {
8568            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8569                + loadingPackageName + ", user=" + userId);
8570            return;
8571        }
8572        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8573    }
8574
8575    // TODO: this is not used nor needed. Delete it.
8576    @Override
8577    public boolean performDexOptIfNeeded(String packageName) {
8578        int dexOptStatus = performDexOptTraced(packageName,
8579                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8580        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8581    }
8582
8583    @Override
8584    public boolean performDexOpt(String packageName,
8585            boolean checkProfiles, int compileReason, boolean force) {
8586        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8587                getCompilerFilterForReason(compileReason), force);
8588        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8589    }
8590
8591    @Override
8592    public boolean performDexOptMode(String packageName,
8593            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8594        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8595                targetCompilerFilter, force);
8596        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8597    }
8598
8599    private int performDexOptTraced(String packageName,
8600                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8601        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8602        try {
8603            return performDexOptInternal(packageName, checkProfiles,
8604                    targetCompilerFilter, force);
8605        } finally {
8606            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8607        }
8608    }
8609
8610    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8611    // if the package can now be considered up to date for the given filter.
8612    private int performDexOptInternal(String packageName,
8613                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8614        PackageParser.Package p;
8615        synchronized (mPackages) {
8616            p = mPackages.get(packageName);
8617            if (p == null) {
8618                // Package could not be found. Report failure.
8619                return PackageDexOptimizer.DEX_OPT_FAILED;
8620            }
8621            mPackageUsage.maybeWriteAsync(mPackages);
8622            mCompilerStats.maybeWriteAsync();
8623        }
8624        long callingId = Binder.clearCallingIdentity();
8625        try {
8626            synchronized (mInstallLock) {
8627                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8628                        targetCompilerFilter, force);
8629            }
8630        } finally {
8631            Binder.restoreCallingIdentity(callingId);
8632        }
8633    }
8634
8635    public ArraySet<String> getOptimizablePackages() {
8636        ArraySet<String> pkgs = new ArraySet<String>();
8637        synchronized (mPackages) {
8638            for (PackageParser.Package p : mPackages.values()) {
8639                if (PackageDexOptimizer.canOptimizePackage(p)) {
8640                    pkgs.add(p.packageName);
8641                }
8642            }
8643        }
8644        return pkgs;
8645    }
8646
8647    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8648            boolean checkProfiles, String targetCompilerFilter,
8649            boolean force) {
8650        // Select the dex optimizer based on the force parameter.
8651        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8652        //       allocate an object here.
8653        PackageDexOptimizer pdo = force
8654                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8655                : mPackageDexOptimizer;
8656
8657        // Dexopt all dependencies first. Note: we ignore the return value and march on
8658        // on errors.
8659        // Note that we are going to call performDexOpt on those libraries as many times as
8660        // they are referenced in packages. When we do a batch of performDexOpt (for example
8661        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8662        // and the first package that uses the library will dexopt it. The
8663        // others will see that the compiled code for the library is up to date.
8664        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8665        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8666        if (!deps.isEmpty()) {
8667            for (PackageParser.Package depPackage : deps) {
8668                // TODO: Analyze and investigate if we (should) profile libraries.
8669                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8670                        false /* checkProfiles */,
8671                        targetCompilerFilter,
8672                        getOrCreateCompilerPackageStats(depPackage),
8673                        true /* isUsedByOtherApps */);
8674            }
8675        }
8676        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8677                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8678                mDexManager.isUsedByOtherApps(p.packageName));
8679    }
8680
8681    // Performs dexopt on the used secondary dex files belonging to the given package.
8682    // Returns true if all dex files were process successfully (which could mean either dexopt or
8683    // skip). Returns false if any of the files caused errors.
8684    @Override
8685    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8686            boolean force) {
8687        mDexManager.reconcileSecondaryDexFiles(packageName);
8688        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8689    }
8690
8691    public boolean performDexOptSecondary(String packageName, int compileReason,
8692            boolean force) {
8693        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8694    }
8695
8696    /**
8697     * Reconcile the information we have about the secondary dex files belonging to
8698     * {@code packagName} and the actual dex files. For all dex files that were
8699     * deleted, update the internal records and delete the generated oat files.
8700     */
8701    @Override
8702    public void reconcileSecondaryDexFiles(String packageName) {
8703        mDexManager.reconcileSecondaryDexFiles(packageName);
8704    }
8705
8706    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8707    // a reference there.
8708    /*package*/ DexManager getDexManager() {
8709        return mDexManager;
8710    }
8711
8712    /**
8713     * Execute the background dexopt job immediately.
8714     */
8715    @Override
8716    public boolean runBackgroundDexoptJob() {
8717        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8718    }
8719
8720    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8721        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8722                || p.usesStaticLibraries != null) {
8723            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8724            Set<String> collectedNames = new HashSet<>();
8725            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8726
8727            retValue.remove(p);
8728
8729            return retValue;
8730        } else {
8731            return Collections.emptyList();
8732        }
8733    }
8734
8735    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8736            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8737        if (!collectedNames.contains(p.packageName)) {
8738            collectedNames.add(p.packageName);
8739            collected.add(p);
8740
8741            if (p.usesLibraries != null) {
8742                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8743                        null, collected, collectedNames);
8744            }
8745            if (p.usesOptionalLibraries != null) {
8746                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8747                        null, collected, collectedNames);
8748            }
8749            if (p.usesStaticLibraries != null) {
8750                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8751                        p.usesStaticLibrariesVersions, collected, collectedNames);
8752            }
8753        }
8754    }
8755
8756    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8757            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8758        final int libNameCount = libs.size();
8759        for (int i = 0; i < libNameCount; i++) {
8760            String libName = libs.get(i);
8761            int version = (versions != null && versions.length == libNameCount)
8762                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8763            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8764            if (libPkg != null) {
8765                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8766            }
8767        }
8768    }
8769
8770    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8771        synchronized (mPackages) {
8772            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8773            if (libEntry != null) {
8774                return mPackages.get(libEntry.apk);
8775            }
8776            return null;
8777        }
8778    }
8779
8780    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8781        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8782        if (versionedLib == null) {
8783            return null;
8784        }
8785        return versionedLib.get(version);
8786    }
8787
8788    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8789        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8790                pkg.staticSharedLibName);
8791        if (versionedLib == null) {
8792            return null;
8793        }
8794        int previousLibVersion = -1;
8795        final int versionCount = versionedLib.size();
8796        for (int i = 0; i < versionCount; i++) {
8797            final int libVersion = versionedLib.keyAt(i);
8798            if (libVersion < pkg.staticSharedLibVersion) {
8799                previousLibVersion = Math.max(previousLibVersion, libVersion);
8800            }
8801        }
8802        if (previousLibVersion >= 0) {
8803            return versionedLib.get(previousLibVersion);
8804        }
8805        return null;
8806    }
8807
8808    public void shutdown() {
8809        mPackageUsage.writeNow(mPackages);
8810        mCompilerStats.writeNow();
8811    }
8812
8813    @Override
8814    public void dumpProfiles(String packageName) {
8815        PackageParser.Package pkg;
8816        synchronized (mPackages) {
8817            pkg = mPackages.get(packageName);
8818            if (pkg == null) {
8819                throw new IllegalArgumentException("Unknown package: " + packageName);
8820            }
8821        }
8822        /* Only the shell, root, or the app user should be able to dump profiles. */
8823        int callingUid = Binder.getCallingUid();
8824        if (callingUid != Process.SHELL_UID &&
8825            callingUid != Process.ROOT_UID &&
8826            callingUid != pkg.applicationInfo.uid) {
8827            throw new SecurityException("dumpProfiles");
8828        }
8829
8830        synchronized (mInstallLock) {
8831            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8832            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8833            try {
8834                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8835                String codePaths = TextUtils.join(";", allCodePaths);
8836                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8837            } catch (InstallerException e) {
8838                Slog.w(TAG, "Failed to dump profiles", e);
8839            }
8840            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8841        }
8842    }
8843
8844    @Override
8845    public void forceDexOpt(String packageName) {
8846        enforceSystemOrRoot("forceDexOpt");
8847
8848        PackageParser.Package pkg;
8849        synchronized (mPackages) {
8850            pkg = mPackages.get(packageName);
8851            if (pkg == null) {
8852                throw new IllegalArgumentException("Unknown package: " + packageName);
8853            }
8854        }
8855
8856        synchronized (mInstallLock) {
8857            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8858
8859            // Whoever is calling forceDexOpt wants a fully compiled package.
8860            // Don't use profiles since that may cause compilation to be skipped.
8861            final int res = performDexOptInternalWithDependenciesLI(pkg,
8862                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8863                    true /* force */);
8864
8865            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8866            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8867                throw new IllegalStateException("Failed to dexopt: " + res);
8868            }
8869        }
8870    }
8871
8872    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8873        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8874            Slog.w(TAG, "Unable to update from " + oldPkg.name
8875                    + " to " + newPkg.packageName
8876                    + ": old package not in system partition");
8877            return false;
8878        } else if (mPackages.get(oldPkg.name) != null) {
8879            Slog.w(TAG, "Unable to update from " + oldPkg.name
8880                    + " to " + newPkg.packageName
8881                    + ": old package still exists");
8882            return false;
8883        }
8884        return true;
8885    }
8886
8887    void removeCodePathLI(File codePath) {
8888        if (codePath.isDirectory()) {
8889            try {
8890                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8891            } catch (InstallerException e) {
8892                Slog.w(TAG, "Failed to remove code path", e);
8893            }
8894        } else {
8895            codePath.delete();
8896        }
8897    }
8898
8899    private int[] resolveUserIds(int userId) {
8900        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8901    }
8902
8903    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8904        if (pkg == null) {
8905            Slog.wtf(TAG, "Package was null!", new Throwable());
8906            return;
8907        }
8908        clearAppDataLeafLIF(pkg, userId, flags);
8909        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8910        for (int i = 0; i < childCount; i++) {
8911            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8912        }
8913    }
8914
8915    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8916        final PackageSetting ps;
8917        synchronized (mPackages) {
8918            ps = mSettings.mPackages.get(pkg.packageName);
8919        }
8920        for (int realUserId : resolveUserIds(userId)) {
8921            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8922            try {
8923                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8924                        ceDataInode);
8925            } catch (InstallerException e) {
8926                Slog.w(TAG, String.valueOf(e));
8927            }
8928        }
8929    }
8930
8931    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8932        if (pkg == null) {
8933            Slog.wtf(TAG, "Package was null!", new Throwable());
8934            return;
8935        }
8936        destroyAppDataLeafLIF(pkg, userId, flags);
8937        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8938        for (int i = 0; i < childCount; i++) {
8939            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8940        }
8941    }
8942
8943    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8944        final PackageSetting ps;
8945        synchronized (mPackages) {
8946            ps = mSettings.mPackages.get(pkg.packageName);
8947        }
8948        for (int realUserId : resolveUserIds(userId)) {
8949            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8950            try {
8951                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8952                        ceDataInode);
8953            } catch (InstallerException e) {
8954                Slog.w(TAG, String.valueOf(e));
8955            }
8956            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8957        }
8958    }
8959
8960    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8961        if (pkg == null) {
8962            Slog.wtf(TAG, "Package was null!", new Throwable());
8963            return;
8964        }
8965        destroyAppProfilesLeafLIF(pkg);
8966        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8967        for (int i = 0; i < childCount; i++) {
8968            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8969        }
8970    }
8971
8972    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8973        try {
8974            mInstaller.destroyAppProfiles(pkg.packageName);
8975        } catch (InstallerException e) {
8976            Slog.w(TAG, String.valueOf(e));
8977        }
8978    }
8979
8980    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8981        if (pkg == null) {
8982            Slog.wtf(TAG, "Package was null!", new Throwable());
8983            return;
8984        }
8985        clearAppProfilesLeafLIF(pkg);
8986        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8987        for (int i = 0; i < childCount; i++) {
8988            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8989        }
8990    }
8991
8992    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8993        try {
8994            mInstaller.clearAppProfiles(pkg.packageName);
8995        } catch (InstallerException e) {
8996            Slog.w(TAG, String.valueOf(e));
8997        }
8998    }
8999
9000    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9001            long lastUpdateTime) {
9002        // Set parent install/update time
9003        PackageSetting ps = (PackageSetting) pkg.mExtras;
9004        if (ps != null) {
9005            ps.firstInstallTime = firstInstallTime;
9006            ps.lastUpdateTime = lastUpdateTime;
9007        }
9008        // Set children install/update time
9009        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9010        for (int i = 0; i < childCount; i++) {
9011            PackageParser.Package childPkg = pkg.childPackages.get(i);
9012            ps = (PackageSetting) childPkg.mExtras;
9013            if (ps != null) {
9014                ps.firstInstallTime = firstInstallTime;
9015                ps.lastUpdateTime = lastUpdateTime;
9016            }
9017        }
9018    }
9019
9020    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9021            PackageParser.Package changingLib) {
9022        if (file.path != null) {
9023            usesLibraryFiles.add(file.path);
9024            return;
9025        }
9026        PackageParser.Package p = mPackages.get(file.apk);
9027        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9028            // If we are doing this while in the middle of updating a library apk,
9029            // then we need to make sure to use that new apk for determining the
9030            // dependencies here.  (We haven't yet finished committing the new apk
9031            // to the package manager state.)
9032            if (p == null || p.packageName.equals(changingLib.packageName)) {
9033                p = changingLib;
9034            }
9035        }
9036        if (p != null) {
9037            usesLibraryFiles.addAll(p.getAllCodePaths());
9038        }
9039    }
9040
9041    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9042            PackageParser.Package changingLib) throws PackageManagerException {
9043        if (pkg == null) {
9044            return;
9045        }
9046        ArraySet<String> usesLibraryFiles = null;
9047        if (pkg.usesLibraries != null) {
9048            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9049                    null, null, pkg.packageName, changingLib, true, null);
9050        }
9051        if (pkg.usesStaticLibraries != null) {
9052            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9053                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9054                    pkg.packageName, changingLib, true, usesLibraryFiles);
9055        }
9056        if (pkg.usesOptionalLibraries != null) {
9057            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9058                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9059        }
9060        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9061            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9062        } else {
9063            pkg.usesLibraryFiles = null;
9064        }
9065    }
9066
9067    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9068            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9069            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9070            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9071            throws PackageManagerException {
9072        final int libCount = requestedLibraries.size();
9073        for (int i = 0; i < libCount; i++) {
9074            final String libName = requestedLibraries.get(i);
9075            final int libVersion = requiredVersions != null ? requiredVersions[i]
9076                    : SharedLibraryInfo.VERSION_UNDEFINED;
9077            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9078            if (libEntry == null) {
9079                if (required) {
9080                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9081                            "Package " + packageName + " requires unavailable shared library "
9082                                    + libName + "; failing!");
9083                } else {
9084                    Slog.w(TAG, "Package " + packageName
9085                            + " desires unavailable shared library "
9086                            + libName + "; ignoring!");
9087                }
9088            } else {
9089                if (requiredVersions != null && requiredCertDigests != null) {
9090                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9091                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9092                            "Package " + packageName + " requires unavailable static shared"
9093                                    + " library " + libName + " version "
9094                                    + libEntry.info.getVersion() + "; failing!");
9095                    }
9096
9097                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9098                    if (libPkg == null) {
9099                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9100                                "Package " + packageName + " requires unavailable static shared"
9101                                        + " library; failing!");
9102                    }
9103
9104                    String expectedCertDigest = requiredCertDigests[i];
9105                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9106                                libPkg.mSignatures[0]);
9107                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9108                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9109                                "Package " + packageName + " requires differently signed" +
9110                                        " static shared library; failing!");
9111                    }
9112                }
9113
9114                if (outUsedLibraries == null) {
9115                    outUsedLibraries = new ArraySet<>();
9116                }
9117                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9118            }
9119        }
9120        return outUsedLibraries;
9121    }
9122
9123    private static boolean hasString(List<String> list, List<String> which) {
9124        if (list == null) {
9125            return false;
9126        }
9127        for (int i=list.size()-1; i>=0; i--) {
9128            for (int j=which.size()-1; j>=0; j--) {
9129                if (which.get(j).equals(list.get(i))) {
9130                    return true;
9131                }
9132            }
9133        }
9134        return false;
9135    }
9136
9137    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9138            PackageParser.Package changingPkg) {
9139        ArrayList<PackageParser.Package> res = null;
9140        for (PackageParser.Package pkg : mPackages.values()) {
9141            if (changingPkg != null
9142                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9143                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9144                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9145                            changingPkg.staticSharedLibName)) {
9146                return null;
9147            }
9148            if (res == null) {
9149                res = new ArrayList<>();
9150            }
9151            res.add(pkg);
9152            try {
9153                updateSharedLibrariesLPr(pkg, changingPkg);
9154            } catch (PackageManagerException e) {
9155                // If a system app update or an app and a required lib missing we
9156                // delete the package and for updated system apps keep the data as
9157                // it is better for the user to reinstall than to be in an limbo
9158                // state. Also libs disappearing under an app should never happen
9159                // - just in case.
9160                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9161                    final int flags = pkg.isUpdatedSystemApp()
9162                            ? PackageManager.DELETE_KEEP_DATA : 0;
9163                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9164                            flags , null, true, null);
9165                }
9166                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9167            }
9168        }
9169        return res;
9170    }
9171
9172    /**
9173     * Derive the value of the {@code cpuAbiOverride} based on the provided
9174     * value and an optional stored value from the package settings.
9175     */
9176    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9177        String cpuAbiOverride = null;
9178
9179        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9180            cpuAbiOverride = null;
9181        } else if (abiOverride != null) {
9182            cpuAbiOverride = abiOverride;
9183        } else if (settings != null) {
9184            cpuAbiOverride = settings.cpuAbiOverrideString;
9185        }
9186
9187        return cpuAbiOverride;
9188    }
9189
9190    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9191            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9192                    throws PackageManagerException {
9193        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9194        // If the package has children and this is the first dive in the function
9195        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9196        // whether all packages (parent and children) would be successfully scanned
9197        // before the actual scan since scanning mutates internal state and we want
9198        // to atomically install the package and its children.
9199        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9200            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9201                scanFlags |= SCAN_CHECK_ONLY;
9202            }
9203        } else {
9204            scanFlags &= ~SCAN_CHECK_ONLY;
9205        }
9206
9207        final PackageParser.Package scannedPkg;
9208        try {
9209            // Scan the parent
9210            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9211            // Scan the children
9212            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9213            for (int i = 0; i < childCount; i++) {
9214                PackageParser.Package childPkg = pkg.childPackages.get(i);
9215                scanPackageLI(childPkg, policyFlags,
9216                        scanFlags, currentTime, user);
9217            }
9218        } finally {
9219            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9220        }
9221
9222        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9223            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9224        }
9225
9226        return scannedPkg;
9227    }
9228
9229    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9230            int scanFlags, long currentTime, @Nullable UserHandle user)
9231                    throws PackageManagerException {
9232        boolean success = false;
9233        try {
9234            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9235                    currentTime, user);
9236            success = true;
9237            return res;
9238        } finally {
9239            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9240                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9241                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9242                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9243                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9244            }
9245        }
9246    }
9247
9248    /**
9249     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9250     */
9251    private static boolean apkHasCode(String fileName) {
9252        StrictJarFile jarFile = null;
9253        try {
9254            jarFile = new StrictJarFile(fileName,
9255                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9256            return jarFile.findEntry("classes.dex") != null;
9257        } catch (IOException ignore) {
9258        } finally {
9259            try {
9260                if (jarFile != null) {
9261                    jarFile.close();
9262                }
9263            } catch (IOException ignore) {}
9264        }
9265        return false;
9266    }
9267
9268    /**
9269     * Enforces code policy for the package. This ensures that if an APK has
9270     * declared hasCode="true" in its manifest that the APK actually contains
9271     * code.
9272     *
9273     * @throws PackageManagerException If bytecode could not be found when it should exist
9274     */
9275    private static void assertCodePolicy(PackageParser.Package pkg)
9276            throws PackageManagerException {
9277        final boolean shouldHaveCode =
9278                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9279        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9280            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9281                    "Package " + pkg.baseCodePath + " code is missing");
9282        }
9283
9284        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9285            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9286                final boolean splitShouldHaveCode =
9287                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9288                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9289                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9290                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9291                }
9292            }
9293        }
9294    }
9295
9296    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9297            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9298                    throws PackageManagerException {
9299        if (DEBUG_PACKAGE_SCANNING) {
9300            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9301                Log.d(TAG, "Scanning package " + pkg.packageName);
9302        }
9303
9304        applyPolicy(pkg, policyFlags);
9305
9306        assertPackageIsValid(pkg, policyFlags, scanFlags);
9307
9308        // Initialize package source and resource directories
9309        final File scanFile = new File(pkg.codePath);
9310        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9311        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9312
9313        SharedUserSetting suid = null;
9314        PackageSetting pkgSetting = null;
9315
9316        // Getting the package setting may have a side-effect, so if we
9317        // are only checking if scan would succeed, stash a copy of the
9318        // old setting to restore at the end.
9319        PackageSetting nonMutatedPs = null;
9320
9321        // We keep references to the derived CPU Abis from settings in oder to reuse
9322        // them in the case where we're not upgrading or booting for the first time.
9323        String primaryCpuAbiFromSettings = null;
9324        String secondaryCpuAbiFromSettings = null;
9325
9326        // writer
9327        synchronized (mPackages) {
9328            if (pkg.mSharedUserId != null) {
9329                // SIDE EFFECTS; may potentially allocate a new shared user
9330                suid = mSettings.getSharedUserLPw(
9331                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9332                if (DEBUG_PACKAGE_SCANNING) {
9333                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9334                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9335                                + "): packages=" + suid.packages);
9336                }
9337            }
9338
9339            // Check if we are renaming from an original package name.
9340            PackageSetting origPackage = null;
9341            String realName = null;
9342            if (pkg.mOriginalPackages != null) {
9343                // This package may need to be renamed to a previously
9344                // installed name.  Let's check on that...
9345                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9346                if (pkg.mOriginalPackages.contains(renamed)) {
9347                    // This package had originally been installed as the
9348                    // original name, and we have already taken care of
9349                    // transitioning to the new one.  Just update the new
9350                    // one to continue using the old name.
9351                    realName = pkg.mRealPackage;
9352                    if (!pkg.packageName.equals(renamed)) {
9353                        // Callers into this function may have already taken
9354                        // care of renaming the package; only do it here if
9355                        // it is not already done.
9356                        pkg.setPackageName(renamed);
9357                    }
9358                } else {
9359                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9360                        if ((origPackage = mSettings.getPackageLPr(
9361                                pkg.mOriginalPackages.get(i))) != null) {
9362                            // We do have the package already installed under its
9363                            // original name...  should we use it?
9364                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9365                                // New package is not compatible with original.
9366                                origPackage = null;
9367                                continue;
9368                            } else if (origPackage.sharedUser != null) {
9369                                // Make sure uid is compatible between packages.
9370                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9371                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9372                                            + " to " + pkg.packageName + ": old uid "
9373                                            + origPackage.sharedUser.name
9374                                            + " differs from " + pkg.mSharedUserId);
9375                                    origPackage = null;
9376                                    continue;
9377                                }
9378                                // TODO: Add case when shared user id is added [b/28144775]
9379                            } else {
9380                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9381                                        + pkg.packageName + " to old name " + origPackage.name);
9382                            }
9383                            break;
9384                        }
9385                    }
9386                }
9387            }
9388
9389            if (mTransferedPackages.contains(pkg.packageName)) {
9390                Slog.w(TAG, "Package " + pkg.packageName
9391                        + " was transferred to another, but its .apk remains");
9392            }
9393
9394            // See comments in nonMutatedPs declaration
9395            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9396                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9397                if (foundPs != null) {
9398                    nonMutatedPs = new PackageSetting(foundPs);
9399                }
9400            }
9401
9402            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9403                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9404                if (foundPs != null) {
9405                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9406                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9407                }
9408            }
9409
9410            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9411            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9412                PackageManagerService.reportSettingsProblem(Log.WARN,
9413                        "Package " + pkg.packageName + " shared user changed from "
9414                                + (pkgSetting.sharedUser != null
9415                                        ? pkgSetting.sharedUser.name : "<nothing>")
9416                                + " to "
9417                                + (suid != null ? suid.name : "<nothing>")
9418                                + "; replacing with new");
9419                pkgSetting = null;
9420            }
9421            final PackageSetting oldPkgSetting =
9422                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9423            final PackageSetting disabledPkgSetting =
9424                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9425
9426            String[] usesStaticLibraries = null;
9427            if (pkg.usesStaticLibraries != null) {
9428                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9429                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9430            }
9431
9432            if (pkgSetting == null) {
9433                final String parentPackageName = (pkg.parentPackage != null)
9434                        ? pkg.parentPackage.packageName : null;
9435                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9436                // REMOVE SharedUserSetting from method; update in a separate call
9437                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9438                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9439                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9440                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9441                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9442                        true /*allowInstall*/, instantApp, parentPackageName,
9443                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9444                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9445                // SIDE EFFECTS; updates system state; move elsewhere
9446                if (origPackage != null) {
9447                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9448                }
9449                mSettings.addUserToSettingLPw(pkgSetting);
9450            } else {
9451                // REMOVE SharedUserSetting from method; update in a separate call.
9452                //
9453                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9454                // secondaryCpuAbi are not known at this point so we always update them
9455                // to null here, only to reset them at a later point.
9456                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9457                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9458                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9459                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9460                        UserManagerService.getInstance(), usesStaticLibraries,
9461                        pkg.usesStaticLibrariesVersions);
9462            }
9463            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9464            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9465
9466            // SIDE EFFECTS; modifies system state; move elsewhere
9467            if (pkgSetting.origPackage != null) {
9468                // If we are first transitioning from an original package,
9469                // fix up the new package's name now.  We need to do this after
9470                // looking up the package under its new name, so getPackageLP
9471                // can take care of fiddling things correctly.
9472                pkg.setPackageName(origPackage.name);
9473
9474                // File a report about this.
9475                String msg = "New package " + pkgSetting.realName
9476                        + " renamed to replace old package " + pkgSetting.name;
9477                reportSettingsProblem(Log.WARN, msg);
9478
9479                // Make a note of it.
9480                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9481                    mTransferedPackages.add(origPackage.name);
9482                }
9483
9484                // No longer need to retain this.
9485                pkgSetting.origPackage = null;
9486            }
9487
9488            // SIDE EFFECTS; modifies system state; move elsewhere
9489            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9490                // Make a note of it.
9491                mTransferedPackages.add(pkg.packageName);
9492            }
9493
9494            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9495                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9496            }
9497
9498            if ((scanFlags & SCAN_BOOTING) == 0
9499                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9500                // Check all shared libraries and map to their actual file path.
9501                // We only do this here for apps not on a system dir, because those
9502                // are the only ones that can fail an install due to this.  We
9503                // will take care of the system apps by updating all of their
9504                // library paths after the scan is done. Also during the initial
9505                // scan don't update any libs as we do this wholesale after all
9506                // apps are scanned to avoid dependency based scanning.
9507                updateSharedLibrariesLPr(pkg, null);
9508            }
9509
9510            if (mFoundPolicyFile) {
9511                SELinuxMMAC.assignSeInfoValue(pkg);
9512            }
9513            pkg.applicationInfo.uid = pkgSetting.appId;
9514            pkg.mExtras = pkgSetting;
9515
9516
9517            // Static shared libs have same package with different versions where
9518            // we internally use a synthetic package name to allow multiple versions
9519            // of the same package, therefore we need to compare signatures against
9520            // the package setting for the latest library version.
9521            PackageSetting signatureCheckPs = pkgSetting;
9522            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9523                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9524                if (libraryEntry != null) {
9525                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9526                }
9527            }
9528
9529            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9530                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9531                    // We just determined the app is signed correctly, so bring
9532                    // over the latest parsed certs.
9533                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9534                } else {
9535                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9536                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9537                                "Package " + pkg.packageName + " upgrade keys do not match the "
9538                                + "previously installed version");
9539                    } else {
9540                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9541                        String msg = "System package " + pkg.packageName
9542                                + " signature changed; retaining data.";
9543                        reportSettingsProblem(Log.WARN, msg);
9544                    }
9545                }
9546            } else {
9547                try {
9548                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9549                    verifySignaturesLP(signatureCheckPs, pkg);
9550                    // We just determined the app is signed correctly, so bring
9551                    // over the latest parsed certs.
9552                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9553                } catch (PackageManagerException e) {
9554                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9555                        throw e;
9556                    }
9557                    // The signature has changed, but this package is in the system
9558                    // image...  let's recover!
9559                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9560                    // However...  if this package is part of a shared user, but it
9561                    // doesn't match the signature of the shared user, let's fail.
9562                    // What this means is that you can't change the signatures
9563                    // associated with an overall shared user, which doesn't seem all
9564                    // that unreasonable.
9565                    if (signatureCheckPs.sharedUser != null) {
9566                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9567                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9568                            throw new PackageManagerException(
9569                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9570                                    "Signature mismatch for shared user: "
9571                                            + pkgSetting.sharedUser);
9572                        }
9573                    }
9574                    // File a report about this.
9575                    String msg = "System package " + pkg.packageName
9576                            + " signature changed; retaining data.";
9577                    reportSettingsProblem(Log.WARN, msg);
9578                }
9579            }
9580
9581            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9582                // This package wants to adopt ownership of permissions from
9583                // another package.
9584                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9585                    final String origName = pkg.mAdoptPermissions.get(i);
9586                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9587                    if (orig != null) {
9588                        if (verifyPackageUpdateLPr(orig, pkg)) {
9589                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9590                                    + pkg.packageName);
9591                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9592                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9593                        }
9594                    }
9595                }
9596            }
9597        }
9598
9599        pkg.applicationInfo.processName = fixProcessName(
9600                pkg.applicationInfo.packageName,
9601                pkg.applicationInfo.processName);
9602
9603        if (pkg != mPlatformPackage) {
9604            // Get all of our default paths setup
9605            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9606        }
9607
9608        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9609
9610        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9611            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9612                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9613                derivePackageAbi(
9614                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9615                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9616
9617                // Some system apps still use directory structure for native libraries
9618                // in which case we might end up not detecting abi solely based on apk
9619                // structure. Try to detect abi based on directory structure.
9620                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9621                        pkg.applicationInfo.primaryCpuAbi == null) {
9622                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9623                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9624                }
9625            } else {
9626                // This is not a first boot or an upgrade, don't bother deriving the
9627                // ABI during the scan. Instead, trust the value that was stored in the
9628                // package setting.
9629                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9630                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9631
9632                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9633
9634                if (DEBUG_ABI_SELECTION) {
9635                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9636                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9637                        pkg.applicationInfo.secondaryCpuAbi);
9638                }
9639            }
9640        } else {
9641            if ((scanFlags & SCAN_MOVE) != 0) {
9642                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9643                // but we already have this packages package info in the PackageSetting. We just
9644                // use that and derive the native library path based on the new codepath.
9645                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9646                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9647            }
9648
9649            // Set native library paths again. For moves, the path will be updated based on the
9650            // ABIs we've determined above. For non-moves, the path will be updated based on the
9651            // ABIs we determined during compilation, but the path will depend on the final
9652            // package path (after the rename away from the stage path).
9653            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9654        }
9655
9656        // This is a special case for the "system" package, where the ABI is
9657        // dictated by the zygote configuration (and init.rc). We should keep track
9658        // of this ABI so that we can deal with "normal" applications that run under
9659        // the same UID correctly.
9660        if (mPlatformPackage == pkg) {
9661            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9662                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9663        }
9664
9665        // If there's a mismatch between the abi-override in the package setting
9666        // and the abiOverride specified for the install. Warn about this because we
9667        // would've already compiled the app without taking the package setting into
9668        // account.
9669        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9670            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9671                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9672                        " for package " + pkg.packageName);
9673            }
9674        }
9675
9676        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9677        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9678        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9679
9680        // Copy the derived override back to the parsed package, so that we can
9681        // update the package settings accordingly.
9682        pkg.cpuAbiOverride = cpuAbiOverride;
9683
9684        if (DEBUG_ABI_SELECTION) {
9685            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9686                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9687                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9688        }
9689
9690        // Push the derived path down into PackageSettings so we know what to
9691        // clean up at uninstall time.
9692        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9693
9694        if (DEBUG_ABI_SELECTION) {
9695            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9696                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9697                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9698        }
9699
9700        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9701        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9702            // We don't do this here during boot because we can do it all
9703            // at once after scanning all existing packages.
9704            //
9705            // We also do this *before* we perform dexopt on this package, so that
9706            // we can avoid redundant dexopts, and also to make sure we've got the
9707            // code and package path correct.
9708            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9709        }
9710
9711        if (mFactoryTest && pkg.requestedPermissions.contains(
9712                android.Manifest.permission.FACTORY_TEST)) {
9713            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9714        }
9715
9716        if (isSystemApp(pkg)) {
9717            pkgSetting.isOrphaned = true;
9718        }
9719
9720        // Take care of first install / last update times.
9721        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9722        if (currentTime != 0) {
9723            if (pkgSetting.firstInstallTime == 0) {
9724                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9725            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9726                pkgSetting.lastUpdateTime = currentTime;
9727            }
9728        } else if (pkgSetting.firstInstallTime == 0) {
9729            // We need *something*.  Take time time stamp of the file.
9730            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9731        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9732            if (scanFileTime != pkgSetting.timeStamp) {
9733                // A package on the system image has changed; consider this
9734                // to be an update.
9735                pkgSetting.lastUpdateTime = scanFileTime;
9736            }
9737        }
9738        pkgSetting.setTimeStamp(scanFileTime);
9739
9740        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9741            if (nonMutatedPs != null) {
9742                synchronized (mPackages) {
9743                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9744                }
9745            }
9746        } else {
9747            final int userId = user == null ? 0 : user.getIdentifier();
9748            // Modify state for the given package setting
9749            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9750                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9751            if (pkgSetting.getInstantApp(userId)) {
9752                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9753            }
9754        }
9755        return pkg;
9756    }
9757
9758    /**
9759     * Applies policy to the parsed package based upon the given policy flags.
9760     * Ensures the package is in a good state.
9761     * <p>
9762     * Implementation detail: This method must NOT have any side effect. It would
9763     * ideally be static, but, it requires locks to read system state.
9764     */
9765    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9766        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9767            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9768            if (pkg.applicationInfo.isDirectBootAware()) {
9769                // we're direct boot aware; set for all components
9770                for (PackageParser.Service s : pkg.services) {
9771                    s.info.encryptionAware = s.info.directBootAware = true;
9772                }
9773                for (PackageParser.Provider p : pkg.providers) {
9774                    p.info.encryptionAware = p.info.directBootAware = true;
9775                }
9776                for (PackageParser.Activity a : pkg.activities) {
9777                    a.info.encryptionAware = a.info.directBootAware = true;
9778                }
9779                for (PackageParser.Activity r : pkg.receivers) {
9780                    r.info.encryptionAware = r.info.directBootAware = true;
9781                }
9782            }
9783        } else {
9784            // Only allow system apps to be flagged as core apps.
9785            pkg.coreApp = false;
9786            // clear flags not applicable to regular apps
9787            pkg.applicationInfo.privateFlags &=
9788                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9789            pkg.applicationInfo.privateFlags &=
9790                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9791        }
9792        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9793
9794        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9795            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9796        }
9797
9798        if (!isSystemApp(pkg)) {
9799            // Only system apps can use these features.
9800            pkg.mOriginalPackages = null;
9801            pkg.mRealPackage = null;
9802            pkg.mAdoptPermissions = null;
9803        }
9804    }
9805
9806    /**
9807     * Asserts the parsed package is valid according to the given policy. If the
9808     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9809     * <p>
9810     * Implementation detail: This method must NOT have any side effects. It would
9811     * ideally be static, but, it requires locks to read system state.
9812     *
9813     * @throws PackageManagerException If the package fails any of the validation checks
9814     */
9815    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9816            throws PackageManagerException {
9817        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9818            assertCodePolicy(pkg);
9819        }
9820
9821        if (pkg.applicationInfo.getCodePath() == null ||
9822                pkg.applicationInfo.getResourcePath() == null) {
9823            // Bail out. The resource and code paths haven't been set.
9824            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9825                    "Code and resource paths haven't been set correctly");
9826        }
9827
9828        // Make sure we're not adding any bogus keyset info
9829        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9830        ksms.assertScannedPackageValid(pkg);
9831
9832        synchronized (mPackages) {
9833            // The special "android" package can only be defined once
9834            if (pkg.packageName.equals("android")) {
9835                if (mAndroidApplication != null) {
9836                    Slog.w(TAG, "*************************************************");
9837                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9838                    Slog.w(TAG, " codePath=" + pkg.codePath);
9839                    Slog.w(TAG, "*************************************************");
9840                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9841                            "Core android package being redefined.  Skipping.");
9842                }
9843            }
9844
9845            // A package name must be unique; don't allow duplicates
9846            if (mPackages.containsKey(pkg.packageName)) {
9847                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9848                        "Application package " + pkg.packageName
9849                        + " already installed.  Skipping duplicate.");
9850            }
9851
9852            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9853                // Static libs have a synthetic package name containing the version
9854                // but we still want the base name to be unique.
9855                if (mPackages.containsKey(pkg.manifestPackageName)) {
9856                    throw new PackageManagerException(
9857                            "Duplicate static shared lib provider package");
9858                }
9859
9860                // Static shared libraries should have at least O target SDK
9861                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9862                    throw new PackageManagerException(
9863                            "Packages declaring static-shared libs must target O SDK or higher");
9864                }
9865
9866                // Package declaring static a shared lib cannot be instant apps
9867                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9868                    throw new PackageManagerException(
9869                            "Packages declaring static-shared libs cannot be instant apps");
9870                }
9871
9872                // Package declaring static a shared lib cannot be renamed since the package
9873                // name is synthetic and apps can't code around package manager internals.
9874                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9875                    throw new PackageManagerException(
9876                            "Packages declaring static-shared libs cannot be renamed");
9877                }
9878
9879                // Package declaring static a shared lib cannot declare child packages
9880                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9881                    throw new PackageManagerException(
9882                            "Packages declaring static-shared libs cannot have child packages");
9883                }
9884
9885                // Package declaring static a shared lib cannot declare dynamic libs
9886                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9887                    throw new PackageManagerException(
9888                            "Packages declaring static-shared libs cannot declare dynamic libs");
9889                }
9890
9891                // Package declaring static a shared lib cannot declare shared users
9892                if (pkg.mSharedUserId != null) {
9893                    throw new PackageManagerException(
9894                            "Packages declaring static-shared libs cannot declare shared users");
9895                }
9896
9897                // Static shared libs cannot declare activities
9898                if (!pkg.activities.isEmpty()) {
9899                    throw new PackageManagerException(
9900                            "Static shared libs cannot declare activities");
9901                }
9902
9903                // Static shared libs cannot declare services
9904                if (!pkg.services.isEmpty()) {
9905                    throw new PackageManagerException(
9906                            "Static shared libs cannot declare services");
9907                }
9908
9909                // Static shared libs cannot declare providers
9910                if (!pkg.providers.isEmpty()) {
9911                    throw new PackageManagerException(
9912                            "Static shared libs cannot declare content providers");
9913                }
9914
9915                // Static shared libs cannot declare receivers
9916                if (!pkg.receivers.isEmpty()) {
9917                    throw new PackageManagerException(
9918                            "Static shared libs cannot declare broadcast receivers");
9919                }
9920
9921                // Static shared libs cannot declare permission groups
9922                if (!pkg.permissionGroups.isEmpty()) {
9923                    throw new PackageManagerException(
9924                            "Static shared libs cannot declare permission groups");
9925                }
9926
9927                // Static shared libs cannot declare permissions
9928                if (!pkg.permissions.isEmpty()) {
9929                    throw new PackageManagerException(
9930                            "Static shared libs cannot declare permissions");
9931                }
9932
9933                // Static shared libs cannot declare protected broadcasts
9934                if (pkg.protectedBroadcasts != null) {
9935                    throw new PackageManagerException(
9936                            "Static shared libs cannot declare protected broadcasts");
9937                }
9938
9939                // Static shared libs cannot be overlay targets
9940                if (pkg.mOverlayTarget != null) {
9941                    throw new PackageManagerException(
9942                            "Static shared libs cannot be overlay targets");
9943                }
9944
9945                // The version codes must be ordered as lib versions
9946                int minVersionCode = Integer.MIN_VALUE;
9947                int maxVersionCode = Integer.MAX_VALUE;
9948
9949                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9950                        pkg.staticSharedLibName);
9951                if (versionedLib != null) {
9952                    final int versionCount = versionedLib.size();
9953                    for (int i = 0; i < versionCount; i++) {
9954                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9955                        // TODO: We will change version code to long, so in the new API it is long
9956                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9957                                .getVersionCode();
9958                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9959                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9960                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9961                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9962                        } else {
9963                            minVersionCode = maxVersionCode = libVersionCode;
9964                            break;
9965                        }
9966                    }
9967                }
9968                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9969                    throw new PackageManagerException("Static shared"
9970                            + " lib version codes must be ordered as lib versions");
9971                }
9972            }
9973
9974            // Only privileged apps and updated privileged apps can add child packages.
9975            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9976                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9977                    throw new PackageManagerException("Only privileged apps can add child "
9978                            + "packages. Ignoring package " + pkg.packageName);
9979                }
9980                final int childCount = pkg.childPackages.size();
9981                for (int i = 0; i < childCount; i++) {
9982                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9983                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9984                            childPkg.packageName)) {
9985                        throw new PackageManagerException("Can't override child of "
9986                                + "another disabled app. Ignoring package " + pkg.packageName);
9987                    }
9988                }
9989            }
9990
9991            // If we're only installing presumed-existing packages, require that the
9992            // scanned APK is both already known and at the path previously established
9993            // for it.  Previously unknown packages we pick up normally, but if we have an
9994            // a priori expectation about this package's install presence, enforce it.
9995            // With a singular exception for new system packages. When an OTA contains
9996            // a new system package, we allow the codepath to change from a system location
9997            // to the user-installed location. If we don't allow this change, any newer,
9998            // user-installed version of the application will be ignored.
9999            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10000                if (mExpectingBetter.containsKey(pkg.packageName)) {
10001                    logCriticalInfo(Log.WARN,
10002                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10003                } else {
10004                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10005                    if (known != null) {
10006                        if (DEBUG_PACKAGE_SCANNING) {
10007                            Log.d(TAG, "Examining " + pkg.codePath
10008                                    + " and requiring known paths " + known.codePathString
10009                                    + " & " + known.resourcePathString);
10010                        }
10011                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10012                                || !pkg.applicationInfo.getResourcePath().equals(
10013                                        known.resourcePathString)) {
10014                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10015                                    "Application package " + pkg.packageName
10016                                    + " found at " + pkg.applicationInfo.getCodePath()
10017                                    + " but expected at " + known.codePathString
10018                                    + "; ignoring.");
10019                        }
10020                    }
10021                }
10022            }
10023
10024            // Verify that this new package doesn't have any content providers
10025            // that conflict with existing packages.  Only do this if the
10026            // package isn't already installed, since we don't want to break
10027            // things that are installed.
10028            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10029                final int N = pkg.providers.size();
10030                int i;
10031                for (i=0; i<N; i++) {
10032                    PackageParser.Provider p = pkg.providers.get(i);
10033                    if (p.info.authority != null) {
10034                        String names[] = p.info.authority.split(";");
10035                        for (int j = 0; j < names.length; j++) {
10036                            if (mProvidersByAuthority.containsKey(names[j])) {
10037                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10038                                final String otherPackageName =
10039                                        ((other != null && other.getComponentName() != null) ?
10040                                                other.getComponentName().getPackageName() : "?");
10041                                throw new PackageManagerException(
10042                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10043                                        "Can't install because provider name " + names[j]
10044                                                + " (in package " + pkg.applicationInfo.packageName
10045                                                + ") is already used by " + otherPackageName);
10046                            }
10047                        }
10048                    }
10049                }
10050            }
10051        }
10052    }
10053
10054    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10055            int type, String declaringPackageName, int declaringVersionCode) {
10056        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10057        if (versionedLib == null) {
10058            versionedLib = new SparseArray<>();
10059            mSharedLibraries.put(name, versionedLib);
10060            if (type == SharedLibraryInfo.TYPE_STATIC) {
10061                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10062            }
10063        } else if (versionedLib.indexOfKey(version) >= 0) {
10064            return false;
10065        }
10066        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10067                version, type, declaringPackageName, declaringVersionCode);
10068        versionedLib.put(version, libEntry);
10069        return true;
10070    }
10071
10072    private boolean removeSharedLibraryLPw(String name, int version) {
10073        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10074        if (versionedLib == null) {
10075            return false;
10076        }
10077        final int libIdx = versionedLib.indexOfKey(version);
10078        if (libIdx < 0) {
10079            return false;
10080        }
10081        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10082        versionedLib.remove(version);
10083        if (versionedLib.size() <= 0) {
10084            mSharedLibraries.remove(name);
10085            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10086                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10087                        .getPackageName());
10088            }
10089        }
10090        return true;
10091    }
10092
10093    /**
10094     * Adds a scanned package to the system. When this method is finished, the package will
10095     * be available for query, resolution, etc...
10096     */
10097    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10098            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10099        final String pkgName = pkg.packageName;
10100        if (mCustomResolverComponentName != null &&
10101                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10102            setUpCustomResolverActivity(pkg);
10103        }
10104
10105        if (pkg.packageName.equals("android")) {
10106            synchronized (mPackages) {
10107                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10108                    // Set up information for our fall-back user intent resolution activity.
10109                    mPlatformPackage = pkg;
10110                    pkg.mVersionCode = mSdkVersion;
10111                    mAndroidApplication = pkg.applicationInfo;
10112                    if (!mResolverReplaced) {
10113                        mResolveActivity.applicationInfo = mAndroidApplication;
10114                        mResolveActivity.name = ResolverActivity.class.getName();
10115                        mResolveActivity.packageName = mAndroidApplication.packageName;
10116                        mResolveActivity.processName = "system:ui";
10117                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10118                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10119                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10120                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10121                        mResolveActivity.exported = true;
10122                        mResolveActivity.enabled = true;
10123                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10124                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10125                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10126                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10127                                | ActivityInfo.CONFIG_ORIENTATION
10128                                | ActivityInfo.CONFIG_KEYBOARD
10129                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10130                        mResolveInfo.activityInfo = mResolveActivity;
10131                        mResolveInfo.priority = 0;
10132                        mResolveInfo.preferredOrder = 0;
10133                        mResolveInfo.match = 0;
10134                        mResolveComponentName = new ComponentName(
10135                                mAndroidApplication.packageName, mResolveActivity.name);
10136                    }
10137                }
10138            }
10139        }
10140
10141        ArrayList<PackageParser.Package> clientLibPkgs = null;
10142        // writer
10143        synchronized (mPackages) {
10144            boolean hasStaticSharedLibs = false;
10145
10146            // Any app can add new static shared libraries
10147            if (pkg.staticSharedLibName != null) {
10148                // Static shared libs don't allow renaming as they have synthetic package
10149                // names to allow install of multiple versions, so use name from manifest.
10150                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10151                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10152                        pkg.manifestPackageName, pkg.mVersionCode)) {
10153                    hasStaticSharedLibs = true;
10154                } else {
10155                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10156                                + pkg.staticSharedLibName + " already exists; skipping");
10157                }
10158                // Static shared libs cannot be updated once installed since they
10159                // use synthetic package name which includes the version code, so
10160                // not need to update other packages's shared lib dependencies.
10161            }
10162
10163            if (!hasStaticSharedLibs
10164                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10165                // Only system apps can add new dynamic shared libraries.
10166                if (pkg.libraryNames != null) {
10167                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10168                        String name = pkg.libraryNames.get(i);
10169                        boolean allowed = false;
10170                        if (pkg.isUpdatedSystemApp()) {
10171                            // New library entries can only be added through the
10172                            // system image.  This is important to get rid of a lot
10173                            // of nasty edge cases: for example if we allowed a non-
10174                            // system update of the app to add a library, then uninstalling
10175                            // the update would make the library go away, and assumptions
10176                            // we made such as through app install filtering would now
10177                            // have allowed apps on the device which aren't compatible
10178                            // with it.  Better to just have the restriction here, be
10179                            // conservative, and create many fewer cases that can negatively
10180                            // impact the user experience.
10181                            final PackageSetting sysPs = mSettings
10182                                    .getDisabledSystemPkgLPr(pkg.packageName);
10183                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10184                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10185                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10186                                        allowed = true;
10187                                        break;
10188                                    }
10189                                }
10190                            }
10191                        } else {
10192                            allowed = true;
10193                        }
10194                        if (allowed) {
10195                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10196                                    SharedLibraryInfo.VERSION_UNDEFINED,
10197                                    SharedLibraryInfo.TYPE_DYNAMIC,
10198                                    pkg.packageName, pkg.mVersionCode)) {
10199                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10200                                        + name + " already exists; skipping");
10201                            }
10202                        } else {
10203                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10204                                    + name + " that is not declared on system image; skipping");
10205                        }
10206                    }
10207
10208                    if ((scanFlags & SCAN_BOOTING) == 0) {
10209                        // If we are not booting, we need to update any applications
10210                        // that are clients of our shared library.  If we are booting,
10211                        // this will all be done once the scan is complete.
10212                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10213                    }
10214                }
10215            }
10216        }
10217
10218        if ((scanFlags & SCAN_BOOTING) != 0) {
10219            // No apps can run during boot scan, so they don't need to be frozen
10220        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10221            // Caller asked to not kill app, so it's probably not frozen
10222        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10223            // Caller asked us to ignore frozen check for some reason; they
10224            // probably didn't know the package name
10225        } else {
10226            // We're doing major surgery on this package, so it better be frozen
10227            // right now to keep it from launching
10228            checkPackageFrozen(pkgName);
10229        }
10230
10231        // Also need to kill any apps that are dependent on the library.
10232        if (clientLibPkgs != null) {
10233            for (int i=0; i<clientLibPkgs.size(); i++) {
10234                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10235                killApplication(clientPkg.applicationInfo.packageName,
10236                        clientPkg.applicationInfo.uid, "update lib");
10237            }
10238        }
10239
10240        // writer
10241        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10242
10243        synchronized (mPackages) {
10244            // We don't expect installation to fail beyond this point
10245
10246            // Add the new setting to mSettings
10247            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10248            // Add the new setting to mPackages
10249            mPackages.put(pkg.applicationInfo.packageName, pkg);
10250            // Make sure we don't accidentally delete its data.
10251            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10252            while (iter.hasNext()) {
10253                PackageCleanItem item = iter.next();
10254                if (pkgName.equals(item.packageName)) {
10255                    iter.remove();
10256                }
10257            }
10258
10259            // Add the package's KeySets to the global KeySetManagerService
10260            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10261            ksms.addScannedPackageLPw(pkg);
10262
10263            int N = pkg.providers.size();
10264            StringBuilder r = null;
10265            int i;
10266            for (i=0; i<N; i++) {
10267                PackageParser.Provider p = pkg.providers.get(i);
10268                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10269                        p.info.processName);
10270                mProviders.addProvider(p);
10271                p.syncable = p.info.isSyncable;
10272                if (p.info.authority != null) {
10273                    String names[] = p.info.authority.split(";");
10274                    p.info.authority = null;
10275                    for (int j = 0; j < names.length; j++) {
10276                        if (j == 1 && p.syncable) {
10277                            // We only want the first authority for a provider to possibly be
10278                            // syncable, so if we already added this provider using a different
10279                            // authority clear the syncable flag. We copy the provider before
10280                            // changing it because the mProviders object contains a reference
10281                            // to a provider that we don't want to change.
10282                            // Only do this for the second authority since the resulting provider
10283                            // object can be the same for all future authorities for this provider.
10284                            p = new PackageParser.Provider(p);
10285                            p.syncable = false;
10286                        }
10287                        if (!mProvidersByAuthority.containsKey(names[j])) {
10288                            mProvidersByAuthority.put(names[j], p);
10289                            if (p.info.authority == null) {
10290                                p.info.authority = names[j];
10291                            } else {
10292                                p.info.authority = p.info.authority + ";" + names[j];
10293                            }
10294                            if (DEBUG_PACKAGE_SCANNING) {
10295                                if (chatty)
10296                                    Log.d(TAG, "Registered content provider: " + names[j]
10297                                            + ", className = " + p.info.name + ", isSyncable = "
10298                                            + p.info.isSyncable);
10299                            }
10300                        } else {
10301                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10302                            Slog.w(TAG, "Skipping provider name " + names[j] +
10303                                    " (in package " + pkg.applicationInfo.packageName +
10304                                    "): name already used by "
10305                                    + ((other != null && other.getComponentName() != null)
10306                                            ? other.getComponentName().getPackageName() : "?"));
10307                        }
10308                    }
10309                }
10310                if (chatty) {
10311                    if (r == null) {
10312                        r = new StringBuilder(256);
10313                    } else {
10314                        r.append(' ');
10315                    }
10316                    r.append(p.info.name);
10317                }
10318            }
10319            if (r != null) {
10320                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10321            }
10322
10323            N = pkg.services.size();
10324            r = null;
10325            for (i=0; i<N; i++) {
10326                PackageParser.Service s = pkg.services.get(i);
10327                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10328                        s.info.processName);
10329                mServices.addService(s);
10330                if (chatty) {
10331                    if (r == null) {
10332                        r = new StringBuilder(256);
10333                    } else {
10334                        r.append(' ');
10335                    }
10336                    r.append(s.info.name);
10337                }
10338            }
10339            if (r != null) {
10340                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10341            }
10342
10343            N = pkg.receivers.size();
10344            r = null;
10345            for (i=0; i<N; i++) {
10346                PackageParser.Activity a = pkg.receivers.get(i);
10347                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10348                        a.info.processName);
10349                mReceivers.addActivity(a, "receiver");
10350                if (chatty) {
10351                    if (r == null) {
10352                        r = new StringBuilder(256);
10353                    } else {
10354                        r.append(' ');
10355                    }
10356                    r.append(a.info.name);
10357                }
10358            }
10359            if (r != null) {
10360                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10361            }
10362
10363            N = pkg.activities.size();
10364            r = null;
10365            for (i=0; i<N; i++) {
10366                PackageParser.Activity a = pkg.activities.get(i);
10367                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10368                        a.info.processName);
10369                mActivities.addActivity(a, "activity");
10370                if (chatty) {
10371                    if (r == null) {
10372                        r = new StringBuilder(256);
10373                    } else {
10374                        r.append(' ');
10375                    }
10376                    r.append(a.info.name);
10377                }
10378            }
10379            if (r != null) {
10380                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10381            }
10382
10383            N = pkg.permissionGroups.size();
10384            r = null;
10385            for (i=0; i<N; i++) {
10386                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10387                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10388                final String curPackageName = cur == null ? null : cur.info.packageName;
10389                // Dont allow ephemeral apps to define new permission groups.
10390                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10391                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10392                            + pg.info.packageName
10393                            + " ignored: instant apps cannot define new permission groups.");
10394                    continue;
10395                }
10396                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10397                if (cur == null || isPackageUpdate) {
10398                    mPermissionGroups.put(pg.info.name, pg);
10399                    if (chatty) {
10400                        if (r == null) {
10401                            r = new StringBuilder(256);
10402                        } else {
10403                            r.append(' ');
10404                        }
10405                        if (isPackageUpdate) {
10406                            r.append("UPD:");
10407                        }
10408                        r.append(pg.info.name);
10409                    }
10410                } else {
10411                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10412                            + pg.info.packageName + " ignored: original from "
10413                            + cur.info.packageName);
10414                    if (chatty) {
10415                        if (r == null) {
10416                            r = new StringBuilder(256);
10417                        } else {
10418                            r.append(' ');
10419                        }
10420                        r.append("DUP:");
10421                        r.append(pg.info.name);
10422                    }
10423                }
10424            }
10425            if (r != null) {
10426                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10427            }
10428
10429            N = pkg.permissions.size();
10430            r = null;
10431            for (i=0; i<N; i++) {
10432                PackageParser.Permission p = pkg.permissions.get(i);
10433
10434                // Dont allow ephemeral apps to define new permissions.
10435                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10436                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10437                            + p.info.packageName
10438                            + " ignored: instant apps cannot define new permissions.");
10439                    continue;
10440                }
10441
10442                // Assume by default that we did not install this permission into the system.
10443                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10444
10445                // Now that permission groups have a special meaning, we ignore permission
10446                // groups for legacy apps to prevent unexpected behavior. In particular,
10447                // permissions for one app being granted to someone just becase they happen
10448                // to be in a group defined by another app (before this had no implications).
10449                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10450                    p.group = mPermissionGroups.get(p.info.group);
10451                    // Warn for a permission in an unknown group.
10452                    if (p.info.group != null && p.group == null) {
10453                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10454                                + p.info.packageName + " in an unknown group " + p.info.group);
10455                    }
10456                }
10457
10458                ArrayMap<String, BasePermission> permissionMap =
10459                        p.tree ? mSettings.mPermissionTrees
10460                                : mSettings.mPermissions;
10461                BasePermission bp = permissionMap.get(p.info.name);
10462
10463                // Allow system apps to redefine non-system permissions
10464                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10465                    final boolean currentOwnerIsSystem = (bp.perm != null
10466                            && isSystemApp(bp.perm.owner));
10467                    if (isSystemApp(p.owner)) {
10468                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10469                            // It's a built-in permission and no owner, take ownership now
10470                            bp.packageSetting = pkgSetting;
10471                            bp.perm = p;
10472                            bp.uid = pkg.applicationInfo.uid;
10473                            bp.sourcePackage = p.info.packageName;
10474                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10475                        } else if (!currentOwnerIsSystem) {
10476                            String msg = "New decl " + p.owner + " of permission  "
10477                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10478                            reportSettingsProblem(Log.WARN, msg);
10479                            bp = null;
10480                        }
10481                    }
10482                }
10483
10484                if (bp == null) {
10485                    bp = new BasePermission(p.info.name, p.info.packageName,
10486                            BasePermission.TYPE_NORMAL);
10487                    permissionMap.put(p.info.name, bp);
10488                }
10489
10490                if (bp.perm == null) {
10491                    if (bp.sourcePackage == null
10492                            || bp.sourcePackage.equals(p.info.packageName)) {
10493                        BasePermission tree = findPermissionTreeLP(p.info.name);
10494                        if (tree == null
10495                                || tree.sourcePackage.equals(p.info.packageName)) {
10496                            bp.packageSetting = pkgSetting;
10497                            bp.perm = p;
10498                            bp.uid = pkg.applicationInfo.uid;
10499                            bp.sourcePackage = p.info.packageName;
10500                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10501                            if (chatty) {
10502                                if (r == null) {
10503                                    r = new StringBuilder(256);
10504                                } else {
10505                                    r.append(' ');
10506                                }
10507                                r.append(p.info.name);
10508                            }
10509                        } else {
10510                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10511                                    + p.info.packageName + " ignored: base tree "
10512                                    + tree.name + " is from package "
10513                                    + tree.sourcePackage);
10514                        }
10515                    } else {
10516                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10517                                + p.info.packageName + " ignored: original from "
10518                                + bp.sourcePackage);
10519                    }
10520                } else if (chatty) {
10521                    if (r == null) {
10522                        r = new StringBuilder(256);
10523                    } else {
10524                        r.append(' ');
10525                    }
10526                    r.append("DUP:");
10527                    r.append(p.info.name);
10528                }
10529                if (bp.perm == p) {
10530                    bp.protectionLevel = p.info.protectionLevel;
10531                }
10532            }
10533
10534            if (r != null) {
10535                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10536            }
10537
10538            N = pkg.instrumentation.size();
10539            r = null;
10540            for (i=0; i<N; i++) {
10541                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10542                a.info.packageName = pkg.applicationInfo.packageName;
10543                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10544                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10545                a.info.splitNames = pkg.splitNames;
10546                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10547                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10548                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10549                a.info.dataDir = pkg.applicationInfo.dataDir;
10550                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10551                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10552                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10553                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10554                mInstrumentation.put(a.getComponentName(), a);
10555                if (chatty) {
10556                    if (r == null) {
10557                        r = new StringBuilder(256);
10558                    } else {
10559                        r.append(' ');
10560                    }
10561                    r.append(a.info.name);
10562                }
10563            }
10564            if (r != null) {
10565                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10566            }
10567
10568            if (pkg.protectedBroadcasts != null) {
10569                N = pkg.protectedBroadcasts.size();
10570                for (i=0; i<N; i++) {
10571                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10572                }
10573            }
10574        }
10575
10576        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10577    }
10578
10579    /**
10580     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10581     * is derived purely on the basis of the contents of {@code scanFile} and
10582     * {@code cpuAbiOverride}.
10583     *
10584     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10585     */
10586    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10587                                 String cpuAbiOverride, boolean extractLibs,
10588                                 File appLib32InstallDir)
10589            throws PackageManagerException {
10590        // Give ourselves some initial paths; we'll come back for another
10591        // pass once we've determined ABI below.
10592        setNativeLibraryPaths(pkg, appLib32InstallDir);
10593
10594        // We would never need to extract libs for forward-locked and external packages,
10595        // since the container service will do it for us. We shouldn't attempt to
10596        // extract libs from system app when it was not updated.
10597        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10598                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10599            extractLibs = false;
10600        }
10601
10602        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10603        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10604
10605        NativeLibraryHelper.Handle handle = null;
10606        try {
10607            handle = NativeLibraryHelper.Handle.create(pkg);
10608            // TODO(multiArch): This can be null for apps that didn't go through the
10609            // usual installation process. We can calculate it again, like we
10610            // do during install time.
10611            //
10612            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10613            // unnecessary.
10614            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10615
10616            // Null out the abis so that they can be recalculated.
10617            pkg.applicationInfo.primaryCpuAbi = null;
10618            pkg.applicationInfo.secondaryCpuAbi = null;
10619            if (isMultiArch(pkg.applicationInfo)) {
10620                // Warn if we've set an abiOverride for multi-lib packages..
10621                // By definition, we need to copy both 32 and 64 bit libraries for
10622                // such packages.
10623                if (pkg.cpuAbiOverride != null
10624                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10625                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10626                }
10627
10628                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10629                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10630                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10631                    if (extractLibs) {
10632                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10633                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10634                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10635                                useIsaSpecificSubdirs);
10636                    } else {
10637                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10638                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10639                    }
10640                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10641                }
10642
10643                maybeThrowExceptionForMultiArchCopy(
10644                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10645
10646                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10647                    if (extractLibs) {
10648                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10649                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10650                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10651                                useIsaSpecificSubdirs);
10652                    } else {
10653                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10654                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10655                    }
10656                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10657                }
10658
10659                maybeThrowExceptionForMultiArchCopy(
10660                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10661
10662                if (abi64 >= 0) {
10663                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10664                }
10665
10666                if (abi32 >= 0) {
10667                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10668                    if (abi64 >= 0) {
10669                        if (pkg.use32bitAbi) {
10670                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10671                            pkg.applicationInfo.primaryCpuAbi = abi;
10672                        } else {
10673                            pkg.applicationInfo.secondaryCpuAbi = abi;
10674                        }
10675                    } else {
10676                        pkg.applicationInfo.primaryCpuAbi = abi;
10677                    }
10678                }
10679
10680            } else {
10681                String[] abiList = (cpuAbiOverride != null) ?
10682                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10683
10684                // Enable gross and lame hacks for apps that are built with old
10685                // SDK tools. We must scan their APKs for renderscript bitcode and
10686                // not launch them if it's present. Don't bother checking on devices
10687                // that don't have 64 bit support.
10688                boolean needsRenderScriptOverride = false;
10689                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10690                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10691                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10692                    needsRenderScriptOverride = true;
10693                }
10694
10695                final int copyRet;
10696                if (extractLibs) {
10697                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10698                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10699                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10700                } else {
10701                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10702                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10703                }
10704                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10705
10706                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10707                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10708                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10709                }
10710
10711                if (copyRet >= 0) {
10712                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10713                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10714                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10715                } else if (needsRenderScriptOverride) {
10716                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10717                }
10718            }
10719        } catch (IOException ioe) {
10720            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10721        } finally {
10722            IoUtils.closeQuietly(handle);
10723        }
10724
10725        // Now that we've calculated the ABIs and determined if it's an internal app,
10726        // we will go ahead and populate the nativeLibraryPath.
10727        setNativeLibraryPaths(pkg, appLib32InstallDir);
10728    }
10729
10730    /**
10731     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10732     * i.e, so that all packages can be run inside a single process if required.
10733     *
10734     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10735     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10736     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10737     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10738     * updating a package that belongs to a shared user.
10739     *
10740     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10741     * adds unnecessary complexity.
10742     */
10743    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10744            PackageParser.Package scannedPackage) {
10745        String requiredInstructionSet = null;
10746        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10747            requiredInstructionSet = VMRuntime.getInstructionSet(
10748                     scannedPackage.applicationInfo.primaryCpuAbi);
10749        }
10750
10751        PackageSetting requirer = null;
10752        for (PackageSetting ps : packagesForUser) {
10753            // If packagesForUser contains scannedPackage, we skip it. This will happen
10754            // when scannedPackage is an update of an existing package. Without this check,
10755            // we will never be able to change the ABI of any package belonging to a shared
10756            // user, even if it's compatible with other packages.
10757            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10758                if (ps.primaryCpuAbiString == null) {
10759                    continue;
10760                }
10761
10762                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10763                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10764                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10765                    // this but there's not much we can do.
10766                    String errorMessage = "Instruction set mismatch, "
10767                            + ((requirer == null) ? "[caller]" : requirer)
10768                            + " requires " + requiredInstructionSet + " whereas " + ps
10769                            + " requires " + instructionSet;
10770                    Slog.w(TAG, errorMessage);
10771                }
10772
10773                if (requiredInstructionSet == null) {
10774                    requiredInstructionSet = instructionSet;
10775                    requirer = ps;
10776                }
10777            }
10778        }
10779
10780        if (requiredInstructionSet != null) {
10781            String adjustedAbi;
10782            if (requirer != null) {
10783                // requirer != null implies that either scannedPackage was null or that scannedPackage
10784                // did not require an ABI, in which case we have to adjust scannedPackage to match
10785                // the ABI of the set (which is the same as requirer's ABI)
10786                adjustedAbi = requirer.primaryCpuAbiString;
10787                if (scannedPackage != null) {
10788                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10789                }
10790            } else {
10791                // requirer == null implies that we're updating all ABIs in the set to
10792                // match scannedPackage.
10793                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10794            }
10795
10796            for (PackageSetting ps : packagesForUser) {
10797                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10798                    if (ps.primaryCpuAbiString != null) {
10799                        continue;
10800                    }
10801
10802                    ps.primaryCpuAbiString = adjustedAbi;
10803                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10804                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10805                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10806                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10807                                + " (requirer="
10808                                + (requirer != null ? requirer.pkg : "null")
10809                                + ", scannedPackage="
10810                                + (scannedPackage != null ? scannedPackage : "null")
10811                                + ")");
10812                        try {
10813                            mInstaller.rmdex(ps.codePathString,
10814                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10815                        } catch (InstallerException ignored) {
10816                        }
10817                    }
10818                }
10819            }
10820        }
10821    }
10822
10823    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10824        synchronized (mPackages) {
10825            mResolverReplaced = true;
10826            // Set up information for custom user intent resolution activity.
10827            mResolveActivity.applicationInfo = pkg.applicationInfo;
10828            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10829            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10830            mResolveActivity.processName = pkg.applicationInfo.packageName;
10831            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10832            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10833                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10834            mResolveActivity.theme = 0;
10835            mResolveActivity.exported = true;
10836            mResolveActivity.enabled = true;
10837            mResolveInfo.activityInfo = mResolveActivity;
10838            mResolveInfo.priority = 0;
10839            mResolveInfo.preferredOrder = 0;
10840            mResolveInfo.match = 0;
10841            mResolveComponentName = mCustomResolverComponentName;
10842            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10843                    mResolveComponentName);
10844        }
10845    }
10846
10847    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
10848        if (installerActivity == null) {
10849            if (DEBUG_EPHEMERAL) {
10850                Slog.d(TAG, "Clear ephemeral installer activity");
10851            }
10852            mInstantAppInstallerActivity = null;
10853            return;
10854        }
10855
10856        if (DEBUG_EPHEMERAL) {
10857            Slog.d(TAG, "Set ephemeral installer activity: "
10858                    + installerActivity.getComponentName());
10859        }
10860        // Set up information for ephemeral installer activity
10861        mInstantAppInstallerActivity = installerActivity;
10862        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10863                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10864        mInstantAppInstallerActivity.exported = true;
10865        mInstantAppInstallerActivity.enabled = true;
10866        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10867        mInstantAppInstallerInfo.priority = 0;
10868        mInstantAppInstallerInfo.preferredOrder = 1;
10869        mInstantAppInstallerInfo.isDefault = true;
10870        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10871                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10872    }
10873
10874    private static String calculateBundledApkRoot(final String codePathString) {
10875        final File codePath = new File(codePathString);
10876        final File codeRoot;
10877        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10878            codeRoot = Environment.getRootDirectory();
10879        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10880            codeRoot = Environment.getOemDirectory();
10881        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10882            codeRoot = Environment.getVendorDirectory();
10883        } else {
10884            // Unrecognized code path; take its top real segment as the apk root:
10885            // e.g. /something/app/blah.apk => /something
10886            try {
10887                File f = codePath.getCanonicalFile();
10888                File parent = f.getParentFile();    // non-null because codePath is a file
10889                File tmp;
10890                while ((tmp = parent.getParentFile()) != null) {
10891                    f = parent;
10892                    parent = tmp;
10893                }
10894                codeRoot = f;
10895                Slog.w(TAG, "Unrecognized code path "
10896                        + codePath + " - using " + codeRoot);
10897            } catch (IOException e) {
10898                // Can't canonicalize the code path -- shenanigans?
10899                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10900                return Environment.getRootDirectory().getPath();
10901            }
10902        }
10903        return codeRoot.getPath();
10904    }
10905
10906    /**
10907     * Derive and set the location of native libraries for the given package,
10908     * which varies depending on where and how the package was installed.
10909     */
10910    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10911        final ApplicationInfo info = pkg.applicationInfo;
10912        final String codePath = pkg.codePath;
10913        final File codeFile = new File(codePath);
10914        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10915        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10916
10917        info.nativeLibraryRootDir = null;
10918        info.nativeLibraryRootRequiresIsa = false;
10919        info.nativeLibraryDir = null;
10920        info.secondaryNativeLibraryDir = null;
10921
10922        if (isApkFile(codeFile)) {
10923            // Monolithic install
10924            if (bundledApp) {
10925                // If "/system/lib64/apkname" exists, assume that is the per-package
10926                // native library directory to use; otherwise use "/system/lib/apkname".
10927                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10928                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10929                        getPrimaryInstructionSet(info));
10930
10931                // This is a bundled system app so choose the path based on the ABI.
10932                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10933                // is just the default path.
10934                final String apkName = deriveCodePathName(codePath);
10935                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10936                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10937                        apkName).getAbsolutePath();
10938
10939                if (info.secondaryCpuAbi != null) {
10940                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10941                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10942                            secondaryLibDir, apkName).getAbsolutePath();
10943                }
10944            } else if (asecApp) {
10945                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10946                        .getAbsolutePath();
10947            } else {
10948                final String apkName = deriveCodePathName(codePath);
10949                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10950                        .getAbsolutePath();
10951            }
10952
10953            info.nativeLibraryRootRequiresIsa = false;
10954            info.nativeLibraryDir = info.nativeLibraryRootDir;
10955        } else {
10956            // Cluster install
10957            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10958            info.nativeLibraryRootRequiresIsa = true;
10959
10960            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10961                    getPrimaryInstructionSet(info)).getAbsolutePath();
10962
10963            if (info.secondaryCpuAbi != null) {
10964                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10965                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10966            }
10967        }
10968    }
10969
10970    /**
10971     * Calculate the abis and roots for a bundled app. These can uniquely
10972     * be determined from the contents of the system partition, i.e whether
10973     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10974     * of this information, and instead assume that the system was built
10975     * sensibly.
10976     */
10977    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10978                                           PackageSetting pkgSetting) {
10979        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10980
10981        // If "/system/lib64/apkname" exists, assume that is the per-package
10982        // native library directory to use; otherwise use "/system/lib/apkname".
10983        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10984        setBundledAppAbi(pkg, apkRoot, apkName);
10985        // pkgSetting might be null during rescan following uninstall of updates
10986        // to a bundled app, so accommodate that possibility.  The settings in
10987        // that case will be established later from the parsed package.
10988        //
10989        // If the settings aren't null, sync them up with what we've just derived.
10990        // note that apkRoot isn't stored in the package settings.
10991        if (pkgSetting != null) {
10992            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10993            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10994        }
10995    }
10996
10997    /**
10998     * Deduces the ABI of a bundled app and sets the relevant fields on the
10999     * parsed pkg object.
11000     *
11001     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11002     *        under which system libraries are installed.
11003     * @param apkName the name of the installed package.
11004     */
11005    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11006        final File codeFile = new File(pkg.codePath);
11007
11008        final boolean has64BitLibs;
11009        final boolean has32BitLibs;
11010        if (isApkFile(codeFile)) {
11011            // Monolithic install
11012            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11013            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11014        } else {
11015            // Cluster install
11016            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11017            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11018                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11019                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11020                has64BitLibs = (new File(rootDir, isa)).exists();
11021            } else {
11022                has64BitLibs = false;
11023            }
11024            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11025                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11026                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11027                has32BitLibs = (new File(rootDir, isa)).exists();
11028            } else {
11029                has32BitLibs = false;
11030            }
11031        }
11032
11033        if (has64BitLibs && !has32BitLibs) {
11034            // The package has 64 bit libs, but not 32 bit libs. Its primary
11035            // ABI should be 64 bit. We can safely assume here that the bundled
11036            // native libraries correspond to the most preferred ABI in the list.
11037
11038            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11039            pkg.applicationInfo.secondaryCpuAbi = null;
11040        } else if (has32BitLibs && !has64BitLibs) {
11041            // The package has 32 bit libs but not 64 bit libs. Its primary
11042            // ABI should be 32 bit.
11043
11044            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11045            pkg.applicationInfo.secondaryCpuAbi = null;
11046        } else if (has32BitLibs && has64BitLibs) {
11047            // The application has both 64 and 32 bit bundled libraries. We check
11048            // here that the app declares multiArch support, and warn if it doesn't.
11049            //
11050            // We will be lenient here and record both ABIs. The primary will be the
11051            // ABI that's higher on the list, i.e, a device that's configured to prefer
11052            // 64 bit apps will see a 64 bit primary ABI,
11053
11054            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11055                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11056            }
11057
11058            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11059                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11060                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11061            } else {
11062                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11063                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11064            }
11065        } else {
11066            pkg.applicationInfo.primaryCpuAbi = null;
11067            pkg.applicationInfo.secondaryCpuAbi = null;
11068        }
11069    }
11070
11071    private void killApplication(String pkgName, int appId, String reason) {
11072        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11073    }
11074
11075    private void killApplication(String pkgName, int appId, int userId, String reason) {
11076        // Request the ActivityManager to kill the process(only for existing packages)
11077        // so that we do not end up in a confused state while the user is still using the older
11078        // version of the application while the new one gets installed.
11079        final long token = Binder.clearCallingIdentity();
11080        try {
11081            IActivityManager am = ActivityManager.getService();
11082            if (am != null) {
11083                try {
11084                    am.killApplication(pkgName, appId, userId, reason);
11085                } catch (RemoteException e) {
11086                }
11087            }
11088        } finally {
11089            Binder.restoreCallingIdentity(token);
11090        }
11091    }
11092
11093    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11094        // Remove the parent package setting
11095        PackageSetting ps = (PackageSetting) pkg.mExtras;
11096        if (ps != null) {
11097            removePackageLI(ps, chatty);
11098        }
11099        // Remove the child package setting
11100        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11101        for (int i = 0; i < childCount; i++) {
11102            PackageParser.Package childPkg = pkg.childPackages.get(i);
11103            ps = (PackageSetting) childPkg.mExtras;
11104            if (ps != null) {
11105                removePackageLI(ps, chatty);
11106            }
11107        }
11108    }
11109
11110    void removePackageLI(PackageSetting ps, boolean chatty) {
11111        if (DEBUG_INSTALL) {
11112            if (chatty)
11113                Log.d(TAG, "Removing package " + ps.name);
11114        }
11115
11116        // writer
11117        synchronized (mPackages) {
11118            mPackages.remove(ps.name);
11119            final PackageParser.Package pkg = ps.pkg;
11120            if (pkg != null) {
11121                cleanPackageDataStructuresLILPw(pkg, chatty);
11122            }
11123        }
11124    }
11125
11126    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11127        if (DEBUG_INSTALL) {
11128            if (chatty)
11129                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11130        }
11131
11132        // writer
11133        synchronized (mPackages) {
11134            // Remove the parent package
11135            mPackages.remove(pkg.applicationInfo.packageName);
11136            cleanPackageDataStructuresLILPw(pkg, chatty);
11137
11138            // Remove the child packages
11139            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11140            for (int i = 0; i < childCount; i++) {
11141                PackageParser.Package childPkg = pkg.childPackages.get(i);
11142                mPackages.remove(childPkg.applicationInfo.packageName);
11143                cleanPackageDataStructuresLILPw(childPkg, chatty);
11144            }
11145        }
11146    }
11147
11148    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11149        int N = pkg.providers.size();
11150        StringBuilder r = null;
11151        int i;
11152        for (i=0; i<N; i++) {
11153            PackageParser.Provider p = pkg.providers.get(i);
11154            mProviders.removeProvider(p);
11155            if (p.info.authority == null) {
11156
11157                /* There was another ContentProvider with this authority when
11158                 * this app was installed so this authority is null,
11159                 * Ignore it as we don't have to unregister the provider.
11160                 */
11161                continue;
11162            }
11163            String names[] = p.info.authority.split(";");
11164            for (int j = 0; j < names.length; j++) {
11165                if (mProvidersByAuthority.get(names[j]) == p) {
11166                    mProvidersByAuthority.remove(names[j]);
11167                    if (DEBUG_REMOVE) {
11168                        if (chatty)
11169                            Log.d(TAG, "Unregistered content provider: " + names[j]
11170                                    + ", className = " + p.info.name + ", isSyncable = "
11171                                    + p.info.isSyncable);
11172                    }
11173                }
11174            }
11175            if (DEBUG_REMOVE && chatty) {
11176                if (r == null) {
11177                    r = new StringBuilder(256);
11178                } else {
11179                    r.append(' ');
11180                }
11181                r.append(p.info.name);
11182            }
11183        }
11184        if (r != null) {
11185            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11186        }
11187
11188        N = pkg.services.size();
11189        r = null;
11190        for (i=0; i<N; i++) {
11191            PackageParser.Service s = pkg.services.get(i);
11192            mServices.removeService(s);
11193            if (chatty) {
11194                if (r == null) {
11195                    r = new StringBuilder(256);
11196                } else {
11197                    r.append(' ');
11198                }
11199                r.append(s.info.name);
11200            }
11201        }
11202        if (r != null) {
11203            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11204        }
11205
11206        N = pkg.receivers.size();
11207        r = null;
11208        for (i=0; i<N; i++) {
11209            PackageParser.Activity a = pkg.receivers.get(i);
11210            mReceivers.removeActivity(a, "receiver");
11211            if (DEBUG_REMOVE && chatty) {
11212                if (r == null) {
11213                    r = new StringBuilder(256);
11214                } else {
11215                    r.append(' ');
11216                }
11217                r.append(a.info.name);
11218            }
11219        }
11220        if (r != null) {
11221            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11222        }
11223
11224        N = pkg.activities.size();
11225        r = null;
11226        for (i=0; i<N; i++) {
11227            PackageParser.Activity a = pkg.activities.get(i);
11228            mActivities.removeActivity(a, "activity");
11229            if (DEBUG_REMOVE && chatty) {
11230                if (r == null) {
11231                    r = new StringBuilder(256);
11232                } else {
11233                    r.append(' ');
11234                }
11235                r.append(a.info.name);
11236            }
11237        }
11238        if (r != null) {
11239            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11240        }
11241
11242        N = pkg.permissions.size();
11243        r = null;
11244        for (i=0; i<N; i++) {
11245            PackageParser.Permission p = pkg.permissions.get(i);
11246            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11247            if (bp == null) {
11248                bp = mSettings.mPermissionTrees.get(p.info.name);
11249            }
11250            if (bp != null && bp.perm == p) {
11251                bp.perm = null;
11252                if (DEBUG_REMOVE && chatty) {
11253                    if (r == null) {
11254                        r = new StringBuilder(256);
11255                    } else {
11256                        r.append(' ');
11257                    }
11258                    r.append(p.info.name);
11259                }
11260            }
11261            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11262                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11263                if (appOpPkgs != null) {
11264                    appOpPkgs.remove(pkg.packageName);
11265                }
11266            }
11267        }
11268        if (r != null) {
11269            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11270        }
11271
11272        N = pkg.requestedPermissions.size();
11273        r = null;
11274        for (i=0; i<N; i++) {
11275            String perm = pkg.requestedPermissions.get(i);
11276            BasePermission bp = mSettings.mPermissions.get(perm);
11277            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11278                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11279                if (appOpPkgs != null) {
11280                    appOpPkgs.remove(pkg.packageName);
11281                    if (appOpPkgs.isEmpty()) {
11282                        mAppOpPermissionPackages.remove(perm);
11283                    }
11284                }
11285            }
11286        }
11287        if (r != null) {
11288            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11289        }
11290
11291        N = pkg.instrumentation.size();
11292        r = null;
11293        for (i=0; i<N; i++) {
11294            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11295            mInstrumentation.remove(a.getComponentName());
11296            if (DEBUG_REMOVE && chatty) {
11297                if (r == null) {
11298                    r = new StringBuilder(256);
11299                } else {
11300                    r.append(' ');
11301                }
11302                r.append(a.info.name);
11303            }
11304        }
11305        if (r != null) {
11306            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11307        }
11308
11309        r = null;
11310        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11311            // Only system apps can hold shared libraries.
11312            if (pkg.libraryNames != null) {
11313                for (i = 0; i < pkg.libraryNames.size(); i++) {
11314                    String name = pkg.libraryNames.get(i);
11315                    if (removeSharedLibraryLPw(name, 0)) {
11316                        if (DEBUG_REMOVE && chatty) {
11317                            if (r == null) {
11318                                r = new StringBuilder(256);
11319                            } else {
11320                                r.append(' ');
11321                            }
11322                            r.append(name);
11323                        }
11324                    }
11325                }
11326            }
11327        }
11328
11329        r = null;
11330
11331        // Any package can hold static shared libraries.
11332        if (pkg.staticSharedLibName != null) {
11333            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11334                if (DEBUG_REMOVE && chatty) {
11335                    if (r == null) {
11336                        r = new StringBuilder(256);
11337                    } else {
11338                        r.append(' ');
11339                    }
11340                    r.append(pkg.staticSharedLibName);
11341                }
11342            }
11343        }
11344
11345        if (r != null) {
11346            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11347        }
11348    }
11349
11350    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11351        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11352            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11353                return true;
11354            }
11355        }
11356        return false;
11357    }
11358
11359    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11360    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11361    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11362
11363    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11364        // Update the parent permissions
11365        updatePermissionsLPw(pkg.packageName, pkg, flags);
11366        // Update the child permissions
11367        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11368        for (int i = 0; i < childCount; i++) {
11369            PackageParser.Package childPkg = pkg.childPackages.get(i);
11370            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11371        }
11372    }
11373
11374    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11375            int flags) {
11376        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11377        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11378    }
11379
11380    private void updatePermissionsLPw(String changingPkg,
11381            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11382        // Make sure there are no dangling permission trees.
11383        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11384        while (it.hasNext()) {
11385            final BasePermission bp = it.next();
11386            if (bp.packageSetting == null) {
11387                // We may not yet have parsed the package, so just see if
11388                // we still know about its settings.
11389                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11390            }
11391            if (bp.packageSetting == null) {
11392                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11393                        + " from package " + bp.sourcePackage);
11394                it.remove();
11395            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11396                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11397                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11398                            + " from package " + bp.sourcePackage);
11399                    flags |= UPDATE_PERMISSIONS_ALL;
11400                    it.remove();
11401                }
11402            }
11403        }
11404
11405        // Make sure all dynamic permissions have been assigned to a package,
11406        // and make sure there are no dangling permissions.
11407        it = mSettings.mPermissions.values().iterator();
11408        while (it.hasNext()) {
11409            final BasePermission bp = it.next();
11410            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11411                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11412                        + bp.name + " pkg=" + bp.sourcePackage
11413                        + " info=" + bp.pendingInfo);
11414                if (bp.packageSetting == null && bp.pendingInfo != null) {
11415                    final BasePermission tree = findPermissionTreeLP(bp.name);
11416                    if (tree != null && tree.perm != null) {
11417                        bp.packageSetting = tree.packageSetting;
11418                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11419                                new PermissionInfo(bp.pendingInfo));
11420                        bp.perm.info.packageName = tree.perm.info.packageName;
11421                        bp.perm.info.name = bp.name;
11422                        bp.uid = tree.uid;
11423                    }
11424                }
11425            }
11426            if (bp.packageSetting == null) {
11427                // We may not yet have parsed the package, so just see if
11428                // we still know about its settings.
11429                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11430            }
11431            if (bp.packageSetting == null) {
11432                Slog.w(TAG, "Removing dangling permission: " + bp.name
11433                        + " from package " + bp.sourcePackage);
11434                it.remove();
11435            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11436                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11437                    Slog.i(TAG, "Removing old permission: " + bp.name
11438                            + " from package " + bp.sourcePackage);
11439                    flags |= UPDATE_PERMISSIONS_ALL;
11440                    it.remove();
11441                }
11442            }
11443        }
11444
11445        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11446        // Now update the permissions for all packages, in particular
11447        // replace the granted permissions of the system packages.
11448        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11449            for (PackageParser.Package pkg : mPackages.values()) {
11450                if (pkg != pkgInfo) {
11451                    // Only replace for packages on requested volume
11452                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11453                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11454                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11455                    grantPermissionsLPw(pkg, replace, changingPkg);
11456                }
11457            }
11458        }
11459
11460        if (pkgInfo != null) {
11461            // Only replace for packages on requested volume
11462            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11463            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11464                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11465            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11466        }
11467        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11468    }
11469
11470    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11471            String packageOfInterest) {
11472        // IMPORTANT: There are two types of permissions: install and runtime.
11473        // Install time permissions are granted when the app is installed to
11474        // all device users and users added in the future. Runtime permissions
11475        // are granted at runtime explicitly to specific users. Normal and signature
11476        // protected permissions are install time permissions. Dangerous permissions
11477        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11478        // otherwise they are runtime permissions. This function does not manage
11479        // runtime permissions except for the case an app targeting Lollipop MR1
11480        // being upgraded to target a newer SDK, in which case dangerous permissions
11481        // are transformed from install time to runtime ones.
11482
11483        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11484        if (ps == null) {
11485            return;
11486        }
11487
11488        PermissionsState permissionsState = ps.getPermissionsState();
11489        PermissionsState origPermissions = permissionsState;
11490
11491        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11492
11493        boolean runtimePermissionsRevoked = false;
11494        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11495
11496        boolean changedInstallPermission = false;
11497
11498        if (replace) {
11499            ps.installPermissionsFixed = false;
11500            if (!ps.isSharedUser()) {
11501                origPermissions = new PermissionsState(permissionsState);
11502                permissionsState.reset();
11503            } else {
11504                // We need to know only about runtime permission changes since the
11505                // calling code always writes the install permissions state but
11506                // the runtime ones are written only if changed. The only cases of
11507                // changed runtime permissions here are promotion of an install to
11508                // runtime and revocation of a runtime from a shared user.
11509                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11510                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11511                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11512                    runtimePermissionsRevoked = true;
11513                }
11514            }
11515        }
11516
11517        permissionsState.setGlobalGids(mGlobalGids);
11518
11519        final int N = pkg.requestedPermissions.size();
11520        for (int i=0; i<N; i++) {
11521            final String name = pkg.requestedPermissions.get(i);
11522            final BasePermission bp = mSettings.mPermissions.get(name);
11523            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11524                    >= Build.VERSION_CODES.M;
11525
11526            if (DEBUG_INSTALL) {
11527                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11528            }
11529
11530            if (bp == null || bp.packageSetting == null) {
11531                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11532                    Slog.w(TAG, "Unknown permission " + name
11533                            + " in package " + pkg.packageName);
11534                }
11535                continue;
11536            }
11537
11538
11539            // Limit ephemeral apps to ephemeral allowed permissions.
11540            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11541                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11542                        + pkg.packageName);
11543                continue;
11544            }
11545
11546            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
11547                Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
11548                        + pkg.packageName);
11549                continue;
11550            }
11551
11552            final String perm = bp.name;
11553            boolean allowedSig = false;
11554            int grant = GRANT_DENIED;
11555
11556            // Keep track of app op permissions.
11557            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11558                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11559                if (pkgs == null) {
11560                    pkgs = new ArraySet<>();
11561                    mAppOpPermissionPackages.put(bp.name, pkgs);
11562                }
11563                pkgs.add(pkg.packageName);
11564            }
11565
11566            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11567            switch (level) {
11568                case PermissionInfo.PROTECTION_NORMAL: {
11569                    // For all apps normal permissions are install time ones.
11570                    grant = GRANT_INSTALL;
11571                } break;
11572
11573                case PermissionInfo.PROTECTION_DANGEROUS: {
11574                    // If a permission review is required for legacy apps we represent
11575                    // their permissions as always granted runtime ones since we need
11576                    // to keep the review required permission flag per user while an
11577                    // install permission's state is shared across all users.
11578                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11579                        // For legacy apps dangerous permissions are install time ones.
11580                        grant = GRANT_INSTALL;
11581                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11582                        // For legacy apps that became modern, install becomes runtime.
11583                        grant = GRANT_UPGRADE;
11584                    } else if (mPromoteSystemApps
11585                            && isSystemApp(ps)
11586                            && mExistingSystemPackages.contains(ps.name)) {
11587                        // For legacy system apps, install becomes runtime.
11588                        // We cannot check hasInstallPermission() for system apps since those
11589                        // permissions were granted implicitly and not persisted pre-M.
11590                        grant = GRANT_UPGRADE;
11591                    } else {
11592                        // For modern apps keep runtime permissions unchanged.
11593                        grant = GRANT_RUNTIME;
11594                    }
11595                } break;
11596
11597                case PermissionInfo.PROTECTION_SIGNATURE: {
11598                    // For all apps signature permissions are install time ones.
11599                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11600                    if (allowedSig) {
11601                        grant = GRANT_INSTALL;
11602                    }
11603                } break;
11604            }
11605
11606            if (DEBUG_INSTALL) {
11607                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11608            }
11609
11610            if (grant != GRANT_DENIED) {
11611                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11612                    // If this is an existing, non-system package, then
11613                    // we can't add any new permissions to it.
11614                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11615                        // Except...  if this is a permission that was added
11616                        // to the platform (note: need to only do this when
11617                        // updating the platform).
11618                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11619                            grant = GRANT_DENIED;
11620                        }
11621                    }
11622                }
11623
11624                switch (grant) {
11625                    case GRANT_INSTALL: {
11626                        // Revoke this as runtime permission to handle the case of
11627                        // a runtime permission being downgraded to an install one.
11628                        // Also in permission review mode we keep dangerous permissions
11629                        // for legacy apps
11630                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11631                            if (origPermissions.getRuntimePermissionState(
11632                                    bp.name, userId) != null) {
11633                                // Revoke the runtime permission and clear the flags.
11634                                origPermissions.revokeRuntimePermission(bp, userId);
11635                                origPermissions.updatePermissionFlags(bp, userId,
11636                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11637                                // If we revoked a permission permission, we have to write.
11638                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11639                                        changedRuntimePermissionUserIds, userId);
11640                            }
11641                        }
11642                        // Grant an install permission.
11643                        if (permissionsState.grantInstallPermission(bp) !=
11644                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11645                            changedInstallPermission = true;
11646                        }
11647                    } break;
11648
11649                    case GRANT_RUNTIME: {
11650                        // Grant previously granted runtime permissions.
11651                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11652                            PermissionState permissionState = origPermissions
11653                                    .getRuntimePermissionState(bp.name, userId);
11654                            int flags = permissionState != null
11655                                    ? permissionState.getFlags() : 0;
11656                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11657                                // Don't propagate the permission in a permission review mode if
11658                                // the former was revoked, i.e. marked to not propagate on upgrade.
11659                                // Note that in a permission review mode install permissions are
11660                                // represented as constantly granted runtime ones since we need to
11661                                // keep a per user state associated with the permission. Also the
11662                                // revoke on upgrade flag is no longer applicable and is reset.
11663                                final boolean revokeOnUpgrade = (flags & PackageManager
11664                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11665                                if (revokeOnUpgrade) {
11666                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11667                                    // Since we changed the flags, we have to write.
11668                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11669                                            changedRuntimePermissionUserIds, userId);
11670                                }
11671                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11672                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11673                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11674                                        // If we cannot put the permission as it was,
11675                                        // we have to write.
11676                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11677                                                changedRuntimePermissionUserIds, userId);
11678                                    }
11679                                }
11680
11681                                // If the app supports runtime permissions no need for a review.
11682                                if (mPermissionReviewRequired
11683                                        && appSupportsRuntimePermissions
11684                                        && (flags & PackageManager
11685                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11686                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11687                                    // Since we changed the flags, we have to write.
11688                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11689                                            changedRuntimePermissionUserIds, userId);
11690                                }
11691                            } else if (mPermissionReviewRequired
11692                                    && !appSupportsRuntimePermissions) {
11693                                // For legacy apps that need a permission review, every new
11694                                // runtime permission is granted but it is pending a review.
11695                                // We also need to review only platform defined runtime
11696                                // permissions as these are the only ones the platform knows
11697                                // how to disable the API to simulate revocation as legacy
11698                                // apps don't expect to run with revoked permissions.
11699                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11700                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11701                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11702                                        // We changed the flags, hence have to write.
11703                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11704                                                changedRuntimePermissionUserIds, userId);
11705                                    }
11706                                }
11707                                if (permissionsState.grantRuntimePermission(bp, userId)
11708                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11709                                    // We changed the permission, hence have to write.
11710                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11711                                            changedRuntimePermissionUserIds, userId);
11712                                }
11713                            }
11714                            // Propagate the permission flags.
11715                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11716                        }
11717                    } break;
11718
11719                    case GRANT_UPGRADE: {
11720                        // Grant runtime permissions for a previously held install permission.
11721                        PermissionState permissionState = origPermissions
11722                                .getInstallPermissionState(bp.name);
11723                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11724
11725                        if (origPermissions.revokeInstallPermission(bp)
11726                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11727                            // We will be transferring the permission flags, so clear them.
11728                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11729                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11730                            changedInstallPermission = true;
11731                        }
11732
11733                        // If the permission is not to be promoted to runtime we ignore it and
11734                        // also its other flags as they are not applicable to install permissions.
11735                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11736                            for (int userId : currentUserIds) {
11737                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11738                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11739                                    // Transfer the permission flags.
11740                                    permissionsState.updatePermissionFlags(bp, userId,
11741                                            flags, flags);
11742                                    // If we granted the permission, we have to write.
11743                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11744                                            changedRuntimePermissionUserIds, userId);
11745                                }
11746                            }
11747                        }
11748                    } break;
11749
11750                    default: {
11751                        if (packageOfInterest == null
11752                                || packageOfInterest.equals(pkg.packageName)) {
11753                            Slog.w(TAG, "Not granting permission " + perm
11754                                    + " to package " + pkg.packageName
11755                                    + " because it was previously installed without");
11756                        }
11757                    } break;
11758                }
11759            } else {
11760                if (permissionsState.revokeInstallPermission(bp) !=
11761                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11762                    // Also drop the permission flags.
11763                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11764                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11765                    changedInstallPermission = true;
11766                    Slog.i(TAG, "Un-granting permission " + perm
11767                            + " from package " + pkg.packageName
11768                            + " (protectionLevel=" + bp.protectionLevel
11769                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11770                            + ")");
11771                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11772                    // Don't print warning for app op permissions, since it is fine for them
11773                    // not to be granted, there is a UI for the user to decide.
11774                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11775                        Slog.w(TAG, "Not granting permission " + perm
11776                                + " to package " + pkg.packageName
11777                                + " (protectionLevel=" + bp.protectionLevel
11778                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11779                                + ")");
11780                    }
11781                }
11782            }
11783        }
11784
11785        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11786                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11787            // This is the first that we have heard about this package, so the
11788            // permissions we have now selected are fixed until explicitly
11789            // changed.
11790            ps.installPermissionsFixed = true;
11791        }
11792
11793        // Persist the runtime permissions state for users with changes. If permissions
11794        // were revoked because no app in the shared user declares them we have to
11795        // write synchronously to avoid losing runtime permissions state.
11796        for (int userId : changedRuntimePermissionUserIds) {
11797            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11798        }
11799    }
11800
11801    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11802        boolean allowed = false;
11803        final int NP = PackageParser.NEW_PERMISSIONS.length;
11804        for (int ip=0; ip<NP; ip++) {
11805            final PackageParser.NewPermissionInfo npi
11806                    = PackageParser.NEW_PERMISSIONS[ip];
11807            if (npi.name.equals(perm)
11808                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11809                allowed = true;
11810                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11811                        + pkg.packageName);
11812                break;
11813            }
11814        }
11815        return allowed;
11816    }
11817
11818    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11819            BasePermission bp, PermissionsState origPermissions) {
11820        boolean privilegedPermission = (bp.protectionLevel
11821                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11822        boolean privappPermissionsDisable =
11823                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11824        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11825        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11826        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11827                && !platformPackage && platformPermission) {
11828            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11829                    .getPrivAppPermissions(pkg.packageName);
11830            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11831            if (!whitelisted) {
11832                Slog.w(TAG, "Privileged permission " + perm + " for package "
11833                        + pkg.packageName + " - not in privapp-permissions whitelist");
11834                // Only report violations for apps on system image
11835                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11836                    if (mPrivappPermissionsViolations == null) {
11837                        mPrivappPermissionsViolations = new ArraySet<>();
11838                    }
11839                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11840                }
11841                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11842                    return false;
11843                }
11844            }
11845        }
11846        boolean allowed = (compareSignatures(
11847                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11848                        == PackageManager.SIGNATURE_MATCH)
11849                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11850                        == PackageManager.SIGNATURE_MATCH);
11851        if (!allowed && privilegedPermission) {
11852            if (isSystemApp(pkg)) {
11853                // For updated system applications, a system permission
11854                // is granted only if it had been defined by the original application.
11855                if (pkg.isUpdatedSystemApp()) {
11856                    final PackageSetting sysPs = mSettings
11857                            .getDisabledSystemPkgLPr(pkg.packageName);
11858                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11859                        // If the original was granted this permission, we take
11860                        // that grant decision as read and propagate it to the
11861                        // update.
11862                        if (sysPs.isPrivileged()) {
11863                            allowed = true;
11864                        }
11865                    } else {
11866                        // The system apk may have been updated with an older
11867                        // version of the one on the data partition, but which
11868                        // granted a new system permission that it didn't have
11869                        // before.  In this case we do want to allow the app to
11870                        // now get the new permission if the ancestral apk is
11871                        // privileged to get it.
11872                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11873                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11874                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11875                                    allowed = true;
11876                                    break;
11877                                }
11878                            }
11879                        }
11880                        // Also if a privileged parent package on the system image or any of
11881                        // its children requested a privileged permission, the updated child
11882                        // packages can also get the permission.
11883                        if (pkg.parentPackage != null) {
11884                            final PackageSetting disabledSysParentPs = mSettings
11885                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11886                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11887                                    && disabledSysParentPs.isPrivileged()) {
11888                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11889                                    allowed = true;
11890                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11891                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11892                                    for (int i = 0; i < count; i++) {
11893                                        PackageParser.Package disabledSysChildPkg =
11894                                                disabledSysParentPs.pkg.childPackages.get(i);
11895                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11896                                                perm)) {
11897                                            allowed = true;
11898                                            break;
11899                                        }
11900                                    }
11901                                }
11902                            }
11903                        }
11904                    }
11905                } else {
11906                    allowed = isPrivilegedApp(pkg);
11907                }
11908            }
11909        }
11910        if (!allowed) {
11911            if (!allowed && (bp.protectionLevel
11912                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11913                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11914                // If this was a previously normal/dangerous permission that got moved
11915                // to a system permission as part of the runtime permission redesign, then
11916                // we still want to blindly grant it to old apps.
11917                allowed = true;
11918            }
11919            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11920                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11921                // If this permission is to be granted to the system installer and
11922                // this app is an installer, then it gets the permission.
11923                allowed = true;
11924            }
11925            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11926                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11927                // If this permission is to be granted to the system verifier and
11928                // this app is a verifier, then it gets the permission.
11929                allowed = true;
11930            }
11931            if (!allowed && (bp.protectionLevel
11932                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11933                    && isSystemApp(pkg)) {
11934                // Any pre-installed system app is allowed to get this permission.
11935                allowed = true;
11936            }
11937            if (!allowed && (bp.protectionLevel
11938                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11939                // For development permissions, a development permission
11940                // is granted only if it was already granted.
11941                allowed = origPermissions.hasInstallPermission(perm);
11942            }
11943            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11944                    && pkg.packageName.equals(mSetupWizardPackage)) {
11945                // If this permission is to be granted to the system setup wizard and
11946                // this app is a setup wizard, then it gets the permission.
11947                allowed = true;
11948            }
11949        }
11950        return allowed;
11951    }
11952
11953    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11954        final int permCount = pkg.requestedPermissions.size();
11955        for (int j = 0; j < permCount; j++) {
11956            String requestedPermission = pkg.requestedPermissions.get(j);
11957            if (permission.equals(requestedPermission)) {
11958                return true;
11959            }
11960        }
11961        return false;
11962    }
11963
11964    final class ActivityIntentResolver
11965            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11966        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11967                boolean defaultOnly, int userId) {
11968            if (!sUserManager.exists(userId)) return null;
11969            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11970            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11971        }
11972
11973        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11974                int userId) {
11975            if (!sUserManager.exists(userId)) return null;
11976            mFlags = flags;
11977            return super.queryIntent(intent, resolvedType,
11978                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11979                    userId);
11980        }
11981
11982        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11983                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11984            if (!sUserManager.exists(userId)) return null;
11985            if (packageActivities == null) {
11986                return null;
11987            }
11988            mFlags = flags;
11989            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11990            final int N = packageActivities.size();
11991            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11992                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11993
11994            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11995            for (int i = 0; i < N; ++i) {
11996                intentFilters = packageActivities.get(i).intents;
11997                if (intentFilters != null && intentFilters.size() > 0) {
11998                    PackageParser.ActivityIntentInfo[] array =
11999                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12000                    intentFilters.toArray(array);
12001                    listCut.add(array);
12002                }
12003            }
12004            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12005        }
12006
12007        /**
12008         * Finds a privileged activity that matches the specified activity names.
12009         */
12010        private PackageParser.Activity findMatchingActivity(
12011                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12012            for (PackageParser.Activity sysActivity : activityList) {
12013                if (sysActivity.info.name.equals(activityInfo.name)) {
12014                    return sysActivity;
12015                }
12016                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12017                    return sysActivity;
12018                }
12019                if (sysActivity.info.targetActivity != null) {
12020                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12021                        return sysActivity;
12022                    }
12023                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12024                        return sysActivity;
12025                    }
12026                }
12027            }
12028            return null;
12029        }
12030
12031        public class IterGenerator<E> {
12032            public Iterator<E> generate(ActivityIntentInfo info) {
12033                return null;
12034            }
12035        }
12036
12037        public class ActionIterGenerator extends IterGenerator<String> {
12038            @Override
12039            public Iterator<String> generate(ActivityIntentInfo info) {
12040                return info.actionsIterator();
12041            }
12042        }
12043
12044        public class CategoriesIterGenerator extends IterGenerator<String> {
12045            @Override
12046            public Iterator<String> generate(ActivityIntentInfo info) {
12047                return info.categoriesIterator();
12048            }
12049        }
12050
12051        public class SchemesIterGenerator extends IterGenerator<String> {
12052            @Override
12053            public Iterator<String> generate(ActivityIntentInfo info) {
12054                return info.schemesIterator();
12055            }
12056        }
12057
12058        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12059            @Override
12060            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12061                return info.authoritiesIterator();
12062            }
12063        }
12064
12065        /**
12066         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12067         * MODIFIED. Do not pass in a list that should not be changed.
12068         */
12069        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12070                IterGenerator<T> generator, Iterator<T> searchIterator) {
12071            // loop through the set of actions; every one must be found in the intent filter
12072            while (searchIterator.hasNext()) {
12073                // we must have at least one filter in the list to consider a match
12074                if (intentList.size() == 0) {
12075                    break;
12076                }
12077
12078                final T searchAction = searchIterator.next();
12079
12080                // loop through the set of intent filters
12081                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12082                while (intentIter.hasNext()) {
12083                    final ActivityIntentInfo intentInfo = intentIter.next();
12084                    boolean selectionFound = false;
12085
12086                    // loop through the intent filter's selection criteria; at least one
12087                    // of them must match the searched criteria
12088                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12089                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12090                        final T intentSelection = intentSelectionIter.next();
12091                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12092                            selectionFound = true;
12093                            break;
12094                        }
12095                    }
12096
12097                    // the selection criteria wasn't found in this filter's set; this filter
12098                    // is not a potential match
12099                    if (!selectionFound) {
12100                        intentIter.remove();
12101                    }
12102                }
12103            }
12104        }
12105
12106        private boolean isProtectedAction(ActivityIntentInfo filter) {
12107            final Iterator<String> actionsIter = filter.actionsIterator();
12108            while (actionsIter != null && actionsIter.hasNext()) {
12109                final String filterAction = actionsIter.next();
12110                if (PROTECTED_ACTIONS.contains(filterAction)) {
12111                    return true;
12112                }
12113            }
12114            return false;
12115        }
12116
12117        /**
12118         * Adjusts the priority of the given intent filter according to policy.
12119         * <p>
12120         * <ul>
12121         * <li>The priority for non privileged applications is capped to '0'</li>
12122         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12123         * <li>The priority for unbundled updates to privileged applications is capped to the
12124         *      priority defined on the system partition</li>
12125         * </ul>
12126         * <p>
12127         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12128         * allowed to obtain any priority on any action.
12129         */
12130        private void adjustPriority(
12131                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12132            // nothing to do; priority is fine as-is
12133            if (intent.getPriority() <= 0) {
12134                return;
12135            }
12136
12137            final ActivityInfo activityInfo = intent.activity.info;
12138            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12139
12140            final boolean privilegedApp =
12141                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12142            if (!privilegedApp) {
12143                // non-privileged applications can never define a priority >0
12144                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12145                        + " package: " + applicationInfo.packageName
12146                        + " activity: " + intent.activity.className
12147                        + " origPrio: " + intent.getPriority());
12148                intent.setPriority(0);
12149                return;
12150            }
12151
12152            if (systemActivities == null) {
12153                // the system package is not disabled; we're parsing the system partition
12154                if (isProtectedAction(intent)) {
12155                    if (mDeferProtectedFilters) {
12156                        // We can't deal with these just yet. No component should ever obtain a
12157                        // >0 priority for a protected actions, with ONE exception -- the setup
12158                        // wizard. The setup wizard, however, cannot be known until we're able to
12159                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12160                        // until all intent filters have been processed. Chicken, meet egg.
12161                        // Let the filter temporarily have a high priority and rectify the
12162                        // priorities after all system packages have been scanned.
12163                        mProtectedFilters.add(intent);
12164                        if (DEBUG_FILTERS) {
12165                            Slog.i(TAG, "Protected action; save for later;"
12166                                    + " package: " + applicationInfo.packageName
12167                                    + " activity: " + intent.activity.className
12168                                    + " origPrio: " + intent.getPriority());
12169                        }
12170                        return;
12171                    } else {
12172                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12173                            Slog.i(TAG, "No setup wizard;"
12174                                + " All protected intents capped to priority 0");
12175                        }
12176                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12177                            if (DEBUG_FILTERS) {
12178                                Slog.i(TAG, "Found setup wizard;"
12179                                    + " allow priority " + intent.getPriority() + ";"
12180                                    + " package: " + intent.activity.info.packageName
12181                                    + " activity: " + intent.activity.className
12182                                    + " priority: " + intent.getPriority());
12183                            }
12184                            // setup wizard gets whatever it wants
12185                            return;
12186                        }
12187                        Slog.w(TAG, "Protected action; cap priority to 0;"
12188                                + " package: " + intent.activity.info.packageName
12189                                + " activity: " + intent.activity.className
12190                                + " origPrio: " + intent.getPriority());
12191                        intent.setPriority(0);
12192                        return;
12193                    }
12194                }
12195                // privileged apps on the system image get whatever priority they request
12196                return;
12197            }
12198
12199            // privileged app unbundled update ... try to find the same activity
12200            final PackageParser.Activity foundActivity =
12201                    findMatchingActivity(systemActivities, activityInfo);
12202            if (foundActivity == null) {
12203                // this is a new activity; it cannot obtain >0 priority
12204                if (DEBUG_FILTERS) {
12205                    Slog.i(TAG, "New activity; cap priority to 0;"
12206                            + " package: " + applicationInfo.packageName
12207                            + " activity: " + intent.activity.className
12208                            + " origPrio: " + intent.getPriority());
12209                }
12210                intent.setPriority(0);
12211                return;
12212            }
12213
12214            // found activity, now check for filter equivalence
12215
12216            // a shallow copy is enough; we modify the list, not its contents
12217            final List<ActivityIntentInfo> intentListCopy =
12218                    new ArrayList<>(foundActivity.intents);
12219            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12220
12221            // find matching action subsets
12222            final Iterator<String> actionsIterator = intent.actionsIterator();
12223            if (actionsIterator != null) {
12224                getIntentListSubset(
12225                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12226                if (intentListCopy.size() == 0) {
12227                    // no more intents to match; we're not equivalent
12228                    if (DEBUG_FILTERS) {
12229                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12230                                + " package: " + applicationInfo.packageName
12231                                + " activity: " + intent.activity.className
12232                                + " origPrio: " + intent.getPriority());
12233                    }
12234                    intent.setPriority(0);
12235                    return;
12236                }
12237            }
12238
12239            // find matching category subsets
12240            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12241            if (categoriesIterator != null) {
12242                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12243                        categoriesIterator);
12244                if (intentListCopy.size() == 0) {
12245                    // no more intents to match; we're not equivalent
12246                    if (DEBUG_FILTERS) {
12247                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12248                                + " package: " + applicationInfo.packageName
12249                                + " activity: " + intent.activity.className
12250                                + " origPrio: " + intent.getPriority());
12251                    }
12252                    intent.setPriority(0);
12253                    return;
12254                }
12255            }
12256
12257            // find matching schemes subsets
12258            final Iterator<String> schemesIterator = intent.schemesIterator();
12259            if (schemesIterator != null) {
12260                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12261                        schemesIterator);
12262                if (intentListCopy.size() == 0) {
12263                    // no more intents to match; we're not equivalent
12264                    if (DEBUG_FILTERS) {
12265                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12266                                + " package: " + applicationInfo.packageName
12267                                + " activity: " + intent.activity.className
12268                                + " origPrio: " + intent.getPriority());
12269                    }
12270                    intent.setPriority(0);
12271                    return;
12272                }
12273            }
12274
12275            // find matching authorities subsets
12276            final Iterator<IntentFilter.AuthorityEntry>
12277                    authoritiesIterator = intent.authoritiesIterator();
12278            if (authoritiesIterator != null) {
12279                getIntentListSubset(intentListCopy,
12280                        new AuthoritiesIterGenerator(),
12281                        authoritiesIterator);
12282                if (intentListCopy.size() == 0) {
12283                    // no more intents to match; we're not equivalent
12284                    if (DEBUG_FILTERS) {
12285                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12286                                + " package: " + applicationInfo.packageName
12287                                + " activity: " + intent.activity.className
12288                                + " origPrio: " + intent.getPriority());
12289                    }
12290                    intent.setPriority(0);
12291                    return;
12292                }
12293            }
12294
12295            // we found matching filter(s); app gets the max priority of all intents
12296            int cappedPriority = 0;
12297            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12298                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12299            }
12300            if (intent.getPriority() > cappedPriority) {
12301                if (DEBUG_FILTERS) {
12302                    Slog.i(TAG, "Found matching filter(s);"
12303                            + " cap priority to " + cappedPriority + ";"
12304                            + " package: " + applicationInfo.packageName
12305                            + " activity: " + intent.activity.className
12306                            + " origPrio: " + intent.getPriority());
12307                }
12308                intent.setPriority(cappedPriority);
12309                return;
12310            }
12311            // all this for nothing; the requested priority was <= what was on the system
12312        }
12313
12314        public final void addActivity(PackageParser.Activity a, String type) {
12315            mActivities.put(a.getComponentName(), a);
12316            if (DEBUG_SHOW_INFO)
12317                Log.v(
12318                TAG, "  " + type + " " +
12319                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12320            if (DEBUG_SHOW_INFO)
12321                Log.v(TAG, "    Class=" + a.info.name);
12322            final int NI = a.intents.size();
12323            for (int j=0; j<NI; j++) {
12324                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12325                if ("activity".equals(type)) {
12326                    final PackageSetting ps =
12327                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12328                    final List<PackageParser.Activity> systemActivities =
12329                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12330                    adjustPriority(systemActivities, intent);
12331                }
12332                if (DEBUG_SHOW_INFO) {
12333                    Log.v(TAG, "    IntentFilter:");
12334                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12335                }
12336                if (!intent.debugCheck()) {
12337                    Log.w(TAG, "==> For Activity " + a.info.name);
12338                }
12339                addFilter(intent);
12340            }
12341        }
12342
12343        public final void removeActivity(PackageParser.Activity a, String type) {
12344            mActivities.remove(a.getComponentName());
12345            if (DEBUG_SHOW_INFO) {
12346                Log.v(TAG, "  " + type + " "
12347                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12348                                : a.info.name) + ":");
12349                Log.v(TAG, "    Class=" + a.info.name);
12350            }
12351            final int NI = a.intents.size();
12352            for (int j=0; j<NI; j++) {
12353                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12354                if (DEBUG_SHOW_INFO) {
12355                    Log.v(TAG, "    IntentFilter:");
12356                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12357                }
12358                removeFilter(intent);
12359            }
12360        }
12361
12362        @Override
12363        protected boolean allowFilterResult(
12364                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12365            ActivityInfo filterAi = filter.activity.info;
12366            for (int i=dest.size()-1; i>=0; i--) {
12367                ActivityInfo destAi = dest.get(i).activityInfo;
12368                if (destAi.name == filterAi.name
12369                        && destAi.packageName == filterAi.packageName) {
12370                    return false;
12371                }
12372            }
12373            return true;
12374        }
12375
12376        @Override
12377        protected ActivityIntentInfo[] newArray(int size) {
12378            return new ActivityIntentInfo[size];
12379        }
12380
12381        @Override
12382        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12383            if (!sUserManager.exists(userId)) return true;
12384            PackageParser.Package p = filter.activity.owner;
12385            if (p != null) {
12386                PackageSetting ps = (PackageSetting)p.mExtras;
12387                if (ps != null) {
12388                    // System apps are never considered stopped for purposes of
12389                    // filtering, because there may be no way for the user to
12390                    // actually re-launch them.
12391                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12392                            && ps.getStopped(userId);
12393                }
12394            }
12395            return false;
12396        }
12397
12398        @Override
12399        protected boolean isPackageForFilter(String packageName,
12400                PackageParser.ActivityIntentInfo info) {
12401            return packageName.equals(info.activity.owner.packageName);
12402        }
12403
12404        @Override
12405        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12406                int match, int userId) {
12407            if (!sUserManager.exists(userId)) return null;
12408            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12409                return null;
12410            }
12411            final PackageParser.Activity activity = info.activity;
12412            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12413            if (ps == null) {
12414                return null;
12415            }
12416            final PackageUserState userState = ps.readUserState(userId);
12417            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
12418            if (ai == null) {
12419                return null;
12420            }
12421            final boolean matchVisibleToInstantApp =
12422                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12423            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12424            // throw out filters that aren't visible to ephemeral apps
12425            if (matchVisibleToInstantApp
12426                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12427                return null;
12428            }
12429            // throw out ephemeral filters if we're not explicitly requesting them
12430            if (!isInstantApp && userState.instantApp) {
12431                return null;
12432            }
12433            // throw out instant app filters if updates are available; will trigger
12434            // instant app resolution
12435            if (userState.instantApp && ps.isUpdateAvailable()) {
12436                return null;
12437            }
12438            final ResolveInfo res = new ResolveInfo();
12439            res.activityInfo = ai;
12440            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12441                res.filter = info;
12442            }
12443            if (info != null) {
12444                res.handleAllWebDataURI = info.handleAllWebDataURI();
12445            }
12446            res.priority = info.getPriority();
12447            res.preferredOrder = activity.owner.mPreferredOrder;
12448            //System.out.println("Result: " + res.activityInfo.className +
12449            //                   " = " + res.priority);
12450            res.match = match;
12451            res.isDefault = info.hasDefault;
12452            res.labelRes = info.labelRes;
12453            res.nonLocalizedLabel = info.nonLocalizedLabel;
12454            if (userNeedsBadging(userId)) {
12455                res.noResourceId = true;
12456            } else {
12457                res.icon = info.icon;
12458            }
12459            res.iconResourceId = info.icon;
12460            res.system = res.activityInfo.applicationInfo.isSystemApp();
12461            res.instantAppAvailable = userState.instantApp;
12462            return res;
12463        }
12464
12465        @Override
12466        protected void sortResults(List<ResolveInfo> results) {
12467            Collections.sort(results, mResolvePrioritySorter);
12468        }
12469
12470        @Override
12471        protected void dumpFilter(PrintWriter out, String prefix,
12472                PackageParser.ActivityIntentInfo filter) {
12473            out.print(prefix); out.print(
12474                    Integer.toHexString(System.identityHashCode(filter.activity)));
12475                    out.print(' ');
12476                    filter.activity.printComponentShortName(out);
12477                    out.print(" filter ");
12478                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12479        }
12480
12481        @Override
12482        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12483            return filter.activity;
12484        }
12485
12486        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12487            PackageParser.Activity activity = (PackageParser.Activity)label;
12488            out.print(prefix); out.print(
12489                    Integer.toHexString(System.identityHashCode(activity)));
12490                    out.print(' ');
12491                    activity.printComponentShortName(out);
12492            if (count > 1) {
12493                out.print(" ("); out.print(count); out.print(" filters)");
12494            }
12495            out.println();
12496        }
12497
12498        // Keys are String (activity class name), values are Activity.
12499        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12500                = new ArrayMap<ComponentName, PackageParser.Activity>();
12501        private int mFlags;
12502    }
12503
12504    private final class ServiceIntentResolver
12505            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12506        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12507                boolean defaultOnly, int userId) {
12508            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12509            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12510        }
12511
12512        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12513                int userId) {
12514            if (!sUserManager.exists(userId)) return null;
12515            mFlags = flags;
12516            return super.queryIntent(intent, resolvedType,
12517                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12518                    userId);
12519        }
12520
12521        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12522                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12523            if (!sUserManager.exists(userId)) return null;
12524            if (packageServices == null) {
12525                return null;
12526            }
12527            mFlags = flags;
12528            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12529            final int N = packageServices.size();
12530            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12531                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12532
12533            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12534            for (int i = 0; i < N; ++i) {
12535                intentFilters = packageServices.get(i).intents;
12536                if (intentFilters != null && intentFilters.size() > 0) {
12537                    PackageParser.ServiceIntentInfo[] array =
12538                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12539                    intentFilters.toArray(array);
12540                    listCut.add(array);
12541                }
12542            }
12543            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12544        }
12545
12546        public final void addService(PackageParser.Service s) {
12547            mServices.put(s.getComponentName(), s);
12548            if (DEBUG_SHOW_INFO) {
12549                Log.v(TAG, "  "
12550                        + (s.info.nonLocalizedLabel != null
12551                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12552                Log.v(TAG, "    Class=" + s.info.name);
12553            }
12554            final int NI = s.intents.size();
12555            int j;
12556            for (j=0; j<NI; j++) {
12557                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12558                if (DEBUG_SHOW_INFO) {
12559                    Log.v(TAG, "    IntentFilter:");
12560                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12561                }
12562                if (!intent.debugCheck()) {
12563                    Log.w(TAG, "==> For Service " + s.info.name);
12564                }
12565                addFilter(intent);
12566            }
12567        }
12568
12569        public final void removeService(PackageParser.Service s) {
12570            mServices.remove(s.getComponentName());
12571            if (DEBUG_SHOW_INFO) {
12572                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12573                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12574                Log.v(TAG, "    Class=" + s.info.name);
12575            }
12576            final int NI = s.intents.size();
12577            int j;
12578            for (j=0; j<NI; j++) {
12579                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12580                if (DEBUG_SHOW_INFO) {
12581                    Log.v(TAG, "    IntentFilter:");
12582                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12583                }
12584                removeFilter(intent);
12585            }
12586        }
12587
12588        @Override
12589        protected boolean allowFilterResult(
12590                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12591            ServiceInfo filterSi = filter.service.info;
12592            for (int i=dest.size()-1; i>=0; i--) {
12593                ServiceInfo destAi = dest.get(i).serviceInfo;
12594                if (destAi.name == filterSi.name
12595                        && destAi.packageName == filterSi.packageName) {
12596                    return false;
12597                }
12598            }
12599            return true;
12600        }
12601
12602        @Override
12603        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12604            return new PackageParser.ServiceIntentInfo[size];
12605        }
12606
12607        @Override
12608        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12609            if (!sUserManager.exists(userId)) return true;
12610            PackageParser.Package p = filter.service.owner;
12611            if (p != null) {
12612                PackageSetting ps = (PackageSetting)p.mExtras;
12613                if (ps != null) {
12614                    // System apps are never considered stopped for purposes of
12615                    // filtering, because there may be no way for the user to
12616                    // actually re-launch them.
12617                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12618                            && ps.getStopped(userId);
12619                }
12620            }
12621            return false;
12622        }
12623
12624        @Override
12625        protected boolean isPackageForFilter(String packageName,
12626                PackageParser.ServiceIntentInfo info) {
12627            return packageName.equals(info.service.owner.packageName);
12628        }
12629
12630        @Override
12631        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12632                int match, int userId) {
12633            if (!sUserManager.exists(userId)) return null;
12634            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12635            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12636                return null;
12637            }
12638            final PackageParser.Service service = info.service;
12639            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12640            if (ps == null) {
12641                return null;
12642            }
12643            final PackageUserState userState = ps.readUserState(userId);
12644            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12645                    userState, userId);
12646            if (si == null) {
12647                return null;
12648            }
12649            final boolean matchVisibleToInstantApp =
12650                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12651            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12652            // throw out filters that aren't visible to ephemeral apps
12653            if (matchVisibleToInstantApp
12654                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12655                return null;
12656            }
12657            // throw out ephemeral filters if we're not explicitly requesting them
12658            if (!isInstantApp && userState.instantApp) {
12659                return null;
12660            }
12661            // throw out instant app filters if updates are available; will trigger
12662            // instant app resolution
12663            if (userState.instantApp && ps.isUpdateAvailable()) {
12664                return null;
12665            }
12666            final ResolveInfo res = new ResolveInfo();
12667            res.serviceInfo = si;
12668            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12669                res.filter = filter;
12670            }
12671            res.priority = info.getPriority();
12672            res.preferredOrder = service.owner.mPreferredOrder;
12673            res.match = match;
12674            res.isDefault = info.hasDefault;
12675            res.labelRes = info.labelRes;
12676            res.nonLocalizedLabel = info.nonLocalizedLabel;
12677            res.icon = info.icon;
12678            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12679            return res;
12680        }
12681
12682        @Override
12683        protected void sortResults(List<ResolveInfo> results) {
12684            Collections.sort(results, mResolvePrioritySorter);
12685        }
12686
12687        @Override
12688        protected void dumpFilter(PrintWriter out, String prefix,
12689                PackageParser.ServiceIntentInfo filter) {
12690            out.print(prefix); out.print(
12691                    Integer.toHexString(System.identityHashCode(filter.service)));
12692                    out.print(' ');
12693                    filter.service.printComponentShortName(out);
12694                    out.print(" filter ");
12695                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12696        }
12697
12698        @Override
12699        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12700            return filter.service;
12701        }
12702
12703        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12704            PackageParser.Service service = (PackageParser.Service)label;
12705            out.print(prefix); out.print(
12706                    Integer.toHexString(System.identityHashCode(service)));
12707                    out.print(' ');
12708                    service.printComponentShortName(out);
12709            if (count > 1) {
12710                out.print(" ("); out.print(count); out.print(" filters)");
12711            }
12712            out.println();
12713        }
12714
12715//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12716//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12717//            final List<ResolveInfo> retList = Lists.newArrayList();
12718//            while (i.hasNext()) {
12719//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12720//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12721//                    retList.add(resolveInfo);
12722//                }
12723//            }
12724//            return retList;
12725//        }
12726
12727        // Keys are String (activity class name), values are Activity.
12728        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12729                = new ArrayMap<ComponentName, PackageParser.Service>();
12730        private int mFlags;
12731    }
12732
12733    private final class ProviderIntentResolver
12734            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12735        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12736                boolean defaultOnly, int userId) {
12737            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12738            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12739        }
12740
12741        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12742                int userId) {
12743            if (!sUserManager.exists(userId))
12744                return null;
12745            mFlags = flags;
12746            return super.queryIntent(intent, resolvedType,
12747                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12748                    userId);
12749        }
12750
12751        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12752                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12753            if (!sUserManager.exists(userId))
12754                return null;
12755            if (packageProviders == null) {
12756                return null;
12757            }
12758            mFlags = flags;
12759            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12760            final int N = packageProviders.size();
12761            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12762                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12763
12764            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12765            for (int i = 0; i < N; ++i) {
12766                intentFilters = packageProviders.get(i).intents;
12767                if (intentFilters != null && intentFilters.size() > 0) {
12768                    PackageParser.ProviderIntentInfo[] array =
12769                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12770                    intentFilters.toArray(array);
12771                    listCut.add(array);
12772                }
12773            }
12774            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12775        }
12776
12777        public final void addProvider(PackageParser.Provider p) {
12778            if (mProviders.containsKey(p.getComponentName())) {
12779                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12780                return;
12781            }
12782
12783            mProviders.put(p.getComponentName(), p);
12784            if (DEBUG_SHOW_INFO) {
12785                Log.v(TAG, "  "
12786                        + (p.info.nonLocalizedLabel != null
12787                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12788                Log.v(TAG, "    Class=" + p.info.name);
12789            }
12790            final int NI = p.intents.size();
12791            int j;
12792            for (j = 0; j < NI; j++) {
12793                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12794                if (DEBUG_SHOW_INFO) {
12795                    Log.v(TAG, "    IntentFilter:");
12796                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12797                }
12798                if (!intent.debugCheck()) {
12799                    Log.w(TAG, "==> For Provider " + p.info.name);
12800                }
12801                addFilter(intent);
12802            }
12803        }
12804
12805        public final void removeProvider(PackageParser.Provider p) {
12806            mProviders.remove(p.getComponentName());
12807            if (DEBUG_SHOW_INFO) {
12808                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12809                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12810                Log.v(TAG, "    Class=" + p.info.name);
12811            }
12812            final int NI = p.intents.size();
12813            int j;
12814            for (j = 0; j < NI; j++) {
12815                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12816                if (DEBUG_SHOW_INFO) {
12817                    Log.v(TAG, "    IntentFilter:");
12818                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12819                }
12820                removeFilter(intent);
12821            }
12822        }
12823
12824        @Override
12825        protected boolean allowFilterResult(
12826                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12827            ProviderInfo filterPi = filter.provider.info;
12828            for (int i = dest.size() - 1; i >= 0; i--) {
12829                ProviderInfo destPi = dest.get(i).providerInfo;
12830                if (destPi.name == filterPi.name
12831                        && destPi.packageName == filterPi.packageName) {
12832                    return false;
12833                }
12834            }
12835            return true;
12836        }
12837
12838        @Override
12839        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12840            return new PackageParser.ProviderIntentInfo[size];
12841        }
12842
12843        @Override
12844        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12845            if (!sUserManager.exists(userId))
12846                return true;
12847            PackageParser.Package p = filter.provider.owner;
12848            if (p != null) {
12849                PackageSetting ps = (PackageSetting) p.mExtras;
12850                if (ps != null) {
12851                    // System apps are never considered stopped for purposes of
12852                    // filtering, because there may be no way for the user to
12853                    // actually re-launch them.
12854                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12855                            && ps.getStopped(userId);
12856                }
12857            }
12858            return false;
12859        }
12860
12861        @Override
12862        protected boolean isPackageForFilter(String packageName,
12863                PackageParser.ProviderIntentInfo info) {
12864            return packageName.equals(info.provider.owner.packageName);
12865        }
12866
12867        @Override
12868        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12869                int match, int userId) {
12870            if (!sUserManager.exists(userId))
12871                return null;
12872            final PackageParser.ProviderIntentInfo info = filter;
12873            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12874                return null;
12875            }
12876            final PackageParser.Provider provider = info.provider;
12877            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12878            if (ps == null) {
12879                return null;
12880            }
12881            final PackageUserState userState = ps.readUserState(userId);
12882            final boolean matchVisibleToInstantApp =
12883                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12884            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12885            // throw out filters that aren't visible to instant applications
12886            if (matchVisibleToInstantApp
12887                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12888                return null;
12889            }
12890            // throw out instant application filters if we're not explicitly requesting them
12891            if (!isInstantApp && userState.instantApp) {
12892                return null;
12893            }
12894            // throw out instant application filters if updates are available; will trigger
12895            // instant application resolution
12896            if (userState.instantApp && ps.isUpdateAvailable()) {
12897                return null;
12898            }
12899            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12900                    userState, userId);
12901            if (pi == null) {
12902                return null;
12903            }
12904            final ResolveInfo res = new ResolveInfo();
12905            res.providerInfo = pi;
12906            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12907                res.filter = filter;
12908            }
12909            res.priority = info.getPriority();
12910            res.preferredOrder = provider.owner.mPreferredOrder;
12911            res.match = match;
12912            res.isDefault = info.hasDefault;
12913            res.labelRes = info.labelRes;
12914            res.nonLocalizedLabel = info.nonLocalizedLabel;
12915            res.icon = info.icon;
12916            res.system = res.providerInfo.applicationInfo.isSystemApp();
12917            return res;
12918        }
12919
12920        @Override
12921        protected void sortResults(List<ResolveInfo> results) {
12922            Collections.sort(results, mResolvePrioritySorter);
12923        }
12924
12925        @Override
12926        protected void dumpFilter(PrintWriter out, String prefix,
12927                PackageParser.ProviderIntentInfo filter) {
12928            out.print(prefix);
12929            out.print(
12930                    Integer.toHexString(System.identityHashCode(filter.provider)));
12931            out.print(' ');
12932            filter.provider.printComponentShortName(out);
12933            out.print(" filter ");
12934            out.println(Integer.toHexString(System.identityHashCode(filter)));
12935        }
12936
12937        @Override
12938        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12939            return filter.provider;
12940        }
12941
12942        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12943            PackageParser.Provider provider = (PackageParser.Provider)label;
12944            out.print(prefix); out.print(
12945                    Integer.toHexString(System.identityHashCode(provider)));
12946                    out.print(' ');
12947                    provider.printComponentShortName(out);
12948            if (count > 1) {
12949                out.print(" ("); out.print(count); out.print(" filters)");
12950            }
12951            out.println();
12952        }
12953
12954        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12955                = new ArrayMap<ComponentName, PackageParser.Provider>();
12956        private int mFlags;
12957    }
12958
12959    static final class EphemeralIntentResolver
12960            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12961        /**
12962         * The result that has the highest defined order. Ordering applies on a
12963         * per-package basis. Mapping is from package name to Pair of order and
12964         * EphemeralResolveInfo.
12965         * <p>
12966         * NOTE: This is implemented as a field variable for convenience and efficiency.
12967         * By having a field variable, we're able to track filter ordering as soon as
12968         * a non-zero order is defined. Otherwise, multiple loops across the result set
12969         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12970         * this needs to be contained entirely within {@link #filterResults}.
12971         */
12972        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12973
12974        @Override
12975        protected AuxiliaryResolveInfo[] newArray(int size) {
12976            return new AuxiliaryResolveInfo[size];
12977        }
12978
12979        @Override
12980        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12981            return true;
12982        }
12983
12984        @Override
12985        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12986                int userId) {
12987            if (!sUserManager.exists(userId)) {
12988                return null;
12989            }
12990            final String packageName = responseObj.resolveInfo.getPackageName();
12991            final Integer order = responseObj.getOrder();
12992            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12993                    mOrderResult.get(packageName);
12994            // ordering is enabled and this item's order isn't high enough
12995            if (lastOrderResult != null && lastOrderResult.first >= order) {
12996                return null;
12997            }
12998            final InstantAppResolveInfo res = responseObj.resolveInfo;
12999            if (order > 0) {
13000                // non-zero order, enable ordering
13001                mOrderResult.put(packageName, new Pair<>(order, res));
13002            }
13003            return responseObj;
13004        }
13005
13006        @Override
13007        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13008            // only do work if ordering is enabled [most of the time it won't be]
13009            if (mOrderResult.size() == 0) {
13010                return;
13011            }
13012            int resultSize = results.size();
13013            for (int i = 0; i < resultSize; i++) {
13014                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13015                final String packageName = info.getPackageName();
13016                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13017                if (savedInfo == null) {
13018                    // package doesn't having ordering
13019                    continue;
13020                }
13021                if (savedInfo.second == info) {
13022                    // circled back to the highest ordered item; remove from order list
13023                    mOrderResult.remove(savedInfo);
13024                    if (mOrderResult.size() == 0) {
13025                        // no more ordered items
13026                        break;
13027                    }
13028                    continue;
13029                }
13030                // item has a worse order, remove it from the result list
13031                results.remove(i);
13032                resultSize--;
13033                i--;
13034            }
13035        }
13036    }
13037
13038    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13039            new Comparator<ResolveInfo>() {
13040        public int compare(ResolveInfo r1, ResolveInfo r2) {
13041            int v1 = r1.priority;
13042            int v2 = r2.priority;
13043            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13044            if (v1 != v2) {
13045                return (v1 > v2) ? -1 : 1;
13046            }
13047            v1 = r1.preferredOrder;
13048            v2 = r2.preferredOrder;
13049            if (v1 != v2) {
13050                return (v1 > v2) ? -1 : 1;
13051            }
13052            if (r1.isDefault != r2.isDefault) {
13053                return r1.isDefault ? -1 : 1;
13054            }
13055            v1 = r1.match;
13056            v2 = r2.match;
13057            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13058            if (v1 != v2) {
13059                return (v1 > v2) ? -1 : 1;
13060            }
13061            if (r1.system != r2.system) {
13062                return r1.system ? -1 : 1;
13063            }
13064            if (r1.activityInfo != null) {
13065                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13066            }
13067            if (r1.serviceInfo != null) {
13068                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13069            }
13070            if (r1.providerInfo != null) {
13071                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13072            }
13073            return 0;
13074        }
13075    };
13076
13077    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13078            new Comparator<ProviderInfo>() {
13079        public int compare(ProviderInfo p1, ProviderInfo p2) {
13080            final int v1 = p1.initOrder;
13081            final int v2 = p2.initOrder;
13082            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13083        }
13084    };
13085
13086    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13087            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13088            final int[] userIds) {
13089        mHandler.post(new Runnable() {
13090            @Override
13091            public void run() {
13092                try {
13093                    final IActivityManager am = ActivityManager.getService();
13094                    if (am == null) return;
13095                    final int[] resolvedUserIds;
13096                    if (userIds == null) {
13097                        resolvedUserIds = am.getRunningUserIds();
13098                    } else {
13099                        resolvedUserIds = userIds;
13100                    }
13101                    for (int id : resolvedUserIds) {
13102                        final Intent intent = new Intent(action,
13103                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13104                        if (extras != null) {
13105                            intent.putExtras(extras);
13106                        }
13107                        if (targetPkg != null) {
13108                            intent.setPackage(targetPkg);
13109                        }
13110                        // Modify the UID when posting to other users
13111                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13112                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13113                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13114                            intent.putExtra(Intent.EXTRA_UID, uid);
13115                        }
13116                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13117                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13118                        if (DEBUG_BROADCASTS) {
13119                            RuntimeException here = new RuntimeException("here");
13120                            here.fillInStackTrace();
13121                            Slog.d(TAG, "Sending to user " + id + ": "
13122                                    + intent.toShortString(false, true, false, false)
13123                                    + " " + intent.getExtras(), here);
13124                        }
13125                        am.broadcastIntent(null, intent, null, finishedReceiver,
13126                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13127                                null, finishedReceiver != null, false, id);
13128                    }
13129                } catch (RemoteException ex) {
13130                }
13131            }
13132        });
13133    }
13134
13135    /**
13136     * Check if the external storage media is available. This is true if there
13137     * is a mounted external storage medium or if the external storage is
13138     * emulated.
13139     */
13140    private boolean isExternalMediaAvailable() {
13141        return mMediaMounted || Environment.isExternalStorageEmulated();
13142    }
13143
13144    @Override
13145    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13146        // writer
13147        synchronized (mPackages) {
13148            if (!isExternalMediaAvailable()) {
13149                // If the external storage is no longer mounted at this point,
13150                // the caller may not have been able to delete all of this
13151                // packages files and can not delete any more.  Bail.
13152                return null;
13153            }
13154            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13155            if (lastPackage != null) {
13156                pkgs.remove(lastPackage);
13157            }
13158            if (pkgs.size() > 0) {
13159                return pkgs.get(0);
13160            }
13161        }
13162        return null;
13163    }
13164
13165    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13166        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13167                userId, andCode ? 1 : 0, packageName);
13168        if (mSystemReady) {
13169            msg.sendToTarget();
13170        } else {
13171            if (mPostSystemReadyMessages == null) {
13172                mPostSystemReadyMessages = new ArrayList<>();
13173            }
13174            mPostSystemReadyMessages.add(msg);
13175        }
13176    }
13177
13178    void startCleaningPackages() {
13179        // reader
13180        if (!isExternalMediaAvailable()) {
13181            return;
13182        }
13183        synchronized (mPackages) {
13184            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13185                return;
13186            }
13187        }
13188        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13189        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13190        IActivityManager am = ActivityManager.getService();
13191        if (am != null) {
13192            int dcsUid = -1;
13193            synchronized (mPackages) {
13194                if (!mDefaultContainerWhitelisted) {
13195                    mDefaultContainerWhitelisted = true;
13196                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13197                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13198                }
13199            }
13200            try {
13201                if (dcsUid > 0) {
13202                    am.backgroundWhitelistUid(dcsUid);
13203                }
13204                am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(),
13205                        UserHandle.USER_SYSTEM);
13206            } catch (RemoteException e) {
13207            }
13208        }
13209    }
13210
13211    @Override
13212    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13213            int installFlags, String installerPackageName, int userId) {
13214        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13215
13216        final int callingUid = Binder.getCallingUid();
13217        enforceCrossUserPermission(callingUid, userId,
13218                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13219
13220        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13221            try {
13222                if (observer != null) {
13223                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13224                }
13225            } catch (RemoteException re) {
13226            }
13227            return;
13228        }
13229
13230        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13231            installFlags |= PackageManager.INSTALL_FROM_ADB;
13232
13233        } else {
13234            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13235            // about installerPackageName.
13236
13237            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13238            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13239        }
13240
13241        UserHandle user;
13242        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13243            user = UserHandle.ALL;
13244        } else {
13245            user = new UserHandle(userId);
13246        }
13247
13248        // Only system components can circumvent runtime permissions when installing.
13249        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13250                && mContext.checkCallingOrSelfPermission(Manifest.permission
13251                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13252            throw new SecurityException("You need the "
13253                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13254                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13255        }
13256
13257        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13258                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13259            throw new IllegalArgumentException(
13260                    "New installs into ASEC containers no longer supported");
13261        }
13262
13263        final File originFile = new File(originPath);
13264        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13265
13266        final Message msg = mHandler.obtainMessage(INIT_COPY);
13267        final VerificationInfo verificationInfo = new VerificationInfo(
13268                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13269        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13270                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13271                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13272                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13273        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13274        msg.obj = params;
13275
13276        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13277                System.identityHashCode(msg.obj));
13278        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13279                System.identityHashCode(msg.obj));
13280
13281        mHandler.sendMessage(msg);
13282    }
13283
13284
13285    /**
13286     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13287     * it is acting on behalf on an enterprise or the user).
13288     *
13289     * Note that the ordering of the conditionals in this method is important. The checks we perform
13290     * are as follows, in this order:
13291     *
13292     * 1) If the install is being performed by a system app, we can trust the app to have set the
13293     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13294     *    what it is.
13295     * 2) If the install is being performed by a device or profile owner app, the install reason
13296     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13297     *    set the install reason correctly. If the app targets an older SDK version where install
13298     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13299     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13300     * 3) In all other cases, the install is being performed by a regular app that is neither part
13301     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13302     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13303     *    set to enterprise policy and if so, change it to unknown instead.
13304     */
13305    private int fixUpInstallReason(String installerPackageName, int installerUid,
13306            int installReason) {
13307        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13308                == PERMISSION_GRANTED) {
13309            // If the install is being performed by a system app, we trust that app to have set the
13310            // install reason correctly.
13311            return installReason;
13312        }
13313
13314        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13315            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13316        if (dpm != null) {
13317            ComponentName owner = null;
13318            try {
13319                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13320                if (owner == null) {
13321                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13322                }
13323            } catch (RemoteException e) {
13324            }
13325            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13326                // If the install is being performed by a device or profile owner, the install
13327                // reason should be enterprise policy.
13328                return PackageManager.INSTALL_REASON_POLICY;
13329            }
13330        }
13331
13332        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13333            // If the install is being performed by a regular app (i.e. neither system app nor
13334            // device or profile owner), we have no reason to believe that the app is acting on
13335            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13336            // change it to unknown instead.
13337            return PackageManager.INSTALL_REASON_UNKNOWN;
13338        }
13339
13340        // If the install is being performed by a regular app and the install reason was set to any
13341        // value but enterprise policy, leave the install reason unchanged.
13342        return installReason;
13343    }
13344
13345    void installStage(String packageName, File stagedDir, String stagedCid,
13346            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13347            String installerPackageName, int installerUid, UserHandle user,
13348            Certificate[][] certificates) {
13349        if (DEBUG_EPHEMERAL) {
13350            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13351                Slog.d(TAG, "Ephemeral install of " + packageName);
13352            }
13353        }
13354        final VerificationInfo verificationInfo = new VerificationInfo(
13355                sessionParams.originatingUri, sessionParams.referrerUri,
13356                sessionParams.originatingUid, installerUid);
13357
13358        final OriginInfo origin;
13359        if (stagedDir != null) {
13360            origin = OriginInfo.fromStagedFile(stagedDir);
13361        } else {
13362            origin = OriginInfo.fromStagedContainer(stagedCid);
13363        }
13364
13365        final Message msg = mHandler.obtainMessage(INIT_COPY);
13366        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13367                sessionParams.installReason);
13368        final InstallParams params = new InstallParams(origin, null, observer,
13369                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13370                verificationInfo, user, sessionParams.abiOverride,
13371                sessionParams.grantedRuntimePermissions, certificates, installReason);
13372        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13373        msg.obj = params;
13374
13375        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13376                System.identityHashCode(msg.obj));
13377        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13378                System.identityHashCode(msg.obj));
13379
13380        mHandler.sendMessage(msg);
13381    }
13382
13383    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13384            int userId) {
13385        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13386        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13387    }
13388
13389    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13390            int appId, int... userIds) {
13391        if (ArrayUtils.isEmpty(userIds)) {
13392            return;
13393        }
13394        Bundle extras = new Bundle(1);
13395        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13396        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13397
13398        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_ADDED, packageName,
13399                extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, userIds);
13400        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13401                extras, 0, null, null, userIds);
13402        if (isSystem) {
13403            mHandler.post(() -> {
13404                        for (int userId : userIds) {
13405                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13406                        }
13407                    }
13408            );
13409        }
13410    }
13411
13412    /**
13413     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13414     * automatically without needing an explicit launch.
13415     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13416     */
13417    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13418        // If user is not running, the app didn't miss any broadcast
13419        if (!mUserManagerInternal.isUserRunning(userId)) {
13420            return;
13421        }
13422        final IActivityManager am = ActivityManager.getService();
13423        try {
13424            // Deliver LOCKED_BOOT_COMPLETED first
13425            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13426                    .setPackage(packageName);
13427            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13428            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13429                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13430
13431            // Deliver BOOT_COMPLETED only if user is unlocked
13432            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13433                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13434                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13435                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13436            }
13437        } catch (RemoteException e) {
13438            throw e.rethrowFromSystemServer();
13439        }
13440    }
13441
13442    @Override
13443    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13444            int userId) {
13445        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13446        PackageSetting pkgSetting;
13447        final int uid = Binder.getCallingUid();
13448        enforceCrossUserPermission(uid, userId,
13449                true /* requireFullPermission */, true /* checkShell */,
13450                "setApplicationHiddenSetting for user " + userId);
13451
13452        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13453            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13454            return false;
13455        }
13456
13457        long callingId = Binder.clearCallingIdentity();
13458        try {
13459            boolean sendAdded = false;
13460            boolean sendRemoved = false;
13461            // writer
13462            synchronized (mPackages) {
13463                pkgSetting = mSettings.mPackages.get(packageName);
13464                if (pkgSetting == null) {
13465                    return false;
13466                }
13467                // Do not allow "android" is being disabled
13468                if ("android".equals(packageName)) {
13469                    Slog.w(TAG, "Cannot hide package: android");
13470                    return false;
13471                }
13472                // Cannot hide static shared libs as they are considered
13473                // a part of the using app (emulating static linking). Also
13474                // static libs are installed always on internal storage.
13475                PackageParser.Package pkg = mPackages.get(packageName);
13476                if (pkg != null && pkg.staticSharedLibName != null) {
13477                    Slog.w(TAG, "Cannot hide package: " + packageName
13478                            + " providing static shared library: "
13479                            + pkg.staticSharedLibName);
13480                    return false;
13481                }
13482                // Only allow protected packages to hide themselves.
13483                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13484                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13485                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13486                    return false;
13487                }
13488
13489                if (pkgSetting.getHidden(userId) != hidden) {
13490                    pkgSetting.setHidden(hidden, userId);
13491                    mSettings.writePackageRestrictionsLPr(userId);
13492                    if (hidden) {
13493                        sendRemoved = true;
13494                    } else {
13495                        sendAdded = true;
13496                    }
13497                }
13498            }
13499            if (sendAdded) {
13500                sendPackageAddedForUser(packageName, pkgSetting, userId);
13501                return true;
13502            }
13503            if (sendRemoved) {
13504                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13505                        "hiding pkg");
13506                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13507                return true;
13508            }
13509        } finally {
13510            Binder.restoreCallingIdentity(callingId);
13511        }
13512        return false;
13513    }
13514
13515    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13516            int userId) {
13517        final PackageRemovedInfo info = new PackageRemovedInfo();
13518        info.removedPackage = packageName;
13519        info.removedUsers = new int[] {userId};
13520        info.broadcastUsers = new int[] {userId};
13521        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13522        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13523    }
13524
13525    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13526        if (pkgList.length > 0) {
13527            Bundle extras = new Bundle(1);
13528            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13529
13530            sendPackageBroadcast(
13531                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13532                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13533                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13534                    new int[] {userId});
13535        }
13536    }
13537
13538    /**
13539     * Returns true if application is not found or there was an error. Otherwise it returns
13540     * the hidden state of the package for the given user.
13541     */
13542    @Override
13543    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13544        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13545        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13546                true /* requireFullPermission */, false /* checkShell */,
13547                "getApplicationHidden for user " + userId);
13548        PackageSetting pkgSetting;
13549        long callingId = Binder.clearCallingIdentity();
13550        try {
13551            // writer
13552            synchronized (mPackages) {
13553                pkgSetting = mSettings.mPackages.get(packageName);
13554                if (pkgSetting == null) {
13555                    return true;
13556                }
13557                return pkgSetting.getHidden(userId);
13558            }
13559        } finally {
13560            Binder.restoreCallingIdentity(callingId);
13561        }
13562    }
13563
13564    /**
13565     * @hide
13566     */
13567    @Override
13568    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13569            int installReason) {
13570        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13571                null);
13572        PackageSetting pkgSetting;
13573        final int uid = Binder.getCallingUid();
13574        enforceCrossUserPermission(uid, userId,
13575                true /* requireFullPermission */, true /* checkShell */,
13576                "installExistingPackage for user " + userId);
13577        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13578            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13579        }
13580
13581        long callingId = Binder.clearCallingIdentity();
13582        try {
13583            boolean installed = false;
13584            final boolean instantApp =
13585                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13586            final boolean fullApp =
13587                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13588
13589            // writer
13590            synchronized (mPackages) {
13591                pkgSetting = mSettings.mPackages.get(packageName);
13592                if (pkgSetting == null) {
13593                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13594                }
13595                if (!pkgSetting.getInstalled(userId)) {
13596                    pkgSetting.setInstalled(true, userId);
13597                    pkgSetting.setHidden(false, userId);
13598                    pkgSetting.setInstallReason(installReason, userId);
13599                    mSettings.writePackageRestrictionsLPr(userId);
13600                    mSettings.writeKernelMappingLPr(pkgSetting);
13601                    installed = true;
13602                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13603                    // upgrade app from instant to full; we don't allow app downgrade
13604                    installed = true;
13605                }
13606                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13607            }
13608
13609            if (installed) {
13610                if (pkgSetting.pkg != null) {
13611                    synchronized (mInstallLock) {
13612                        // We don't need to freeze for a brand new install
13613                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13614                    }
13615                }
13616                sendPackageAddedForUser(packageName, pkgSetting, userId);
13617                synchronized (mPackages) {
13618                    updateSequenceNumberLP(packageName, new int[]{ userId });
13619                }
13620            }
13621        } finally {
13622            Binder.restoreCallingIdentity(callingId);
13623        }
13624
13625        return PackageManager.INSTALL_SUCCEEDED;
13626    }
13627
13628    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13629            boolean instantApp, boolean fullApp) {
13630        // no state specified; do nothing
13631        if (!instantApp && !fullApp) {
13632            return;
13633        }
13634        if (userId != UserHandle.USER_ALL) {
13635            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13636                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13637            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13638                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13639            }
13640        } else {
13641            for (int currentUserId : sUserManager.getUserIds()) {
13642                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13643                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13644                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13645                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13646                }
13647            }
13648        }
13649    }
13650
13651    boolean isUserRestricted(int userId, String restrictionKey) {
13652        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13653        if (restrictions.getBoolean(restrictionKey, false)) {
13654            Log.w(TAG, "User is restricted: " + restrictionKey);
13655            return true;
13656        }
13657        return false;
13658    }
13659
13660    @Override
13661    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13662            int userId) {
13663        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13664        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13665                true /* requireFullPermission */, true /* checkShell */,
13666                "setPackagesSuspended for user " + userId);
13667
13668        if (ArrayUtils.isEmpty(packageNames)) {
13669            return packageNames;
13670        }
13671
13672        // List of package names for whom the suspended state has changed.
13673        List<String> changedPackages = new ArrayList<>(packageNames.length);
13674        // List of package names for whom the suspended state is not set as requested in this
13675        // method.
13676        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13677        long callingId = Binder.clearCallingIdentity();
13678        try {
13679            for (int i = 0; i < packageNames.length; i++) {
13680                String packageName = packageNames[i];
13681                boolean changed = false;
13682                final int appId;
13683                synchronized (mPackages) {
13684                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13685                    if (pkgSetting == null) {
13686                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13687                                + "\". Skipping suspending/un-suspending.");
13688                        unactionedPackages.add(packageName);
13689                        continue;
13690                    }
13691                    appId = pkgSetting.appId;
13692                    if (pkgSetting.getSuspended(userId) != suspended) {
13693                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13694                            unactionedPackages.add(packageName);
13695                            continue;
13696                        }
13697                        pkgSetting.setSuspended(suspended, userId);
13698                        mSettings.writePackageRestrictionsLPr(userId);
13699                        changed = true;
13700                        changedPackages.add(packageName);
13701                    }
13702                }
13703
13704                if (changed && suspended) {
13705                    killApplication(packageName, UserHandle.getUid(userId, appId),
13706                            "suspending package");
13707                }
13708            }
13709        } finally {
13710            Binder.restoreCallingIdentity(callingId);
13711        }
13712
13713        if (!changedPackages.isEmpty()) {
13714            sendPackagesSuspendedForUser(changedPackages.toArray(
13715                    new String[changedPackages.size()]), userId, suspended);
13716        }
13717
13718        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13719    }
13720
13721    @Override
13722    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13723        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13724                true /* requireFullPermission */, false /* checkShell */,
13725                "isPackageSuspendedForUser for user " + userId);
13726        synchronized (mPackages) {
13727            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13728            if (pkgSetting == null) {
13729                throw new IllegalArgumentException("Unknown target package: " + packageName);
13730            }
13731            return pkgSetting.getSuspended(userId);
13732        }
13733    }
13734
13735    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13736        if (isPackageDeviceAdmin(packageName, userId)) {
13737            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13738                    + "\": has an active device admin");
13739            return false;
13740        }
13741
13742        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13743        if (packageName.equals(activeLauncherPackageName)) {
13744            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13745                    + "\": contains the active launcher");
13746            return false;
13747        }
13748
13749        if (packageName.equals(mRequiredInstallerPackage)) {
13750            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13751                    + "\": required for package installation");
13752            return false;
13753        }
13754
13755        if (packageName.equals(mRequiredUninstallerPackage)) {
13756            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13757                    + "\": required for package uninstallation");
13758            return false;
13759        }
13760
13761        if (packageName.equals(mRequiredVerifierPackage)) {
13762            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13763                    + "\": required for package verification");
13764            return false;
13765        }
13766
13767        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13768            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13769                    + "\": is the default dialer");
13770            return false;
13771        }
13772
13773        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13774            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13775                    + "\": protected package");
13776            return false;
13777        }
13778
13779        // Cannot suspend static shared libs as they are considered
13780        // a part of the using app (emulating static linking). Also
13781        // static libs are installed always on internal storage.
13782        PackageParser.Package pkg = mPackages.get(packageName);
13783        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13784            Slog.w(TAG, "Cannot suspend package: " + packageName
13785                    + " providing static shared library: "
13786                    + pkg.staticSharedLibName);
13787            return false;
13788        }
13789
13790        return true;
13791    }
13792
13793    private String getActiveLauncherPackageName(int userId) {
13794        Intent intent = new Intent(Intent.ACTION_MAIN);
13795        intent.addCategory(Intent.CATEGORY_HOME);
13796        ResolveInfo resolveInfo = resolveIntent(
13797                intent,
13798                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13799                PackageManager.MATCH_DEFAULT_ONLY,
13800                userId);
13801
13802        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13803    }
13804
13805    private String getDefaultDialerPackageName(int userId) {
13806        synchronized (mPackages) {
13807            return mSettings.getDefaultDialerPackageNameLPw(userId);
13808        }
13809    }
13810
13811    @Override
13812    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13813        mContext.enforceCallingOrSelfPermission(
13814                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13815                "Only package verification agents can verify applications");
13816
13817        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13818        final PackageVerificationResponse response = new PackageVerificationResponse(
13819                verificationCode, Binder.getCallingUid());
13820        msg.arg1 = id;
13821        msg.obj = response;
13822        mHandler.sendMessage(msg);
13823    }
13824
13825    @Override
13826    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13827            long millisecondsToDelay) {
13828        mContext.enforceCallingOrSelfPermission(
13829                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13830                "Only package verification agents can extend verification timeouts");
13831
13832        final PackageVerificationState state = mPendingVerification.get(id);
13833        final PackageVerificationResponse response = new PackageVerificationResponse(
13834                verificationCodeAtTimeout, Binder.getCallingUid());
13835
13836        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13837            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13838        }
13839        if (millisecondsToDelay < 0) {
13840            millisecondsToDelay = 0;
13841        }
13842        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13843                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13844            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13845        }
13846
13847        if ((state != null) && !state.timeoutExtended()) {
13848            state.extendTimeout();
13849
13850            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13851            msg.arg1 = id;
13852            msg.obj = response;
13853            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13854        }
13855    }
13856
13857    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13858            int verificationCode, UserHandle user) {
13859        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13860        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13861        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13862        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13863        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13864
13865        mContext.sendBroadcastAsUser(intent, user,
13866                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13867    }
13868
13869    private ComponentName matchComponentForVerifier(String packageName,
13870            List<ResolveInfo> receivers) {
13871        ActivityInfo targetReceiver = null;
13872
13873        final int NR = receivers.size();
13874        for (int i = 0; i < NR; i++) {
13875            final ResolveInfo info = receivers.get(i);
13876            if (info.activityInfo == null) {
13877                continue;
13878            }
13879
13880            if (packageName.equals(info.activityInfo.packageName)) {
13881                targetReceiver = info.activityInfo;
13882                break;
13883            }
13884        }
13885
13886        if (targetReceiver == null) {
13887            return null;
13888        }
13889
13890        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13891    }
13892
13893    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13894            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13895        if (pkgInfo.verifiers.length == 0) {
13896            return null;
13897        }
13898
13899        final int N = pkgInfo.verifiers.length;
13900        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13901        for (int i = 0; i < N; i++) {
13902            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13903
13904            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13905                    receivers);
13906            if (comp == null) {
13907                continue;
13908            }
13909
13910            final int verifierUid = getUidForVerifier(verifierInfo);
13911            if (verifierUid == -1) {
13912                continue;
13913            }
13914
13915            if (DEBUG_VERIFY) {
13916                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13917                        + " with the correct signature");
13918            }
13919            sufficientVerifiers.add(comp);
13920            verificationState.addSufficientVerifier(verifierUid);
13921        }
13922
13923        return sufficientVerifiers;
13924    }
13925
13926    private int getUidForVerifier(VerifierInfo verifierInfo) {
13927        synchronized (mPackages) {
13928            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13929            if (pkg == null) {
13930                return -1;
13931            } else if (pkg.mSignatures.length != 1) {
13932                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13933                        + " has more than one signature; ignoring");
13934                return -1;
13935            }
13936
13937            /*
13938             * If the public key of the package's signature does not match
13939             * our expected public key, then this is a different package and
13940             * we should skip.
13941             */
13942
13943            final byte[] expectedPublicKey;
13944            try {
13945                final Signature verifierSig = pkg.mSignatures[0];
13946                final PublicKey publicKey = verifierSig.getPublicKey();
13947                expectedPublicKey = publicKey.getEncoded();
13948            } catch (CertificateException e) {
13949                return -1;
13950            }
13951
13952            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13953
13954            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13955                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13956                        + " does not have the expected public key; ignoring");
13957                return -1;
13958            }
13959
13960            return pkg.applicationInfo.uid;
13961        }
13962    }
13963
13964    @Override
13965    public void finishPackageInstall(int token, boolean didLaunch) {
13966        enforceSystemOrRoot("Only the system is allowed to finish installs");
13967
13968        if (DEBUG_INSTALL) {
13969            Slog.v(TAG, "BM finishing package install for " + token);
13970        }
13971        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13972
13973        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13974        mHandler.sendMessage(msg);
13975    }
13976
13977    /**
13978     * Get the verification agent timeout.
13979     *
13980     * @return verification timeout in milliseconds
13981     */
13982    private long getVerificationTimeout() {
13983        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13984                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13985                DEFAULT_VERIFICATION_TIMEOUT);
13986    }
13987
13988    /**
13989     * Get the default verification agent response code.
13990     *
13991     * @return default verification response code
13992     */
13993    private int getDefaultVerificationResponse() {
13994        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13995                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13996                DEFAULT_VERIFICATION_RESPONSE);
13997    }
13998
13999    /**
14000     * Check whether or not package verification has been enabled.
14001     *
14002     * @return true if verification should be performed
14003     */
14004    private boolean isVerificationEnabled(int userId, int installFlags) {
14005        if (!DEFAULT_VERIFY_ENABLE) {
14006            return false;
14007        }
14008
14009        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14010
14011        // Check if installing from ADB
14012        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14013            // Do not run verification in a test harness environment
14014            if (ActivityManager.isRunningInTestHarness()) {
14015                return false;
14016            }
14017            if (ensureVerifyAppsEnabled) {
14018                return true;
14019            }
14020            // Check if the developer does not want package verification for ADB installs
14021            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14022                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14023                return false;
14024            }
14025        }
14026
14027        if (ensureVerifyAppsEnabled) {
14028            return true;
14029        }
14030
14031        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14032                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14033    }
14034
14035    @Override
14036    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14037            throws RemoteException {
14038        mContext.enforceCallingOrSelfPermission(
14039                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14040                "Only intentfilter verification agents can verify applications");
14041
14042        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14043        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14044                Binder.getCallingUid(), verificationCode, failedDomains);
14045        msg.arg1 = id;
14046        msg.obj = response;
14047        mHandler.sendMessage(msg);
14048    }
14049
14050    @Override
14051    public int getIntentVerificationStatus(String packageName, int userId) {
14052        synchronized (mPackages) {
14053            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14054        }
14055    }
14056
14057    @Override
14058    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14059        mContext.enforceCallingOrSelfPermission(
14060                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14061
14062        boolean result = false;
14063        synchronized (mPackages) {
14064            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14065        }
14066        if (result) {
14067            scheduleWritePackageRestrictionsLocked(userId);
14068        }
14069        return result;
14070    }
14071
14072    @Override
14073    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14074            String packageName) {
14075        synchronized (mPackages) {
14076            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14077        }
14078    }
14079
14080    @Override
14081    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14082        if (TextUtils.isEmpty(packageName)) {
14083            return ParceledListSlice.emptyList();
14084        }
14085        synchronized (mPackages) {
14086            PackageParser.Package pkg = mPackages.get(packageName);
14087            if (pkg == null || pkg.activities == null) {
14088                return ParceledListSlice.emptyList();
14089            }
14090            final int count = pkg.activities.size();
14091            ArrayList<IntentFilter> result = new ArrayList<>();
14092            for (int n=0; n<count; n++) {
14093                PackageParser.Activity activity = pkg.activities.get(n);
14094                if (activity.intents != null && activity.intents.size() > 0) {
14095                    result.addAll(activity.intents);
14096                }
14097            }
14098            return new ParceledListSlice<>(result);
14099        }
14100    }
14101
14102    @Override
14103    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14104        mContext.enforceCallingOrSelfPermission(
14105                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14106
14107        synchronized (mPackages) {
14108            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14109            if (packageName != null) {
14110                result |= updateIntentVerificationStatus(packageName,
14111                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
14112                        userId);
14113                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
14114                        packageName, userId);
14115            }
14116            return result;
14117        }
14118    }
14119
14120    @Override
14121    public String getDefaultBrowserPackageName(int userId) {
14122        synchronized (mPackages) {
14123            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14124        }
14125    }
14126
14127    /**
14128     * Get the "allow unknown sources" setting.
14129     *
14130     * @return the current "allow unknown sources" setting
14131     */
14132    private int getUnknownSourcesSettings() {
14133        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14134                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14135                -1);
14136    }
14137
14138    @Override
14139    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14140        final int uid = Binder.getCallingUid();
14141        // writer
14142        synchronized (mPackages) {
14143            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14144            if (targetPackageSetting == null) {
14145                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14146            }
14147
14148            PackageSetting installerPackageSetting;
14149            if (installerPackageName != null) {
14150                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14151                if (installerPackageSetting == null) {
14152                    throw new IllegalArgumentException("Unknown installer package: "
14153                            + installerPackageName);
14154                }
14155            } else {
14156                installerPackageSetting = null;
14157            }
14158
14159            Signature[] callerSignature;
14160            Object obj = mSettings.getUserIdLPr(uid);
14161            if (obj != null) {
14162                if (obj instanceof SharedUserSetting) {
14163                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14164                } else if (obj instanceof PackageSetting) {
14165                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14166                } else {
14167                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14168                }
14169            } else {
14170                throw new SecurityException("Unknown calling UID: " + uid);
14171            }
14172
14173            // Verify: can't set installerPackageName to a package that is
14174            // not signed with the same cert as the caller.
14175            if (installerPackageSetting != null) {
14176                if (compareSignatures(callerSignature,
14177                        installerPackageSetting.signatures.mSignatures)
14178                        != PackageManager.SIGNATURE_MATCH) {
14179                    throw new SecurityException(
14180                            "Caller does not have same cert as new installer package "
14181                            + installerPackageName);
14182                }
14183            }
14184
14185            // Verify: if target already has an installer package, it must
14186            // be signed with the same cert as the caller.
14187            if (targetPackageSetting.installerPackageName != null) {
14188                PackageSetting setting = mSettings.mPackages.get(
14189                        targetPackageSetting.installerPackageName);
14190                // If the currently set package isn't valid, then it's always
14191                // okay to change it.
14192                if (setting != null) {
14193                    if (compareSignatures(callerSignature,
14194                            setting.signatures.mSignatures)
14195                            != PackageManager.SIGNATURE_MATCH) {
14196                        throw new SecurityException(
14197                                "Caller does not have same cert as old installer package "
14198                                + targetPackageSetting.installerPackageName);
14199                    }
14200                }
14201            }
14202
14203            // Okay!
14204            targetPackageSetting.installerPackageName = installerPackageName;
14205            if (installerPackageName != null) {
14206                mSettings.mInstallerPackages.add(installerPackageName);
14207            }
14208            scheduleWriteSettingsLocked();
14209        }
14210    }
14211
14212    @Override
14213    public void setApplicationCategoryHint(String packageName, int categoryHint,
14214            String callerPackageName) {
14215        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14216                callerPackageName);
14217        synchronized (mPackages) {
14218            PackageSetting ps = mSettings.mPackages.get(packageName);
14219            if (ps == null) {
14220                throw new IllegalArgumentException("Unknown target package " + packageName);
14221            }
14222
14223            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14224                throw new IllegalArgumentException("Calling package " + callerPackageName
14225                        + " is not installer for " + packageName);
14226            }
14227
14228            if (ps.categoryHint != categoryHint) {
14229                ps.categoryHint = categoryHint;
14230                scheduleWriteSettingsLocked();
14231            }
14232        }
14233    }
14234
14235    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14236        // Queue up an async operation since the package installation may take a little while.
14237        mHandler.post(new Runnable() {
14238            public void run() {
14239                mHandler.removeCallbacks(this);
14240                 // Result object to be returned
14241                PackageInstalledInfo res = new PackageInstalledInfo();
14242                res.setReturnCode(currentStatus);
14243                res.uid = -1;
14244                res.pkg = null;
14245                res.removedInfo = null;
14246                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14247                    args.doPreInstall(res.returnCode);
14248                    synchronized (mInstallLock) {
14249                        installPackageTracedLI(args, res);
14250                    }
14251                    args.doPostInstall(res.returnCode, res.uid);
14252                }
14253
14254                // A restore should be performed at this point if (a) the install
14255                // succeeded, (b) the operation is not an update, and (c) the new
14256                // package has not opted out of backup participation.
14257                final boolean update = res.removedInfo != null
14258                        && res.removedInfo.removedPackage != null;
14259                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14260                boolean doRestore = !update
14261                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14262
14263                // Set up the post-install work request bookkeeping.  This will be used
14264                // and cleaned up by the post-install event handling regardless of whether
14265                // there's a restore pass performed.  Token values are >= 1.
14266                int token;
14267                if (mNextInstallToken < 0) mNextInstallToken = 1;
14268                token = mNextInstallToken++;
14269
14270                PostInstallData data = new PostInstallData(args, res);
14271                mRunningInstalls.put(token, data);
14272                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14273
14274                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14275                    // Pass responsibility to the Backup Manager.  It will perform a
14276                    // restore if appropriate, then pass responsibility back to the
14277                    // Package Manager to run the post-install observer callbacks
14278                    // and broadcasts.
14279                    IBackupManager bm = IBackupManager.Stub.asInterface(
14280                            ServiceManager.getService(Context.BACKUP_SERVICE));
14281                    if (bm != null) {
14282                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14283                                + " to BM for possible restore");
14284                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14285                        try {
14286                            // TODO: http://b/22388012
14287                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14288                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14289                            } else {
14290                                doRestore = false;
14291                            }
14292                        } catch (RemoteException e) {
14293                            // can't happen; the backup manager is local
14294                        } catch (Exception e) {
14295                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14296                            doRestore = false;
14297                        }
14298                    } else {
14299                        Slog.e(TAG, "Backup Manager not found!");
14300                        doRestore = false;
14301                    }
14302                }
14303
14304                if (!doRestore) {
14305                    // No restore possible, or the Backup Manager was mysteriously not
14306                    // available -- just fire the post-install work request directly.
14307                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14308
14309                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14310
14311                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14312                    mHandler.sendMessage(msg);
14313                }
14314            }
14315        });
14316    }
14317
14318    /**
14319     * Callback from PackageSettings whenever an app is first transitioned out of the
14320     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14321     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14322     * here whether the app is the target of an ongoing install, and only send the
14323     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14324     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14325     * handling.
14326     */
14327    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14328        // Serialize this with the rest of the install-process message chain.  In the
14329        // restore-at-install case, this Runnable will necessarily run before the
14330        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14331        // are coherent.  In the non-restore case, the app has already completed install
14332        // and been launched through some other means, so it is not in a problematic
14333        // state for observers to see the FIRST_LAUNCH signal.
14334        mHandler.post(new Runnable() {
14335            @Override
14336            public void run() {
14337                for (int i = 0; i < mRunningInstalls.size(); i++) {
14338                    final PostInstallData data = mRunningInstalls.valueAt(i);
14339                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14340                        continue;
14341                    }
14342                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14343                        // right package; but is it for the right user?
14344                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14345                            if (userId == data.res.newUsers[uIndex]) {
14346                                if (DEBUG_BACKUP) {
14347                                    Slog.i(TAG, "Package " + pkgName
14348                                            + " being restored so deferring FIRST_LAUNCH");
14349                                }
14350                                return;
14351                            }
14352                        }
14353                    }
14354                }
14355                // didn't find it, so not being restored
14356                if (DEBUG_BACKUP) {
14357                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14358                }
14359                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14360            }
14361        });
14362    }
14363
14364    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14365        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14366                installerPkg, null, userIds);
14367    }
14368
14369    private abstract class HandlerParams {
14370        private static final int MAX_RETRIES = 4;
14371
14372        /**
14373         * Number of times startCopy() has been attempted and had a non-fatal
14374         * error.
14375         */
14376        private int mRetries = 0;
14377
14378        /** User handle for the user requesting the information or installation. */
14379        private final UserHandle mUser;
14380        String traceMethod;
14381        int traceCookie;
14382
14383        HandlerParams(UserHandle user) {
14384            mUser = user;
14385        }
14386
14387        UserHandle getUser() {
14388            return mUser;
14389        }
14390
14391        HandlerParams setTraceMethod(String traceMethod) {
14392            this.traceMethod = traceMethod;
14393            return this;
14394        }
14395
14396        HandlerParams setTraceCookie(int traceCookie) {
14397            this.traceCookie = traceCookie;
14398            return this;
14399        }
14400
14401        final boolean startCopy() {
14402            boolean res;
14403            try {
14404                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14405
14406                if (++mRetries > MAX_RETRIES) {
14407                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14408                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14409                    handleServiceError();
14410                    return false;
14411                } else {
14412                    handleStartCopy();
14413                    res = true;
14414                }
14415            } catch (RemoteException e) {
14416                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14417                mHandler.sendEmptyMessage(MCS_RECONNECT);
14418                res = false;
14419            }
14420            handleReturnCode();
14421            return res;
14422        }
14423
14424        final void serviceError() {
14425            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14426            handleServiceError();
14427            handleReturnCode();
14428        }
14429
14430        abstract void handleStartCopy() throws RemoteException;
14431        abstract void handleServiceError();
14432        abstract void handleReturnCode();
14433    }
14434
14435    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14436        for (File path : paths) {
14437            try {
14438                mcs.clearDirectory(path.getAbsolutePath());
14439            } catch (RemoteException e) {
14440            }
14441        }
14442    }
14443
14444    static class OriginInfo {
14445        /**
14446         * Location where install is coming from, before it has been
14447         * copied/renamed into place. This could be a single monolithic APK
14448         * file, or a cluster directory. This location may be untrusted.
14449         */
14450        final File file;
14451        final String cid;
14452
14453        /**
14454         * Flag indicating that {@link #file} or {@link #cid} has already been
14455         * staged, meaning downstream users don't need to defensively copy the
14456         * contents.
14457         */
14458        final boolean staged;
14459
14460        /**
14461         * Flag indicating that {@link #file} or {@link #cid} is an already
14462         * installed app that is being moved.
14463         */
14464        final boolean existing;
14465
14466        final String resolvedPath;
14467        final File resolvedFile;
14468
14469        static OriginInfo fromNothing() {
14470            return new OriginInfo(null, null, false, false);
14471        }
14472
14473        static OriginInfo fromUntrustedFile(File file) {
14474            return new OriginInfo(file, null, false, false);
14475        }
14476
14477        static OriginInfo fromExistingFile(File file) {
14478            return new OriginInfo(file, null, false, true);
14479        }
14480
14481        static OriginInfo fromStagedFile(File file) {
14482            return new OriginInfo(file, null, true, false);
14483        }
14484
14485        static OriginInfo fromStagedContainer(String cid) {
14486            return new OriginInfo(null, cid, true, false);
14487        }
14488
14489        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14490            this.file = file;
14491            this.cid = cid;
14492            this.staged = staged;
14493            this.existing = existing;
14494
14495            if (cid != null) {
14496                resolvedPath = PackageHelper.getSdDir(cid);
14497                resolvedFile = new File(resolvedPath);
14498            } else if (file != null) {
14499                resolvedPath = file.getAbsolutePath();
14500                resolvedFile = file;
14501            } else {
14502                resolvedPath = null;
14503                resolvedFile = null;
14504            }
14505        }
14506    }
14507
14508    static class MoveInfo {
14509        final int moveId;
14510        final String fromUuid;
14511        final String toUuid;
14512        final String packageName;
14513        final String dataAppName;
14514        final int appId;
14515        final String seinfo;
14516        final int targetSdkVersion;
14517
14518        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14519                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14520            this.moveId = moveId;
14521            this.fromUuid = fromUuid;
14522            this.toUuid = toUuid;
14523            this.packageName = packageName;
14524            this.dataAppName = dataAppName;
14525            this.appId = appId;
14526            this.seinfo = seinfo;
14527            this.targetSdkVersion = targetSdkVersion;
14528        }
14529    }
14530
14531    static class VerificationInfo {
14532        /** A constant used to indicate that a uid value is not present. */
14533        public static final int NO_UID = -1;
14534
14535        /** URI referencing where the package was downloaded from. */
14536        final Uri originatingUri;
14537
14538        /** HTTP referrer URI associated with the originatingURI. */
14539        final Uri referrer;
14540
14541        /** UID of the application that the install request originated from. */
14542        final int originatingUid;
14543
14544        /** UID of application requesting the install */
14545        final int installerUid;
14546
14547        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14548            this.originatingUri = originatingUri;
14549            this.referrer = referrer;
14550            this.originatingUid = originatingUid;
14551            this.installerUid = installerUid;
14552        }
14553    }
14554
14555    class InstallParams extends HandlerParams {
14556        final OriginInfo origin;
14557        final MoveInfo move;
14558        final IPackageInstallObserver2 observer;
14559        int installFlags;
14560        final String installerPackageName;
14561        final String volumeUuid;
14562        private InstallArgs mArgs;
14563        private int mRet;
14564        final String packageAbiOverride;
14565        final String[] grantedRuntimePermissions;
14566        final VerificationInfo verificationInfo;
14567        final Certificate[][] certificates;
14568        final int installReason;
14569
14570        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14571                int installFlags, String installerPackageName, String volumeUuid,
14572                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14573                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14574            super(user);
14575            this.origin = origin;
14576            this.move = move;
14577            this.observer = observer;
14578            this.installFlags = installFlags;
14579            this.installerPackageName = installerPackageName;
14580            this.volumeUuid = volumeUuid;
14581            this.verificationInfo = verificationInfo;
14582            this.packageAbiOverride = packageAbiOverride;
14583            this.grantedRuntimePermissions = grantedPermissions;
14584            this.certificates = certificates;
14585            this.installReason = installReason;
14586        }
14587
14588        @Override
14589        public String toString() {
14590            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14591                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14592        }
14593
14594        private int installLocationPolicy(PackageInfoLite pkgLite) {
14595            String packageName = pkgLite.packageName;
14596            int installLocation = pkgLite.installLocation;
14597            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14598            // reader
14599            synchronized (mPackages) {
14600                // Currently installed package which the new package is attempting to replace or
14601                // null if no such package is installed.
14602                PackageParser.Package installedPkg = mPackages.get(packageName);
14603                // Package which currently owns the data which the new package will own if installed.
14604                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14605                // will be null whereas dataOwnerPkg will contain information about the package
14606                // which was uninstalled while keeping its data.
14607                PackageParser.Package dataOwnerPkg = installedPkg;
14608                if (dataOwnerPkg  == null) {
14609                    PackageSetting ps = mSettings.mPackages.get(packageName);
14610                    if (ps != null) {
14611                        dataOwnerPkg = ps.pkg;
14612                    }
14613                }
14614
14615                if (dataOwnerPkg != null) {
14616                    // If installed, the package will get access to data left on the device by its
14617                    // predecessor. As a security measure, this is permited only if this is not a
14618                    // version downgrade or if the predecessor package is marked as debuggable and
14619                    // a downgrade is explicitly requested.
14620                    //
14621                    // On debuggable platform builds, downgrades are permitted even for
14622                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14623                    // not offer security guarantees and thus it's OK to disable some security
14624                    // mechanisms to make debugging/testing easier on those builds. However, even on
14625                    // debuggable builds downgrades of packages are permitted only if requested via
14626                    // installFlags. This is because we aim to keep the behavior of debuggable
14627                    // platform builds as close as possible to the behavior of non-debuggable
14628                    // platform builds.
14629                    final boolean downgradeRequested =
14630                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14631                    final boolean packageDebuggable =
14632                                (dataOwnerPkg.applicationInfo.flags
14633                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14634                    final boolean downgradePermitted =
14635                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14636                    if (!downgradePermitted) {
14637                        try {
14638                            checkDowngrade(dataOwnerPkg, pkgLite);
14639                        } catch (PackageManagerException e) {
14640                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14641                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14642                        }
14643                    }
14644                }
14645
14646                if (installedPkg != null) {
14647                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14648                        // Check for updated system application.
14649                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14650                            if (onSd) {
14651                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14652                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14653                            }
14654                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14655                        } else {
14656                            if (onSd) {
14657                                // Install flag overrides everything.
14658                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14659                            }
14660                            // If current upgrade specifies particular preference
14661                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14662                                // Application explicitly specified internal.
14663                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14664                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14665                                // App explictly prefers external. Let policy decide
14666                            } else {
14667                                // Prefer previous location
14668                                if (isExternal(installedPkg)) {
14669                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14670                                }
14671                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14672                            }
14673                        }
14674                    } else {
14675                        // Invalid install. Return error code
14676                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14677                    }
14678                }
14679            }
14680            // All the special cases have been taken care of.
14681            // Return result based on recommended install location.
14682            if (onSd) {
14683                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14684            }
14685            return pkgLite.recommendedInstallLocation;
14686        }
14687
14688        /*
14689         * Invoke remote method to get package information and install
14690         * location values. Override install location based on default
14691         * policy if needed and then create install arguments based
14692         * on the install location.
14693         */
14694        public void handleStartCopy() throws RemoteException {
14695            int ret = PackageManager.INSTALL_SUCCEEDED;
14696
14697            // If we're already staged, we've firmly committed to an install location
14698            if (origin.staged) {
14699                if (origin.file != null) {
14700                    installFlags |= PackageManager.INSTALL_INTERNAL;
14701                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14702                } else if (origin.cid != null) {
14703                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14704                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14705                } else {
14706                    throw new IllegalStateException("Invalid stage location");
14707                }
14708            }
14709
14710            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14711            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14712            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14713            PackageInfoLite pkgLite = null;
14714
14715            if (onInt && onSd) {
14716                // Check if both bits are set.
14717                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14718                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14719            } else if (onSd && ephemeral) {
14720                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14721                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14722            } else {
14723                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14724                        packageAbiOverride);
14725
14726                if (DEBUG_EPHEMERAL && ephemeral) {
14727                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14728                }
14729
14730                /*
14731                 * If we have too little free space, try to free cache
14732                 * before giving up.
14733                 */
14734                if (!origin.staged && pkgLite.recommendedInstallLocation
14735                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14736                    // TODO: focus freeing disk space on the target device
14737                    final StorageManager storage = StorageManager.from(mContext);
14738                    final long lowThreshold = storage.getStorageLowBytes(
14739                            Environment.getDataDirectory());
14740
14741                    final long sizeBytes = mContainerService.calculateInstalledSize(
14742                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14743
14744                    try {
14745                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14746                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14747                                installFlags, packageAbiOverride);
14748                    } catch (InstallerException e) {
14749                        Slog.w(TAG, "Failed to free cache", e);
14750                    }
14751
14752                    /*
14753                     * The cache free must have deleted the file we
14754                     * downloaded to install.
14755                     *
14756                     * TODO: fix the "freeCache" call to not delete
14757                     *       the file we care about.
14758                     */
14759                    if (pkgLite.recommendedInstallLocation
14760                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14761                        pkgLite.recommendedInstallLocation
14762                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14763                    }
14764                }
14765            }
14766
14767            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14768                int loc = pkgLite.recommendedInstallLocation;
14769                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14770                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14771                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14772                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14773                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14774                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14775                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14776                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14777                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14778                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14779                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14780                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14781                } else {
14782                    // Override with defaults if needed.
14783                    loc = installLocationPolicy(pkgLite);
14784                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14785                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14786                    } else if (!onSd && !onInt) {
14787                        // Override install location with flags
14788                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14789                            // Set the flag to install on external media.
14790                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14791                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14792                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14793                            if (DEBUG_EPHEMERAL) {
14794                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14795                            }
14796                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14797                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14798                                    |PackageManager.INSTALL_INTERNAL);
14799                        } else {
14800                            // Make sure the flag for installing on external
14801                            // media is unset
14802                            installFlags |= PackageManager.INSTALL_INTERNAL;
14803                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14804                        }
14805                    }
14806                }
14807            }
14808
14809            final InstallArgs args = createInstallArgs(this);
14810            mArgs = args;
14811
14812            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14813                // TODO: http://b/22976637
14814                // Apps installed for "all" users use the device owner to verify the app
14815                UserHandle verifierUser = getUser();
14816                if (verifierUser == UserHandle.ALL) {
14817                    verifierUser = UserHandle.SYSTEM;
14818                }
14819
14820                /*
14821                 * Determine if we have any installed package verifiers. If we
14822                 * do, then we'll defer to them to verify the packages.
14823                 */
14824                final int requiredUid = mRequiredVerifierPackage == null ? -1
14825                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14826                                verifierUser.getIdentifier());
14827                if (!origin.existing && requiredUid != -1
14828                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14829                    final Intent verification = new Intent(
14830                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14831                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14832                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14833                            PACKAGE_MIME_TYPE);
14834                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14835
14836                    // Query all live verifiers based on current user state
14837                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14838                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14839
14840                    if (DEBUG_VERIFY) {
14841                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14842                                + verification.toString() + " with " + pkgLite.verifiers.length
14843                                + " optional verifiers");
14844                    }
14845
14846                    final int verificationId = mPendingVerificationToken++;
14847
14848                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14849
14850                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14851                            installerPackageName);
14852
14853                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14854                            installFlags);
14855
14856                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14857                            pkgLite.packageName);
14858
14859                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14860                            pkgLite.versionCode);
14861
14862                    if (verificationInfo != null) {
14863                        if (verificationInfo.originatingUri != null) {
14864                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14865                                    verificationInfo.originatingUri);
14866                        }
14867                        if (verificationInfo.referrer != null) {
14868                            verification.putExtra(Intent.EXTRA_REFERRER,
14869                                    verificationInfo.referrer);
14870                        }
14871                        if (verificationInfo.originatingUid >= 0) {
14872                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14873                                    verificationInfo.originatingUid);
14874                        }
14875                        if (verificationInfo.installerUid >= 0) {
14876                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14877                                    verificationInfo.installerUid);
14878                        }
14879                    }
14880
14881                    final PackageVerificationState verificationState = new PackageVerificationState(
14882                            requiredUid, args);
14883
14884                    mPendingVerification.append(verificationId, verificationState);
14885
14886                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14887                            receivers, verificationState);
14888
14889                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14890                    final long idleDuration = getVerificationTimeout();
14891
14892                    /*
14893                     * If any sufficient verifiers were listed in the package
14894                     * manifest, attempt to ask them.
14895                     */
14896                    if (sufficientVerifiers != null) {
14897                        final int N = sufficientVerifiers.size();
14898                        if (N == 0) {
14899                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14900                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14901                        } else {
14902                            for (int i = 0; i < N; i++) {
14903                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14904                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14905                                        verifierComponent.getPackageName(), idleDuration,
14906                                        verifierUser.getIdentifier(), false, "package verifier");
14907
14908                                final Intent sufficientIntent = new Intent(verification);
14909                                sufficientIntent.setComponent(verifierComponent);
14910                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14911                            }
14912                        }
14913                    }
14914
14915                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14916                            mRequiredVerifierPackage, receivers);
14917                    if (ret == PackageManager.INSTALL_SUCCEEDED
14918                            && mRequiredVerifierPackage != null) {
14919                        Trace.asyncTraceBegin(
14920                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14921                        /*
14922                         * Send the intent to the required verification agent,
14923                         * but only start the verification timeout after the
14924                         * target BroadcastReceivers have run.
14925                         */
14926                        verification.setComponent(requiredVerifierComponent);
14927                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14928                                mRequiredVerifierPackage, idleDuration,
14929                                verifierUser.getIdentifier(), false, "package verifier");
14930                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14931                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14932                                new BroadcastReceiver() {
14933                                    @Override
14934                                    public void onReceive(Context context, Intent intent) {
14935                                        final Message msg = mHandler
14936                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14937                                        msg.arg1 = verificationId;
14938                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14939                                    }
14940                                }, null, 0, null, null);
14941
14942                        /*
14943                         * We don't want the copy to proceed until verification
14944                         * succeeds, so null out this field.
14945                         */
14946                        mArgs = null;
14947                    }
14948                } else {
14949                    /*
14950                     * No package verification is enabled, so immediately start
14951                     * the remote call to initiate copy using temporary file.
14952                     */
14953                    ret = args.copyApk(mContainerService, true);
14954                }
14955            }
14956
14957            mRet = ret;
14958        }
14959
14960        @Override
14961        void handleReturnCode() {
14962            // If mArgs is null, then MCS couldn't be reached. When it
14963            // reconnects, it will try again to install. At that point, this
14964            // will succeed.
14965            if (mArgs != null) {
14966                processPendingInstall(mArgs, mRet);
14967            }
14968        }
14969
14970        @Override
14971        void handleServiceError() {
14972            mArgs = createInstallArgs(this);
14973            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14974        }
14975
14976        public boolean isForwardLocked() {
14977            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14978        }
14979    }
14980
14981    /**
14982     * Used during creation of InstallArgs
14983     *
14984     * @param installFlags package installation flags
14985     * @return true if should be installed on external storage
14986     */
14987    private static boolean installOnExternalAsec(int installFlags) {
14988        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14989            return false;
14990        }
14991        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14992            return true;
14993        }
14994        return false;
14995    }
14996
14997    /**
14998     * Used during creation of InstallArgs
14999     *
15000     * @param installFlags package installation flags
15001     * @return true if should be installed as forward locked
15002     */
15003    private static boolean installForwardLocked(int installFlags) {
15004        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15005    }
15006
15007    private InstallArgs createInstallArgs(InstallParams params) {
15008        if (params.move != null) {
15009            return new MoveInstallArgs(params);
15010        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15011            return new AsecInstallArgs(params);
15012        } else {
15013            return new FileInstallArgs(params);
15014        }
15015    }
15016
15017    /**
15018     * Create args that describe an existing installed package. Typically used
15019     * when cleaning up old installs, or used as a move source.
15020     */
15021    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15022            String resourcePath, String[] instructionSets) {
15023        final boolean isInAsec;
15024        if (installOnExternalAsec(installFlags)) {
15025            /* Apps on SD card are always in ASEC containers. */
15026            isInAsec = true;
15027        } else if (installForwardLocked(installFlags)
15028                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15029            /*
15030             * Forward-locked apps are only in ASEC containers if they're the
15031             * new style
15032             */
15033            isInAsec = true;
15034        } else {
15035            isInAsec = false;
15036        }
15037
15038        if (isInAsec) {
15039            return new AsecInstallArgs(codePath, instructionSets,
15040                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15041        } else {
15042            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15043        }
15044    }
15045
15046    static abstract class InstallArgs {
15047        /** @see InstallParams#origin */
15048        final OriginInfo origin;
15049        /** @see InstallParams#move */
15050        final MoveInfo move;
15051
15052        final IPackageInstallObserver2 observer;
15053        // Always refers to PackageManager flags only
15054        final int installFlags;
15055        final String installerPackageName;
15056        final String volumeUuid;
15057        final UserHandle user;
15058        final String abiOverride;
15059        final String[] installGrantPermissions;
15060        /** If non-null, drop an async trace when the install completes */
15061        final String traceMethod;
15062        final int traceCookie;
15063        final Certificate[][] certificates;
15064        final int installReason;
15065
15066        // The list of instruction sets supported by this app. This is currently
15067        // only used during the rmdex() phase to clean up resources. We can get rid of this
15068        // if we move dex files under the common app path.
15069        /* nullable */ String[] instructionSets;
15070
15071        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15072                int installFlags, String installerPackageName, String volumeUuid,
15073                UserHandle user, String[] instructionSets,
15074                String abiOverride, String[] installGrantPermissions,
15075                String traceMethod, int traceCookie, Certificate[][] certificates,
15076                int installReason) {
15077            this.origin = origin;
15078            this.move = move;
15079            this.installFlags = installFlags;
15080            this.observer = observer;
15081            this.installerPackageName = installerPackageName;
15082            this.volumeUuid = volumeUuid;
15083            this.user = user;
15084            this.instructionSets = instructionSets;
15085            this.abiOverride = abiOverride;
15086            this.installGrantPermissions = installGrantPermissions;
15087            this.traceMethod = traceMethod;
15088            this.traceCookie = traceCookie;
15089            this.certificates = certificates;
15090            this.installReason = installReason;
15091        }
15092
15093        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15094        abstract int doPreInstall(int status);
15095
15096        /**
15097         * Rename package into final resting place. All paths on the given
15098         * scanned package should be updated to reflect the rename.
15099         */
15100        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15101        abstract int doPostInstall(int status, int uid);
15102
15103        /** @see PackageSettingBase#codePathString */
15104        abstract String getCodePath();
15105        /** @see PackageSettingBase#resourcePathString */
15106        abstract String getResourcePath();
15107
15108        // Need installer lock especially for dex file removal.
15109        abstract void cleanUpResourcesLI();
15110        abstract boolean doPostDeleteLI(boolean delete);
15111
15112        /**
15113         * Called before the source arguments are copied. This is used mostly
15114         * for MoveParams when it needs to read the source file to put it in the
15115         * destination.
15116         */
15117        int doPreCopy() {
15118            return PackageManager.INSTALL_SUCCEEDED;
15119        }
15120
15121        /**
15122         * Called after the source arguments are copied. This is used mostly for
15123         * MoveParams when it needs to read the source file to put it in the
15124         * destination.
15125         */
15126        int doPostCopy(int uid) {
15127            return PackageManager.INSTALL_SUCCEEDED;
15128        }
15129
15130        protected boolean isFwdLocked() {
15131            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15132        }
15133
15134        protected boolean isExternalAsec() {
15135            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15136        }
15137
15138        protected boolean isEphemeral() {
15139            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15140        }
15141
15142        UserHandle getUser() {
15143            return user;
15144        }
15145    }
15146
15147    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15148        if (!allCodePaths.isEmpty()) {
15149            if (instructionSets == null) {
15150                throw new IllegalStateException("instructionSet == null");
15151            }
15152            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15153            for (String codePath : allCodePaths) {
15154                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15155                    try {
15156                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15157                    } catch (InstallerException ignored) {
15158                    }
15159                }
15160            }
15161        }
15162    }
15163
15164    /**
15165     * Logic to handle installation of non-ASEC applications, including copying
15166     * and renaming logic.
15167     */
15168    class FileInstallArgs extends InstallArgs {
15169        private File codeFile;
15170        private File resourceFile;
15171
15172        // Example topology:
15173        // /data/app/com.example/base.apk
15174        // /data/app/com.example/split_foo.apk
15175        // /data/app/com.example/lib/arm/libfoo.so
15176        // /data/app/com.example/lib/arm64/libfoo.so
15177        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15178
15179        /** New install */
15180        FileInstallArgs(InstallParams params) {
15181            super(params.origin, params.move, params.observer, params.installFlags,
15182                    params.installerPackageName, params.volumeUuid,
15183                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15184                    params.grantedRuntimePermissions,
15185                    params.traceMethod, params.traceCookie, params.certificates,
15186                    params.installReason);
15187            if (isFwdLocked()) {
15188                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15189            }
15190        }
15191
15192        /** Existing install */
15193        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15194            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15195                    null, null, null, 0, null /*certificates*/,
15196                    PackageManager.INSTALL_REASON_UNKNOWN);
15197            this.codeFile = (codePath != null) ? new File(codePath) : null;
15198            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15199        }
15200
15201        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15202            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15203            try {
15204                return doCopyApk(imcs, temp);
15205            } finally {
15206                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15207            }
15208        }
15209
15210        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15211            if (origin.staged) {
15212                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15213                codeFile = origin.file;
15214                resourceFile = origin.file;
15215                return PackageManager.INSTALL_SUCCEEDED;
15216            }
15217
15218            try {
15219                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15220                final File tempDir =
15221                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15222                codeFile = tempDir;
15223                resourceFile = tempDir;
15224            } catch (IOException e) {
15225                Slog.w(TAG, "Failed to create copy file: " + e);
15226                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15227            }
15228
15229            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15230                @Override
15231                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15232                    if (!FileUtils.isValidExtFilename(name)) {
15233                        throw new IllegalArgumentException("Invalid filename: " + name);
15234                    }
15235                    try {
15236                        final File file = new File(codeFile, name);
15237                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15238                                O_RDWR | O_CREAT, 0644);
15239                        Os.chmod(file.getAbsolutePath(), 0644);
15240                        return new ParcelFileDescriptor(fd);
15241                    } catch (ErrnoException e) {
15242                        throw new RemoteException("Failed to open: " + e.getMessage());
15243                    }
15244                }
15245            };
15246
15247            int ret = PackageManager.INSTALL_SUCCEEDED;
15248            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15249            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15250                Slog.e(TAG, "Failed to copy package");
15251                return ret;
15252            }
15253
15254            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15255            NativeLibraryHelper.Handle handle = null;
15256            try {
15257                handle = NativeLibraryHelper.Handle.create(codeFile);
15258                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15259                        abiOverride);
15260            } catch (IOException e) {
15261                Slog.e(TAG, "Copying native libraries failed", e);
15262                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15263            } finally {
15264                IoUtils.closeQuietly(handle);
15265            }
15266
15267            return ret;
15268        }
15269
15270        int doPreInstall(int status) {
15271            if (status != PackageManager.INSTALL_SUCCEEDED) {
15272                cleanUp();
15273            }
15274            return status;
15275        }
15276
15277        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15278            if (status != PackageManager.INSTALL_SUCCEEDED) {
15279                cleanUp();
15280                return false;
15281            }
15282
15283            final File targetDir = codeFile.getParentFile();
15284            final File beforeCodeFile = codeFile;
15285            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15286
15287            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15288            try {
15289                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15290            } catch (ErrnoException e) {
15291                Slog.w(TAG, "Failed to rename", e);
15292                return false;
15293            }
15294
15295            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15296                Slog.w(TAG, "Failed to restorecon");
15297                return false;
15298            }
15299
15300            // Reflect the rename internally
15301            codeFile = afterCodeFile;
15302            resourceFile = afterCodeFile;
15303
15304            // Reflect the rename in scanned details
15305            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15306            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15307                    afterCodeFile, pkg.baseCodePath));
15308            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15309                    afterCodeFile, pkg.splitCodePaths));
15310
15311            // Reflect the rename in app info
15312            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15313            pkg.setApplicationInfoCodePath(pkg.codePath);
15314            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15315            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15316            pkg.setApplicationInfoResourcePath(pkg.codePath);
15317            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15318            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15319
15320            return true;
15321        }
15322
15323        int doPostInstall(int status, int uid) {
15324            if (status != PackageManager.INSTALL_SUCCEEDED) {
15325                cleanUp();
15326            }
15327            return status;
15328        }
15329
15330        @Override
15331        String getCodePath() {
15332            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15333        }
15334
15335        @Override
15336        String getResourcePath() {
15337            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15338        }
15339
15340        private boolean cleanUp() {
15341            if (codeFile == null || !codeFile.exists()) {
15342                return false;
15343            }
15344
15345            removeCodePathLI(codeFile);
15346
15347            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15348                resourceFile.delete();
15349            }
15350
15351            return true;
15352        }
15353
15354        void cleanUpResourcesLI() {
15355            // Try enumerating all code paths before deleting
15356            List<String> allCodePaths = Collections.EMPTY_LIST;
15357            if (codeFile != null && codeFile.exists()) {
15358                try {
15359                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15360                    allCodePaths = pkg.getAllCodePaths();
15361                } catch (PackageParserException e) {
15362                    // Ignored; we tried our best
15363                }
15364            }
15365
15366            cleanUp();
15367            removeDexFiles(allCodePaths, instructionSets);
15368        }
15369
15370        boolean doPostDeleteLI(boolean delete) {
15371            // XXX err, shouldn't we respect the delete flag?
15372            cleanUpResourcesLI();
15373            return true;
15374        }
15375    }
15376
15377    private boolean isAsecExternal(String cid) {
15378        final String asecPath = PackageHelper.getSdFilesystem(cid);
15379        return !asecPath.startsWith(mAsecInternalPath);
15380    }
15381
15382    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15383            PackageManagerException {
15384        if (copyRet < 0) {
15385            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15386                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15387                throw new PackageManagerException(copyRet, message);
15388            }
15389        }
15390    }
15391
15392    /**
15393     * Extract the StorageManagerService "container ID" from the full code path of an
15394     * .apk.
15395     */
15396    static String cidFromCodePath(String fullCodePath) {
15397        int eidx = fullCodePath.lastIndexOf("/");
15398        String subStr1 = fullCodePath.substring(0, eidx);
15399        int sidx = subStr1.lastIndexOf("/");
15400        return subStr1.substring(sidx+1, eidx);
15401    }
15402
15403    /**
15404     * Logic to handle installation of ASEC applications, including copying and
15405     * renaming logic.
15406     */
15407    class AsecInstallArgs extends InstallArgs {
15408        static final String RES_FILE_NAME = "pkg.apk";
15409        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15410
15411        String cid;
15412        String packagePath;
15413        String resourcePath;
15414
15415        /** New install */
15416        AsecInstallArgs(InstallParams params) {
15417            super(params.origin, params.move, params.observer, params.installFlags,
15418                    params.installerPackageName, params.volumeUuid,
15419                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15420                    params.grantedRuntimePermissions,
15421                    params.traceMethod, params.traceCookie, params.certificates,
15422                    params.installReason);
15423        }
15424
15425        /** Existing install */
15426        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15427                        boolean isExternal, boolean isForwardLocked) {
15428            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15429                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15430                    instructionSets, null, null, null, 0, null /*certificates*/,
15431                    PackageManager.INSTALL_REASON_UNKNOWN);
15432            // Hackily pretend we're still looking at a full code path
15433            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15434                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15435            }
15436
15437            // Extract cid from fullCodePath
15438            int eidx = fullCodePath.lastIndexOf("/");
15439            String subStr1 = fullCodePath.substring(0, eidx);
15440            int sidx = subStr1.lastIndexOf("/");
15441            cid = subStr1.substring(sidx+1, eidx);
15442            setMountPath(subStr1);
15443        }
15444
15445        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15446            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15447                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15448                    instructionSets, null, null, null, 0, null /*certificates*/,
15449                    PackageManager.INSTALL_REASON_UNKNOWN);
15450            this.cid = cid;
15451            setMountPath(PackageHelper.getSdDir(cid));
15452        }
15453
15454        void createCopyFile() {
15455            cid = mInstallerService.allocateExternalStageCidLegacy();
15456        }
15457
15458        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15459            if (origin.staged && origin.cid != null) {
15460                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15461                cid = origin.cid;
15462                setMountPath(PackageHelper.getSdDir(cid));
15463                return PackageManager.INSTALL_SUCCEEDED;
15464            }
15465
15466            if (temp) {
15467                createCopyFile();
15468            } else {
15469                /*
15470                 * Pre-emptively destroy the container since it's destroyed if
15471                 * copying fails due to it existing anyway.
15472                 */
15473                PackageHelper.destroySdDir(cid);
15474            }
15475
15476            final String newMountPath = imcs.copyPackageToContainer(
15477                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15478                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15479
15480            if (newMountPath != null) {
15481                setMountPath(newMountPath);
15482                return PackageManager.INSTALL_SUCCEEDED;
15483            } else {
15484                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15485            }
15486        }
15487
15488        @Override
15489        String getCodePath() {
15490            return packagePath;
15491        }
15492
15493        @Override
15494        String getResourcePath() {
15495            return resourcePath;
15496        }
15497
15498        int doPreInstall(int status) {
15499            if (status != PackageManager.INSTALL_SUCCEEDED) {
15500                // Destroy container
15501                PackageHelper.destroySdDir(cid);
15502            } else {
15503                boolean mounted = PackageHelper.isContainerMounted(cid);
15504                if (!mounted) {
15505                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15506                            Process.SYSTEM_UID);
15507                    if (newMountPath != null) {
15508                        setMountPath(newMountPath);
15509                    } else {
15510                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15511                    }
15512                }
15513            }
15514            return status;
15515        }
15516
15517        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15518            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15519            String newMountPath = null;
15520            if (PackageHelper.isContainerMounted(cid)) {
15521                // Unmount the container
15522                if (!PackageHelper.unMountSdDir(cid)) {
15523                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15524                    return false;
15525                }
15526            }
15527            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15528                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15529                        " which might be stale. Will try to clean up.");
15530                // Clean up the stale container and proceed to recreate.
15531                if (!PackageHelper.destroySdDir(newCacheId)) {
15532                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15533                    return false;
15534                }
15535                // Successfully cleaned up stale container. Try to rename again.
15536                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15537                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15538                            + " inspite of cleaning it up.");
15539                    return false;
15540                }
15541            }
15542            if (!PackageHelper.isContainerMounted(newCacheId)) {
15543                Slog.w(TAG, "Mounting container " + newCacheId);
15544                newMountPath = PackageHelper.mountSdDir(newCacheId,
15545                        getEncryptKey(), Process.SYSTEM_UID);
15546            } else {
15547                newMountPath = PackageHelper.getSdDir(newCacheId);
15548            }
15549            if (newMountPath == null) {
15550                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15551                return false;
15552            }
15553            Log.i(TAG, "Succesfully renamed " + cid +
15554                    " to " + newCacheId +
15555                    " at new path: " + newMountPath);
15556            cid = newCacheId;
15557
15558            final File beforeCodeFile = new File(packagePath);
15559            setMountPath(newMountPath);
15560            final File afterCodeFile = new File(packagePath);
15561
15562            // Reflect the rename in scanned details
15563            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15564            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15565                    afterCodeFile, pkg.baseCodePath));
15566            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15567                    afterCodeFile, pkg.splitCodePaths));
15568
15569            // Reflect the rename in app info
15570            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15571            pkg.setApplicationInfoCodePath(pkg.codePath);
15572            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15573            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15574            pkg.setApplicationInfoResourcePath(pkg.codePath);
15575            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15576            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15577
15578            return true;
15579        }
15580
15581        private void setMountPath(String mountPath) {
15582            final File mountFile = new File(mountPath);
15583
15584            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15585            if (monolithicFile.exists()) {
15586                packagePath = monolithicFile.getAbsolutePath();
15587                if (isFwdLocked()) {
15588                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15589                } else {
15590                    resourcePath = packagePath;
15591                }
15592            } else {
15593                packagePath = mountFile.getAbsolutePath();
15594                resourcePath = packagePath;
15595            }
15596        }
15597
15598        int doPostInstall(int status, int uid) {
15599            if (status != PackageManager.INSTALL_SUCCEEDED) {
15600                cleanUp();
15601            } else {
15602                final int groupOwner;
15603                final String protectedFile;
15604                if (isFwdLocked()) {
15605                    groupOwner = UserHandle.getSharedAppGid(uid);
15606                    protectedFile = RES_FILE_NAME;
15607                } else {
15608                    groupOwner = -1;
15609                    protectedFile = null;
15610                }
15611
15612                if (uid < Process.FIRST_APPLICATION_UID
15613                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15614                    Slog.e(TAG, "Failed to finalize " + cid);
15615                    PackageHelper.destroySdDir(cid);
15616                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15617                }
15618
15619                boolean mounted = PackageHelper.isContainerMounted(cid);
15620                if (!mounted) {
15621                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15622                }
15623            }
15624            return status;
15625        }
15626
15627        private void cleanUp() {
15628            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15629
15630            // Destroy secure container
15631            PackageHelper.destroySdDir(cid);
15632        }
15633
15634        private List<String> getAllCodePaths() {
15635            final File codeFile = new File(getCodePath());
15636            if (codeFile != null && codeFile.exists()) {
15637                try {
15638                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15639                    return pkg.getAllCodePaths();
15640                } catch (PackageParserException e) {
15641                    // Ignored; we tried our best
15642                }
15643            }
15644            return Collections.EMPTY_LIST;
15645        }
15646
15647        void cleanUpResourcesLI() {
15648            // Enumerate all code paths before deleting
15649            cleanUpResourcesLI(getAllCodePaths());
15650        }
15651
15652        private void cleanUpResourcesLI(List<String> allCodePaths) {
15653            cleanUp();
15654            removeDexFiles(allCodePaths, instructionSets);
15655        }
15656
15657        String getPackageName() {
15658            return getAsecPackageName(cid);
15659        }
15660
15661        boolean doPostDeleteLI(boolean delete) {
15662            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15663            final List<String> allCodePaths = getAllCodePaths();
15664            boolean mounted = PackageHelper.isContainerMounted(cid);
15665            if (mounted) {
15666                // Unmount first
15667                if (PackageHelper.unMountSdDir(cid)) {
15668                    mounted = false;
15669                }
15670            }
15671            if (!mounted && delete) {
15672                cleanUpResourcesLI(allCodePaths);
15673            }
15674            return !mounted;
15675        }
15676
15677        @Override
15678        int doPreCopy() {
15679            if (isFwdLocked()) {
15680                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15681                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15682                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15683                }
15684            }
15685
15686            return PackageManager.INSTALL_SUCCEEDED;
15687        }
15688
15689        @Override
15690        int doPostCopy(int uid) {
15691            if (isFwdLocked()) {
15692                if (uid < Process.FIRST_APPLICATION_UID
15693                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15694                                RES_FILE_NAME)) {
15695                    Slog.e(TAG, "Failed to finalize " + cid);
15696                    PackageHelper.destroySdDir(cid);
15697                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15698                }
15699            }
15700
15701            return PackageManager.INSTALL_SUCCEEDED;
15702        }
15703    }
15704
15705    /**
15706     * Logic to handle movement of existing installed applications.
15707     */
15708    class MoveInstallArgs extends InstallArgs {
15709        private File codeFile;
15710        private File resourceFile;
15711
15712        /** New install */
15713        MoveInstallArgs(InstallParams params) {
15714            super(params.origin, params.move, params.observer, params.installFlags,
15715                    params.installerPackageName, params.volumeUuid,
15716                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15717                    params.grantedRuntimePermissions,
15718                    params.traceMethod, params.traceCookie, params.certificates,
15719                    params.installReason);
15720        }
15721
15722        int copyApk(IMediaContainerService imcs, boolean temp) {
15723            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15724                    + move.fromUuid + " to " + move.toUuid);
15725            synchronized (mInstaller) {
15726                try {
15727                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15728                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15729                } catch (InstallerException e) {
15730                    Slog.w(TAG, "Failed to move app", e);
15731                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15732                }
15733            }
15734
15735            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15736            resourceFile = codeFile;
15737            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15738
15739            return PackageManager.INSTALL_SUCCEEDED;
15740        }
15741
15742        int doPreInstall(int status) {
15743            if (status != PackageManager.INSTALL_SUCCEEDED) {
15744                cleanUp(move.toUuid);
15745            }
15746            return status;
15747        }
15748
15749        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15750            if (status != PackageManager.INSTALL_SUCCEEDED) {
15751                cleanUp(move.toUuid);
15752                return false;
15753            }
15754
15755            // Reflect the move in app info
15756            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15757            pkg.setApplicationInfoCodePath(pkg.codePath);
15758            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15759            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15760            pkg.setApplicationInfoResourcePath(pkg.codePath);
15761            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15762            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15763
15764            return true;
15765        }
15766
15767        int doPostInstall(int status, int uid) {
15768            if (status == PackageManager.INSTALL_SUCCEEDED) {
15769                cleanUp(move.fromUuid);
15770            } else {
15771                cleanUp(move.toUuid);
15772            }
15773            return status;
15774        }
15775
15776        @Override
15777        String getCodePath() {
15778            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15779        }
15780
15781        @Override
15782        String getResourcePath() {
15783            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15784        }
15785
15786        private boolean cleanUp(String volumeUuid) {
15787            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15788                    move.dataAppName);
15789            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15790            final int[] userIds = sUserManager.getUserIds();
15791            synchronized (mInstallLock) {
15792                // Clean up both app data and code
15793                // All package moves are frozen until finished
15794                for (int userId : userIds) {
15795                    try {
15796                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15797                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15798                    } catch (InstallerException e) {
15799                        Slog.w(TAG, String.valueOf(e));
15800                    }
15801                }
15802                removeCodePathLI(codeFile);
15803            }
15804            return true;
15805        }
15806
15807        void cleanUpResourcesLI() {
15808            throw new UnsupportedOperationException();
15809        }
15810
15811        boolean doPostDeleteLI(boolean delete) {
15812            throw new UnsupportedOperationException();
15813        }
15814    }
15815
15816    static String getAsecPackageName(String packageCid) {
15817        int idx = packageCid.lastIndexOf("-");
15818        if (idx == -1) {
15819            return packageCid;
15820        }
15821        return packageCid.substring(0, idx);
15822    }
15823
15824    // Utility method used to create code paths based on package name and available index.
15825    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15826        String idxStr = "";
15827        int idx = 1;
15828        // Fall back to default value of idx=1 if prefix is not
15829        // part of oldCodePath
15830        if (oldCodePath != null) {
15831            String subStr = oldCodePath;
15832            // Drop the suffix right away
15833            if (suffix != null && subStr.endsWith(suffix)) {
15834                subStr = subStr.substring(0, subStr.length() - suffix.length());
15835            }
15836            // If oldCodePath already contains prefix find out the
15837            // ending index to either increment or decrement.
15838            int sidx = subStr.lastIndexOf(prefix);
15839            if (sidx != -1) {
15840                subStr = subStr.substring(sidx + prefix.length());
15841                if (subStr != null) {
15842                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15843                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15844                    }
15845                    try {
15846                        idx = Integer.parseInt(subStr);
15847                        if (idx <= 1) {
15848                            idx++;
15849                        } else {
15850                            idx--;
15851                        }
15852                    } catch(NumberFormatException e) {
15853                    }
15854                }
15855            }
15856        }
15857        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15858        return prefix + idxStr;
15859    }
15860
15861    private File getNextCodePath(File targetDir, String packageName) {
15862        File result;
15863        SecureRandom random = new SecureRandom();
15864        byte[] bytes = new byte[16];
15865        do {
15866            random.nextBytes(bytes);
15867            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15868            result = new File(targetDir, packageName + "-" + suffix);
15869        } while (result.exists());
15870        return result;
15871    }
15872
15873    // Utility method that returns the relative package path with respect
15874    // to the installation directory. Like say for /data/data/com.test-1.apk
15875    // string com.test-1 is returned.
15876    static String deriveCodePathName(String codePath) {
15877        if (codePath == null) {
15878            return null;
15879        }
15880        final File codeFile = new File(codePath);
15881        final String name = codeFile.getName();
15882        if (codeFile.isDirectory()) {
15883            return name;
15884        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15885            final int lastDot = name.lastIndexOf('.');
15886            return name.substring(0, lastDot);
15887        } else {
15888            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15889            return null;
15890        }
15891    }
15892
15893    static class PackageInstalledInfo {
15894        String name;
15895        int uid;
15896        // The set of users that originally had this package installed.
15897        int[] origUsers;
15898        // The set of users that now have this package installed.
15899        int[] newUsers;
15900        PackageParser.Package pkg;
15901        int returnCode;
15902        String returnMsg;
15903        PackageRemovedInfo removedInfo;
15904        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15905
15906        public void setError(int code, String msg) {
15907            setReturnCode(code);
15908            setReturnMessage(msg);
15909            Slog.w(TAG, msg);
15910        }
15911
15912        public void setError(String msg, PackageParserException e) {
15913            setReturnCode(e.error);
15914            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15915            Slog.w(TAG, msg, e);
15916        }
15917
15918        public void setError(String msg, PackageManagerException e) {
15919            returnCode = e.error;
15920            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15921            Slog.w(TAG, msg, e);
15922        }
15923
15924        public void setReturnCode(int returnCode) {
15925            this.returnCode = returnCode;
15926            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15927            for (int i = 0; i < childCount; i++) {
15928                addedChildPackages.valueAt(i).returnCode = returnCode;
15929            }
15930        }
15931
15932        private void setReturnMessage(String returnMsg) {
15933            this.returnMsg = returnMsg;
15934            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15935            for (int i = 0; i < childCount; i++) {
15936                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15937            }
15938        }
15939
15940        // In some error cases we want to convey more info back to the observer
15941        String origPackage;
15942        String origPermission;
15943    }
15944
15945    /*
15946     * Install a non-existing package.
15947     */
15948    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15949            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15950            PackageInstalledInfo res, int installReason) {
15951        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15952
15953        // Remember this for later, in case we need to rollback this install
15954        String pkgName = pkg.packageName;
15955
15956        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15957
15958        synchronized(mPackages) {
15959            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15960            if (renamedPackage != null) {
15961                // A package with the same name is already installed, though
15962                // it has been renamed to an older name.  The package we
15963                // are trying to install should be installed as an update to
15964                // the existing one, but that has not been requested, so bail.
15965                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15966                        + " without first uninstalling package running as "
15967                        + renamedPackage);
15968                return;
15969            }
15970            if (mPackages.containsKey(pkgName)) {
15971                // Don't allow installation over an existing package with the same name.
15972                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15973                        + " without first uninstalling.");
15974                return;
15975            }
15976        }
15977
15978        try {
15979            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15980                    System.currentTimeMillis(), user);
15981
15982            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15983
15984            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15985                prepareAppDataAfterInstallLIF(newPackage);
15986
15987            } else {
15988                // Remove package from internal structures, but keep around any
15989                // data that might have already existed
15990                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15991                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15992            }
15993        } catch (PackageManagerException e) {
15994            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15995        }
15996
15997        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15998    }
15999
16000    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16001        // Can't rotate keys during boot or if sharedUser.
16002        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16003                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16004            return false;
16005        }
16006        // app is using upgradeKeySets; make sure all are valid
16007        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16008        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16009        for (int i = 0; i < upgradeKeySets.length; i++) {
16010            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16011                Slog.wtf(TAG, "Package "
16012                         + (oldPs.name != null ? oldPs.name : "<null>")
16013                         + " contains upgrade-key-set reference to unknown key-set: "
16014                         + upgradeKeySets[i]
16015                         + " reverting to signatures check.");
16016                return false;
16017            }
16018        }
16019        return true;
16020    }
16021
16022    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16023        // Upgrade keysets are being used.  Determine if new package has a superset of the
16024        // required keys.
16025        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16026        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16027        for (int i = 0; i < upgradeKeySets.length; i++) {
16028            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16029            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16030                return true;
16031            }
16032        }
16033        return false;
16034    }
16035
16036    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16037        try (DigestInputStream digestStream =
16038                new DigestInputStream(new FileInputStream(file), digest)) {
16039            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16040        }
16041    }
16042
16043    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16044            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16045            int installReason) {
16046        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16047
16048        final PackageParser.Package oldPackage;
16049        final String pkgName = pkg.packageName;
16050        final int[] allUsers;
16051        final int[] installedUsers;
16052
16053        synchronized(mPackages) {
16054            oldPackage = mPackages.get(pkgName);
16055            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16056
16057            // don't allow upgrade to target a release SDK from a pre-release SDK
16058            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16059                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16060            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16061                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16062            if (oldTargetsPreRelease
16063                    && !newTargetsPreRelease
16064                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16065                Slog.w(TAG, "Can't install package targeting released sdk");
16066                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16067                return;
16068            }
16069
16070            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16071
16072            // verify signatures are valid
16073            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16074                if (!checkUpgradeKeySetLP(ps, pkg)) {
16075                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16076                            "New package not signed by keys specified by upgrade-keysets: "
16077                                    + pkgName);
16078                    return;
16079                }
16080            } else {
16081                // default to original signature matching
16082                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16083                        != PackageManager.SIGNATURE_MATCH) {
16084                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16085                            "New package has a different signature: " + pkgName);
16086                    return;
16087                }
16088            }
16089
16090            // don't allow a system upgrade unless the upgrade hash matches
16091            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16092                byte[] digestBytes = null;
16093                try {
16094                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16095                    updateDigest(digest, new File(pkg.baseCodePath));
16096                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16097                        for (String path : pkg.splitCodePaths) {
16098                            updateDigest(digest, new File(path));
16099                        }
16100                    }
16101                    digestBytes = digest.digest();
16102                } catch (NoSuchAlgorithmException | IOException e) {
16103                    res.setError(INSTALL_FAILED_INVALID_APK,
16104                            "Could not compute hash: " + pkgName);
16105                    return;
16106                }
16107                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16108                    res.setError(INSTALL_FAILED_INVALID_APK,
16109                            "New package fails restrict-update check: " + pkgName);
16110                    return;
16111                }
16112                // retain upgrade restriction
16113                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16114            }
16115
16116            // Check for shared user id changes
16117            String invalidPackageName =
16118                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16119            if (invalidPackageName != null) {
16120                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16121                        "Package " + invalidPackageName + " tried to change user "
16122                                + oldPackage.mSharedUserId);
16123                return;
16124            }
16125
16126            // In case of rollback, remember per-user/profile install state
16127            allUsers = sUserManager.getUserIds();
16128            installedUsers = ps.queryInstalledUsers(allUsers, true);
16129
16130            // don't allow an upgrade from full to ephemeral
16131            if (isInstantApp) {
16132                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16133                    for (int currentUser : allUsers) {
16134                        if (!ps.getInstantApp(currentUser)) {
16135                            // can't downgrade from full to instant
16136                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16137                                    + " for user: " + currentUser);
16138                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16139                            return;
16140                        }
16141                    }
16142                } else if (!ps.getInstantApp(user.getIdentifier())) {
16143                    // can't downgrade from full to instant
16144                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16145                            + " for user: " + user.getIdentifier());
16146                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16147                    return;
16148                }
16149            }
16150        }
16151
16152        // Update what is removed
16153        res.removedInfo = new PackageRemovedInfo();
16154        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16155        res.removedInfo.removedPackage = oldPackage.packageName;
16156        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16157        res.removedInfo.isUpdate = true;
16158        res.removedInfo.origUsers = installedUsers;
16159        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
16160        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16161        for (int i = 0; i < installedUsers.length; i++) {
16162            final int userId = installedUsers[i];
16163            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16164        }
16165
16166        final int childCount = (oldPackage.childPackages != null)
16167                ? oldPackage.childPackages.size() : 0;
16168        for (int i = 0; i < childCount; i++) {
16169            boolean childPackageUpdated = false;
16170            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16171            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16172            if (res.addedChildPackages != null) {
16173                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16174                if (childRes != null) {
16175                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16176                    childRes.removedInfo.removedPackage = childPkg.packageName;
16177                    childRes.removedInfo.isUpdate = true;
16178                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16179                    childPackageUpdated = true;
16180                }
16181            }
16182            if (!childPackageUpdated) {
16183                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
16184                childRemovedRes.removedPackage = childPkg.packageName;
16185                childRemovedRes.isUpdate = false;
16186                childRemovedRes.dataRemoved = true;
16187                synchronized (mPackages) {
16188                    if (childPs != null) {
16189                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16190                    }
16191                }
16192                if (res.removedInfo.removedChildPackages == null) {
16193                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16194                }
16195                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16196            }
16197        }
16198
16199        boolean sysPkg = (isSystemApp(oldPackage));
16200        if (sysPkg) {
16201            // Set the system/privileged flags as needed
16202            final boolean privileged =
16203                    (oldPackage.applicationInfo.privateFlags
16204                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16205            final int systemPolicyFlags = policyFlags
16206                    | PackageParser.PARSE_IS_SYSTEM
16207                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16208
16209            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16210                    user, allUsers, installerPackageName, res, installReason);
16211        } else {
16212            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16213                    user, allUsers, installerPackageName, res, installReason);
16214        }
16215    }
16216
16217    public List<String> getPreviousCodePaths(String packageName) {
16218        final PackageSetting ps = mSettings.mPackages.get(packageName);
16219        final List<String> result = new ArrayList<String>();
16220        if (ps != null && ps.oldCodePaths != null) {
16221            result.addAll(ps.oldCodePaths);
16222        }
16223        return result;
16224    }
16225
16226    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16227            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16228            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16229            int installReason) {
16230        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16231                + deletedPackage);
16232
16233        String pkgName = deletedPackage.packageName;
16234        boolean deletedPkg = true;
16235        boolean addedPkg = false;
16236        boolean updatedSettings = false;
16237        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16238        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16239                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16240
16241        final long origUpdateTime = (pkg.mExtras != null)
16242                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16243
16244        // First delete the existing package while retaining the data directory
16245        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16246                res.removedInfo, true, pkg)) {
16247            // If the existing package wasn't successfully deleted
16248            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16249            deletedPkg = false;
16250        } else {
16251            // Successfully deleted the old package; proceed with replace.
16252
16253            // If deleted package lived in a container, give users a chance to
16254            // relinquish resources before killing.
16255            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16256                if (DEBUG_INSTALL) {
16257                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16258                }
16259                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16260                final ArrayList<String> pkgList = new ArrayList<String>(1);
16261                pkgList.add(deletedPackage.applicationInfo.packageName);
16262                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16263            }
16264
16265            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16266                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16267            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16268
16269            try {
16270                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16271                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16272                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16273                        installReason);
16274
16275                // Update the in-memory copy of the previous code paths.
16276                PackageSetting ps = mSettings.mPackages.get(pkgName);
16277                if (!killApp) {
16278                    if (ps.oldCodePaths == null) {
16279                        ps.oldCodePaths = new ArraySet<>();
16280                    }
16281                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16282                    if (deletedPackage.splitCodePaths != null) {
16283                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16284                    }
16285                } else {
16286                    ps.oldCodePaths = null;
16287                }
16288                if (ps.childPackageNames != null) {
16289                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16290                        final String childPkgName = ps.childPackageNames.get(i);
16291                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16292                        childPs.oldCodePaths = ps.oldCodePaths;
16293                    }
16294                }
16295                // set instant app status, but, only if it's explicitly specified
16296                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16297                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16298                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16299                prepareAppDataAfterInstallLIF(newPackage);
16300                addedPkg = true;
16301                mDexManager.notifyPackageUpdated(newPackage.packageName,
16302                        newPackage.baseCodePath, newPackage.splitCodePaths);
16303            } catch (PackageManagerException e) {
16304                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16305            }
16306        }
16307
16308        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16309            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16310
16311            // Revert all internal state mutations and added folders for the failed install
16312            if (addedPkg) {
16313                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16314                        res.removedInfo, true, null);
16315            }
16316
16317            // Restore the old package
16318            if (deletedPkg) {
16319                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16320                File restoreFile = new File(deletedPackage.codePath);
16321                // Parse old package
16322                boolean oldExternal = isExternal(deletedPackage);
16323                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16324                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16325                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16326                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16327                try {
16328                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16329                            null);
16330                } catch (PackageManagerException e) {
16331                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16332                            + e.getMessage());
16333                    return;
16334                }
16335
16336                synchronized (mPackages) {
16337                    // Ensure the installer package name up to date
16338                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16339
16340                    // Update permissions for restored package
16341                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16342
16343                    mSettings.writeLPr();
16344                }
16345
16346                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16347            }
16348        } else {
16349            synchronized (mPackages) {
16350                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16351                if (ps != null) {
16352                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16353                    if (res.removedInfo.removedChildPackages != null) {
16354                        final int childCount = res.removedInfo.removedChildPackages.size();
16355                        // Iterate in reverse as we may modify the collection
16356                        for (int i = childCount - 1; i >= 0; i--) {
16357                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16358                            if (res.addedChildPackages.containsKey(childPackageName)) {
16359                                res.removedInfo.removedChildPackages.removeAt(i);
16360                            } else {
16361                                PackageRemovedInfo childInfo = res.removedInfo
16362                                        .removedChildPackages.valueAt(i);
16363                                childInfo.removedForAllUsers = mPackages.get(
16364                                        childInfo.removedPackage) == null;
16365                            }
16366                        }
16367                    }
16368                }
16369            }
16370        }
16371    }
16372
16373    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16374            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16375            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16376            int installReason) {
16377        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16378                + ", old=" + deletedPackage);
16379
16380        final boolean disabledSystem;
16381
16382        // Remove existing system package
16383        removePackageLI(deletedPackage, true);
16384
16385        synchronized (mPackages) {
16386            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16387        }
16388        if (!disabledSystem) {
16389            // We didn't need to disable the .apk as a current system package,
16390            // which means we are replacing another update that is already
16391            // installed.  We need to make sure to delete the older one's .apk.
16392            res.removedInfo.args = createInstallArgsForExisting(0,
16393                    deletedPackage.applicationInfo.getCodePath(),
16394                    deletedPackage.applicationInfo.getResourcePath(),
16395                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16396        } else {
16397            res.removedInfo.args = null;
16398        }
16399
16400        // Successfully disabled the old package. Now proceed with re-installation
16401        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16402                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16403        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16404
16405        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16406        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16407                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16408
16409        PackageParser.Package newPackage = null;
16410        try {
16411            // Add the package to the internal data structures
16412            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16413
16414            // Set the update and install times
16415            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16416            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16417                    System.currentTimeMillis());
16418
16419            // Update the package dynamic state if succeeded
16420            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16421                // Now that the install succeeded make sure we remove data
16422                // directories for any child package the update removed.
16423                final int deletedChildCount = (deletedPackage.childPackages != null)
16424                        ? deletedPackage.childPackages.size() : 0;
16425                final int newChildCount = (newPackage.childPackages != null)
16426                        ? newPackage.childPackages.size() : 0;
16427                for (int i = 0; i < deletedChildCount; i++) {
16428                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16429                    boolean childPackageDeleted = true;
16430                    for (int j = 0; j < newChildCount; j++) {
16431                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16432                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16433                            childPackageDeleted = false;
16434                            break;
16435                        }
16436                    }
16437                    if (childPackageDeleted) {
16438                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16439                                deletedChildPkg.packageName);
16440                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16441                            PackageRemovedInfo removedChildRes = res.removedInfo
16442                                    .removedChildPackages.get(deletedChildPkg.packageName);
16443                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16444                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16445                        }
16446                    }
16447                }
16448
16449                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16450                        installReason);
16451                prepareAppDataAfterInstallLIF(newPackage);
16452
16453                mDexManager.notifyPackageUpdated(newPackage.packageName,
16454                            newPackage.baseCodePath, newPackage.splitCodePaths);
16455            }
16456        } catch (PackageManagerException e) {
16457            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16458            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16459        }
16460
16461        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16462            // Re installation failed. Restore old information
16463            // Remove new pkg information
16464            if (newPackage != null) {
16465                removeInstalledPackageLI(newPackage, true);
16466            }
16467            // Add back the old system package
16468            try {
16469                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16470            } catch (PackageManagerException e) {
16471                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16472            }
16473
16474            synchronized (mPackages) {
16475                if (disabledSystem) {
16476                    enableSystemPackageLPw(deletedPackage);
16477                }
16478
16479                // Ensure the installer package name up to date
16480                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16481
16482                // Update permissions for restored package
16483                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16484
16485                mSettings.writeLPr();
16486            }
16487
16488            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16489                    + " after failed upgrade");
16490        }
16491    }
16492
16493    /**
16494     * Checks whether the parent or any of the child packages have a change shared
16495     * user. For a package to be a valid update the shred users of the parent and
16496     * the children should match. We may later support changing child shared users.
16497     * @param oldPkg The updated package.
16498     * @param newPkg The update package.
16499     * @return The shared user that change between the versions.
16500     */
16501    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16502            PackageParser.Package newPkg) {
16503        // Check parent shared user
16504        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16505            return newPkg.packageName;
16506        }
16507        // Check child shared users
16508        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16509        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16510        for (int i = 0; i < newChildCount; i++) {
16511            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16512            // If this child was present, did it have the same shared user?
16513            for (int j = 0; j < oldChildCount; j++) {
16514                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16515                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16516                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16517                    return newChildPkg.packageName;
16518                }
16519            }
16520        }
16521        return null;
16522    }
16523
16524    private void removeNativeBinariesLI(PackageSetting ps) {
16525        // Remove the lib path for the parent package
16526        if (ps != null) {
16527            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16528            // Remove the lib path for the child packages
16529            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16530            for (int i = 0; i < childCount; i++) {
16531                PackageSetting childPs = null;
16532                synchronized (mPackages) {
16533                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16534                }
16535                if (childPs != null) {
16536                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16537                            .legacyNativeLibraryPathString);
16538                }
16539            }
16540        }
16541    }
16542
16543    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16544        // Enable the parent package
16545        mSettings.enableSystemPackageLPw(pkg.packageName);
16546        // Enable the child packages
16547        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16548        for (int i = 0; i < childCount; i++) {
16549            PackageParser.Package childPkg = pkg.childPackages.get(i);
16550            mSettings.enableSystemPackageLPw(childPkg.packageName);
16551        }
16552    }
16553
16554    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16555            PackageParser.Package newPkg) {
16556        // Disable the parent package (parent always replaced)
16557        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16558        // Disable the child packages
16559        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16560        for (int i = 0; i < childCount; i++) {
16561            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16562            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16563            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16564        }
16565        return disabled;
16566    }
16567
16568    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16569            String installerPackageName) {
16570        // Enable the parent package
16571        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16572        // Enable the child packages
16573        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16574        for (int i = 0; i < childCount; i++) {
16575            PackageParser.Package childPkg = pkg.childPackages.get(i);
16576            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16577        }
16578    }
16579
16580    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16581        // Collect all used permissions in the UID
16582        ArraySet<String> usedPermissions = new ArraySet<>();
16583        final int packageCount = su.packages.size();
16584        for (int i = 0; i < packageCount; i++) {
16585            PackageSetting ps = su.packages.valueAt(i);
16586            if (ps.pkg == null) {
16587                continue;
16588            }
16589            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16590            for (int j = 0; j < requestedPermCount; j++) {
16591                String permission = ps.pkg.requestedPermissions.get(j);
16592                BasePermission bp = mSettings.mPermissions.get(permission);
16593                if (bp != null) {
16594                    usedPermissions.add(permission);
16595                }
16596            }
16597        }
16598
16599        PermissionsState permissionsState = su.getPermissionsState();
16600        // Prune install permissions
16601        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16602        final int installPermCount = installPermStates.size();
16603        for (int i = installPermCount - 1; i >= 0;  i--) {
16604            PermissionState permissionState = installPermStates.get(i);
16605            if (!usedPermissions.contains(permissionState.getName())) {
16606                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16607                if (bp != null) {
16608                    permissionsState.revokeInstallPermission(bp);
16609                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16610                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16611                }
16612            }
16613        }
16614
16615        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16616
16617        // Prune runtime permissions
16618        for (int userId : allUserIds) {
16619            List<PermissionState> runtimePermStates = permissionsState
16620                    .getRuntimePermissionStates(userId);
16621            final int runtimePermCount = runtimePermStates.size();
16622            for (int i = runtimePermCount - 1; i >= 0; i--) {
16623                PermissionState permissionState = runtimePermStates.get(i);
16624                if (!usedPermissions.contains(permissionState.getName())) {
16625                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16626                    if (bp != null) {
16627                        permissionsState.revokeRuntimePermission(bp, userId);
16628                        permissionsState.updatePermissionFlags(bp, userId,
16629                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16630                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16631                                runtimePermissionChangedUserIds, userId);
16632                    }
16633                }
16634            }
16635        }
16636
16637        return runtimePermissionChangedUserIds;
16638    }
16639
16640    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16641            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16642        // Update the parent package setting
16643        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16644                res, user, installReason);
16645        // Update the child packages setting
16646        final int childCount = (newPackage.childPackages != null)
16647                ? newPackage.childPackages.size() : 0;
16648        for (int i = 0; i < childCount; i++) {
16649            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16650            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16651            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16652                    childRes.origUsers, childRes, user, installReason);
16653        }
16654    }
16655
16656    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16657            String installerPackageName, int[] allUsers, int[] installedForUsers,
16658            PackageInstalledInfo res, UserHandle user, int installReason) {
16659        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16660
16661        String pkgName = newPackage.packageName;
16662        synchronized (mPackages) {
16663            //write settings. the installStatus will be incomplete at this stage.
16664            //note that the new package setting would have already been
16665            //added to mPackages. It hasn't been persisted yet.
16666            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16667            // TODO: Remove this write? It's also written at the end of this method
16668            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16669            mSettings.writeLPr();
16670            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16671        }
16672
16673        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16674        synchronized (mPackages) {
16675            updatePermissionsLPw(newPackage.packageName, newPackage,
16676                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16677                            ? UPDATE_PERMISSIONS_ALL : 0));
16678            // For system-bundled packages, we assume that installing an upgraded version
16679            // of the package implies that the user actually wants to run that new code,
16680            // so we enable the package.
16681            PackageSetting ps = mSettings.mPackages.get(pkgName);
16682            final int userId = user.getIdentifier();
16683            if (ps != null) {
16684                if (isSystemApp(newPackage)) {
16685                    if (DEBUG_INSTALL) {
16686                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16687                    }
16688                    // Enable system package for requested users
16689                    if (res.origUsers != null) {
16690                        for (int origUserId : res.origUsers) {
16691                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16692                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16693                                        origUserId, installerPackageName);
16694                            }
16695                        }
16696                    }
16697                    // Also convey the prior install/uninstall state
16698                    if (allUsers != null && installedForUsers != null) {
16699                        for (int currentUserId : allUsers) {
16700                            final boolean installed = ArrayUtils.contains(
16701                                    installedForUsers, currentUserId);
16702                            if (DEBUG_INSTALL) {
16703                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16704                            }
16705                            ps.setInstalled(installed, currentUserId);
16706                        }
16707                        // these install state changes will be persisted in the
16708                        // upcoming call to mSettings.writeLPr().
16709                    }
16710                }
16711                // It's implied that when a user requests installation, they want the app to be
16712                // installed and enabled.
16713                if (userId != UserHandle.USER_ALL) {
16714                    ps.setInstalled(true, userId);
16715                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16716                }
16717
16718                // When replacing an existing package, preserve the original install reason for all
16719                // users that had the package installed before.
16720                final Set<Integer> previousUserIds = new ArraySet<>();
16721                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16722                    final int installReasonCount = res.removedInfo.installReasons.size();
16723                    for (int i = 0; i < installReasonCount; i++) {
16724                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16725                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16726                        ps.setInstallReason(previousInstallReason, previousUserId);
16727                        previousUserIds.add(previousUserId);
16728                    }
16729                }
16730
16731                // Set install reason for users that are having the package newly installed.
16732                if (userId == UserHandle.USER_ALL) {
16733                    for (int currentUserId : sUserManager.getUserIds()) {
16734                        if (!previousUserIds.contains(currentUserId)) {
16735                            ps.setInstallReason(installReason, currentUserId);
16736                        }
16737                    }
16738                } else if (!previousUserIds.contains(userId)) {
16739                    ps.setInstallReason(installReason, userId);
16740                }
16741                mSettings.writeKernelMappingLPr(ps);
16742            }
16743            res.name = pkgName;
16744            res.uid = newPackage.applicationInfo.uid;
16745            res.pkg = newPackage;
16746            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16747            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16748            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16749            //to update install status
16750            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16751            mSettings.writeLPr();
16752            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16753        }
16754
16755        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16756    }
16757
16758    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16759        try {
16760            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16761            installPackageLI(args, res);
16762        } finally {
16763            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16764        }
16765    }
16766
16767    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16768        final int installFlags = args.installFlags;
16769        final String installerPackageName = args.installerPackageName;
16770        final String volumeUuid = args.volumeUuid;
16771        final File tmpPackageFile = new File(args.getCodePath());
16772        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16773        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16774                || (args.volumeUuid != null));
16775        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16776        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16777        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16778        boolean replace = false;
16779        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16780        if (args.move != null) {
16781            // moving a complete application; perform an initial scan on the new install location
16782            scanFlags |= SCAN_INITIAL;
16783        }
16784        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16785            scanFlags |= SCAN_DONT_KILL_APP;
16786        }
16787        if (instantApp) {
16788            scanFlags |= SCAN_AS_INSTANT_APP;
16789        }
16790        if (fullApp) {
16791            scanFlags |= SCAN_AS_FULL_APP;
16792        }
16793
16794        // Result object to be returned
16795        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16796
16797        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16798
16799        // Sanity check
16800        if (instantApp && (forwardLocked || onExternal)) {
16801            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16802                    + " external=" + onExternal);
16803            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16804            return;
16805        }
16806
16807        // Retrieve PackageSettings and parse package
16808        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16809                | PackageParser.PARSE_ENFORCE_CODE
16810                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16811                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16812                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16813                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16814        PackageParser pp = new PackageParser();
16815        pp.setSeparateProcesses(mSeparateProcesses);
16816        pp.setDisplayMetrics(mMetrics);
16817        pp.setCallback(mPackageParserCallback);
16818
16819        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16820        final PackageParser.Package pkg;
16821        try {
16822            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16823        } catch (PackageParserException e) {
16824            res.setError("Failed parse during installPackageLI", e);
16825            return;
16826        } finally {
16827            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16828        }
16829
16830        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16831        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16832            Slog.w(TAG, "Instant app package " + pkg.packageName
16833                    + " does not target O, this will be a fatal error.");
16834            // STOPSHIP: Make this a fatal error
16835            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16836        }
16837        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16838            Slog.w(TAG, "Instant app package " + pkg.packageName
16839                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16840            // STOPSHIP: Make this a fatal error
16841            pkg.applicationInfo.targetSandboxVersion = 2;
16842        }
16843
16844        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16845            // Static shared libraries have synthetic package names
16846            renameStaticSharedLibraryPackage(pkg);
16847
16848            // No static shared libs on external storage
16849            if (onExternal) {
16850                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16851                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16852                        "Packages declaring static-shared libs cannot be updated");
16853                return;
16854            }
16855        }
16856
16857        // If we are installing a clustered package add results for the children
16858        if (pkg.childPackages != null) {
16859            synchronized (mPackages) {
16860                final int childCount = pkg.childPackages.size();
16861                for (int i = 0; i < childCount; i++) {
16862                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16863                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16864                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16865                    childRes.pkg = childPkg;
16866                    childRes.name = childPkg.packageName;
16867                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16868                    if (childPs != null) {
16869                        childRes.origUsers = childPs.queryInstalledUsers(
16870                                sUserManager.getUserIds(), true);
16871                    }
16872                    if ((mPackages.containsKey(childPkg.packageName))) {
16873                        childRes.removedInfo = new PackageRemovedInfo();
16874                        childRes.removedInfo.removedPackage = childPkg.packageName;
16875                    }
16876                    if (res.addedChildPackages == null) {
16877                        res.addedChildPackages = new ArrayMap<>();
16878                    }
16879                    res.addedChildPackages.put(childPkg.packageName, childRes);
16880                }
16881            }
16882        }
16883
16884        // If package doesn't declare API override, mark that we have an install
16885        // time CPU ABI override.
16886        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16887            pkg.cpuAbiOverride = args.abiOverride;
16888        }
16889
16890        String pkgName = res.name = pkg.packageName;
16891        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16892            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16893                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16894                return;
16895            }
16896        }
16897
16898        try {
16899            // either use what we've been given or parse directly from the APK
16900            if (args.certificates != null) {
16901                try {
16902                    PackageParser.populateCertificates(pkg, args.certificates);
16903                } catch (PackageParserException e) {
16904                    // there was something wrong with the certificates we were given;
16905                    // try to pull them from the APK
16906                    PackageParser.collectCertificates(pkg, parseFlags);
16907                }
16908            } else {
16909                PackageParser.collectCertificates(pkg, parseFlags);
16910            }
16911        } catch (PackageParserException e) {
16912            res.setError("Failed collect during installPackageLI", e);
16913            return;
16914        }
16915
16916        // Get rid of all references to package scan path via parser.
16917        pp = null;
16918        String oldCodePath = null;
16919        boolean systemApp = false;
16920        synchronized (mPackages) {
16921            // Check if installing already existing package
16922            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16923                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16924                if (pkg.mOriginalPackages != null
16925                        && pkg.mOriginalPackages.contains(oldName)
16926                        && mPackages.containsKey(oldName)) {
16927                    // This package is derived from an original package,
16928                    // and this device has been updating from that original
16929                    // name.  We must continue using the original name, so
16930                    // rename the new package here.
16931                    pkg.setPackageName(oldName);
16932                    pkgName = pkg.packageName;
16933                    replace = true;
16934                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16935                            + oldName + " pkgName=" + pkgName);
16936                } else if (mPackages.containsKey(pkgName)) {
16937                    // This package, under its official name, already exists
16938                    // on the device; we should replace it.
16939                    replace = true;
16940                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16941                }
16942
16943                // Child packages are installed through the parent package
16944                if (pkg.parentPackage != null) {
16945                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16946                            "Package " + pkg.packageName + " is child of package "
16947                                    + pkg.parentPackage.parentPackage + ". Child packages "
16948                                    + "can be updated only through the parent package.");
16949                    return;
16950                }
16951
16952                if (replace) {
16953                    // Prevent apps opting out from runtime permissions
16954                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16955                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16956                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16957                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16958                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16959                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16960                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16961                                        + " doesn't support runtime permissions but the old"
16962                                        + " target SDK " + oldTargetSdk + " does.");
16963                        return;
16964                    }
16965                    // Prevent apps from downgrading their targetSandbox.
16966                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16967                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16968                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16969                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16970                                "Package " + pkg.packageName + " new target sandbox "
16971                                + newTargetSandbox + " is incompatible with the previous value of"
16972                                + oldTargetSandbox + ".");
16973                        return;
16974                    }
16975
16976                    // Prevent installing of child packages
16977                    if (oldPackage.parentPackage != null) {
16978                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16979                                "Package " + pkg.packageName + " is child of package "
16980                                        + oldPackage.parentPackage + ". Child packages "
16981                                        + "can be updated only through the parent package.");
16982                        return;
16983                    }
16984                }
16985            }
16986
16987            PackageSetting ps = mSettings.mPackages.get(pkgName);
16988            if (ps != null) {
16989                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16990
16991                // Static shared libs have same package with different versions where
16992                // we internally use a synthetic package name to allow multiple versions
16993                // of the same package, therefore we need to compare signatures against
16994                // the package setting for the latest library version.
16995                PackageSetting signatureCheckPs = ps;
16996                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16997                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16998                    if (libraryEntry != null) {
16999                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17000                    }
17001                }
17002
17003                // Quick sanity check that we're signed correctly if updating;
17004                // we'll check this again later when scanning, but we want to
17005                // bail early here before tripping over redefined permissions.
17006                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17007                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17008                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17009                                + pkg.packageName + " upgrade keys do not match the "
17010                                + "previously installed version");
17011                        return;
17012                    }
17013                } else {
17014                    try {
17015                        verifySignaturesLP(signatureCheckPs, pkg);
17016                    } catch (PackageManagerException e) {
17017                        res.setError(e.error, e.getMessage());
17018                        return;
17019                    }
17020                }
17021
17022                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17023                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17024                    systemApp = (ps.pkg.applicationInfo.flags &
17025                            ApplicationInfo.FLAG_SYSTEM) != 0;
17026                }
17027                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17028            }
17029
17030            int N = pkg.permissions.size();
17031            for (int i = N-1; i >= 0; i--) {
17032                PackageParser.Permission perm = pkg.permissions.get(i);
17033                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17034
17035                // Don't allow anyone but the platform to define ephemeral permissions.
17036                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17037                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17038                    Slog.w(TAG, "Package " + pkg.packageName
17039                            + " attempting to delcare ephemeral permission "
17040                            + perm.info.name + "; Removing ephemeral.");
17041                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17042                }
17043                // Check whether the newly-scanned package wants to define an already-defined perm
17044                if (bp != null) {
17045                    // If the defining package is signed with our cert, it's okay.  This
17046                    // also includes the "updating the same package" case, of course.
17047                    // "updating same package" could also involve key-rotation.
17048                    final boolean sigsOk;
17049                    if (bp.sourcePackage.equals(pkg.packageName)
17050                            && (bp.packageSetting instanceof PackageSetting)
17051                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17052                                    scanFlags))) {
17053                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17054                    } else {
17055                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17056                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17057                    }
17058                    if (!sigsOk) {
17059                        // If the owning package is the system itself, we log but allow
17060                        // install to proceed; we fail the install on all other permission
17061                        // redefinitions.
17062                        if (!bp.sourcePackage.equals("android")) {
17063                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17064                                    + pkg.packageName + " attempting to redeclare permission "
17065                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17066                            res.origPermission = perm.info.name;
17067                            res.origPackage = bp.sourcePackage;
17068                            return;
17069                        } else {
17070                            Slog.w(TAG, "Package " + pkg.packageName
17071                                    + " attempting to redeclare system permission "
17072                                    + perm.info.name + "; ignoring new declaration");
17073                            pkg.permissions.remove(i);
17074                        }
17075                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17076                        // Prevent apps to change protection level to dangerous from any other
17077                        // type as this would allow a privilege escalation where an app adds a
17078                        // normal/signature permission in other app's group and later redefines
17079                        // it as dangerous leading to the group auto-grant.
17080                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17081                                == PermissionInfo.PROTECTION_DANGEROUS) {
17082                            if (bp != null && !bp.isRuntime()) {
17083                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17084                                        + "non-runtime permission " + perm.info.name
17085                                        + " to runtime; keeping old protection level");
17086                                perm.info.protectionLevel = bp.protectionLevel;
17087                            }
17088                        }
17089                    }
17090                }
17091            }
17092        }
17093
17094        if (systemApp) {
17095            if (onExternal) {
17096                // Abort update; system app can't be replaced with app on sdcard
17097                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17098                        "Cannot install updates to system apps on sdcard");
17099                return;
17100            } else if (instantApp) {
17101                // Abort update; system app can't be replaced with an instant app
17102                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17103                        "Cannot update a system app with an instant app");
17104                return;
17105            }
17106        }
17107
17108        if (args.move != null) {
17109            // We did an in-place move, so dex is ready to roll
17110            scanFlags |= SCAN_NO_DEX;
17111            scanFlags |= SCAN_MOVE;
17112
17113            synchronized (mPackages) {
17114                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17115                if (ps == null) {
17116                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17117                            "Missing settings for moved package " + pkgName);
17118                }
17119
17120                // We moved the entire application as-is, so bring over the
17121                // previously derived ABI information.
17122                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17123                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17124            }
17125
17126        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17127            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17128            scanFlags |= SCAN_NO_DEX;
17129
17130            try {
17131                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17132                    args.abiOverride : pkg.cpuAbiOverride);
17133                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17134                        true /*extractLibs*/, mAppLib32InstallDir);
17135            } catch (PackageManagerException pme) {
17136                Slog.e(TAG, "Error deriving application ABI", pme);
17137                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17138                return;
17139            }
17140
17141            // Shared libraries for the package need to be updated.
17142            synchronized (mPackages) {
17143                try {
17144                    updateSharedLibrariesLPr(pkg, null);
17145                } catch (PackageManagerException e) {
17146                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17147                }
17148            }
17149
17150            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17151            // Do not run PackageDexOptimizer through the local performDexOpt
17152            // method because `pkg` may not be in `mPackages` yet.
17153            //
17154            // Also, don't fail application installs if the dexopt step fails.
17155            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17156                    null /* instructionSets */, false /* checkProfiles */,
17157                    getCompilerFilterForReason(REASON_INSTALL),
17158                    getOrCreateCompilerPackageStats(pkg),
17159                    mDexManager.isUsedByOtherApps(pkg.packageName));
17160            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17161
17162            // Notify BackgroundDexOptService that the package has been changed.
17163            // If this is an update of a package which used to fail to compile,
17164            // BDOS will remove it from its blacklist.
17165            // TODO: Layering violation
17166            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17167        }
17168
17169        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17170            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17171            return;
17172        }
17173
17174        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17175
17176        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17177                "installPackageLI")) {
17178            if (replace) {
17179                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17180                    // Static libs have a synthetic package name containing the version
17181                    // and cannot be updated as an update would get a new package name,
17182                    // unless this is the exact same version code which is useful for
17183                    // development.
17184                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17185                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17186                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17187                                + "static-shared libs cannot be updated");
17188                        return;
17189                    }
17190                }
17191                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17192                        installerPackageName, res, args.installReason);
17193            } else {
17194                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17195                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17196            }
17197        }
17198
17199        synchronized (mPackages) {
17200            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17201            if (ps != null) {
17202                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17203                ps.setUpdateAvailable(false /*updateAvailable*/);
17204            }
17205
17206            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17207            for (int i = 0; i < childCount; i++) {
17208                PackageParser.Package childPkg = pkg.childPackages.get(i);
17209                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17210                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17211                if (childPs != null) {
17212                    childRes.newUsers = childPs.queryInstalledUsers(
17213                            sUserManager.getUserIds(), true);
17214                }
17215            }
17216
17217            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17218                updateSequenceNumberLP(pkgName, res.newUsers);
17219                updateInstantAppInstallerLocked(pkgName);
17220            }
17221        }
17222    }
17223
17224    private void startIntentFilterVerifications(int userId, boolean replacing,
17225            PackageParser.Package pkg) {
17226        if (mIntentFilterVerifierComponent == null) {
17227            Slog.w(TAG, "No IntentFilter verification will not be done as "
17228                    + "there is no IntentFilterVerifier available!");
17229            return;
17230        }
17231
17232        final int verifierUid = getPackageUid(
17233                mIntentFilterVerifierComponent.getPackageName(),
17234                MATCH_DEBUG_TRIAGED_MISSING,
17235                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17236
17237        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17238        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17239        mHandler.sendMessage(msg);
17240
17241        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17242        for (int i = 0; i < childCount; i++) {
17243            PackageParser.Package childPkg = pkg.childPackages.get(i);
17244            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17245            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17246            mHandler.sendMessage(msg);
17247        }
17248    }
17249
17250    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17251            PackageParser.Package pkg) {
17252        int size = pkg.activities.size();
17253        if (size == 0) {
17254            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17255                    "No activity, so no need to verify any IntentFilter!");
17256            return;
17257        }
17258
17259        final boolean hasDomainURLs = hasDomainURLs(pkg);
17260        if (!hasDomainURLs) {
17261            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17262                    "No domain URLs, so no need to verify any IntentFilter!");
17263            return;
17264        }
17265
17266        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17267                + " if any IntentFilter from the " + size
17268                + " Activities needs verification ...");
17269
17270        int count = 0;
17271        final String packageName = pkg.packageName;
17272
17273        synchronized (mPackages) {
17274            // If this is a new install and we see that we've already run verification for this
17275            // package, we have nothing to do: it means the state was restored from backup.
17276            if (!replacing) {
17277                IntentFilterVerificationInfo ivi =
17278                        mSettings.getIntentFilterVerificationLPr(packageName);
17279                if (ivi != null) {
17280                    if (DEBUG_DOMAIN_VERIFICATION) {
17281                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17282                                + ivi.getStatusString());
17283                    }
17284                    return;
17285                }
17286            }
17287
17288            // If any filters need to be verified, then all need to be.
17289            boolean needToVerify = false;
17290            for (PackageParser.Activity a : pkg.activities) {
17291                for (ActivityIntentInfo filter : a.intents) {
17292                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17293                        if (DEBUG_DOMAIN_VERIFICATION) {
17294                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17295                        }
17296                        needToVerify = true;
17297                        break;
17298                    }
17299                }
17300            }
17301
17302            if (needToVerify) {
17303                final int verificationId = mIntentFilterVerificationToken++;
17304                for (PackageParser.Activity a : pkg.activities) {
17305                    for (ActivityIntentInfo filter : a.intents) {
17306                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17307                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17308                                    "Verification needed for IntentFilter:" + filter.toString());
17309                            mIntentFilterVerifier.addOneIntentFilterVerification(
17310                                    verifierUid, userId, verificationId, filter, packageName);
17311                            count++;
17312                        }
17313                    }
17314                }
17315            }
17316        }
17317
17318        if (count > 0) {
17319            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17320                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17321                    +  " for userId:" + userId);
17322            mIntentFilterVerifier.startVerifications(userId);
17323        } else {
17324            if (DEBUG_DOMAIN_VERIFICATION) {
17325                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17326            }
17327        }
17328    }
17329
17330    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17331        final ComponentName cn  = filter.activity.getComponentName();
17332        final String packageName = cn.getPackageName();
17333
17334        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17335                packageName);
17336        if (ivi == null) {
17337            return true;
17338        }
17339        int status = ivi.getStatus();
17340        switch (status) {
17341            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17342            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17343                return true;
17344
17345            default:
17346                // Nothing to do
17347                return false;
17348        }
17349    }
17350
17351    private static boolean isMultiArch(ApplicationInfo info) {
17352        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17353    }
17354
17355    private static boolean isExternal(PackageParser.Package pkg) {
17356        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17357    }
17358
17359    private static boolean isExternal(PackageSetting ps) {
17360        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17361    }
17362
17363    private static boolean isSystemApp(PackageParser.Package pkg) {
17364        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17365    }
17366
17367    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17368        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17369    }
17370
17371    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17372        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17373    }
17374
17375    private static boolean isSystemApp(PackageSetting ps) {
17376        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17377    }
17378
17379    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17380        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17381    }
17382
17383    private int packageFlagsToInstallFlags(PackageSetting ps) {
17384        int installFlags = 0;
17385        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17386            // This existing package was an external ASEC install when we have
17387            // the external flag without a UUID
17388            installFlags |= PackageManager.INSTALL_EXTERNAL;
17389        }
17390        if (ps.isForwardLocked()) {
17391            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17392        }
17393        return installFlags;
17394    }
17395
17396    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17397        if (isExternal(pkg)) {
17398            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17399                return StorageManager.UUID_PRIMARY_PHYSICAL;
17400            } else {
17401                return pkg.volumeUuid;
17402            }
17403        } else {
17404            return StorageManager.UUID_PRIVATE_INTERNAL;
17405        }
17406    }
17407
17408    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17409        if (isExternal(pkg)) {
17410            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17411                return mSettings.getExternalVersion();
17412            } else {
17413                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17414            }
17415        } else {
17416            return mSettings.getInternalVersion();
17417        }
17418    }
17419
17420    private void deleteTempPackageFiles() {
17421        final FilenameFilter filter = new FilenameFilter() {
17422            public boolean accept(File dir, String name) {
17423                return name.startsWith("vmdl") && name.endsWith(".tmp");
17424            }
17425        };
17426        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17427            file.delete();
17428        }
17429    }
17430
17431    @Override
17432    public void deletePackageAsUser(String packageName, int versionCode,
17433            IPackageDeleteObserver observer, int userId, int flags) {
17434        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17435                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17436    }
17437
17438    @Override
17439    public void deletePackageVersioned(VersionedPackage versionedPackage,
17440            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17441        mContext.enforceCallingOrSelfPermission(
17442                android.Manifest.permission.DELETE_PACKAGES, null);
17443        Preconditions.checkNotNull(versionedPackage);
17444        Preconditions.checkNotNull(observer);
17445        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17446                PackageManager.VERSION_CODE_HIGHEST,
17447                Integer.MAX_VALUE, "versionCode must be >= -1");
17448
17449        final String packageName = versionedPackage.getPackageName();
17450        // TODO: We will change version code to long, so in the new API it is long
17451        final int versionCode = (int) versionedPackage.getVersionCode();
17452        final String internalPackageName;
17453        synchronized (mPackages) {
17454            // Normalize package name to handle renamed packages and static libs
17455            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17456                    // TODO: We will change version code to long, so in the new API it is long
17457                    (int) versionedPackage.getVersionCode());
17458        }
17459
17460        final int uid = Binder.getCallingUid();
17461        if (!isOrphaned(internalPackageName)
17462                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17463            try {
17464                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17465                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17466                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17467                observer.onUserActionRequired(intent);
17468            } catch (RemoteException re) {
17469            }
17470            return;
17471        }
17472        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17473        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17474        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17475            mContext.enforceCallingOrSelfPermission(
17476                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17477                    "deletePackage for user " + userId);
17478        }
17479
17480        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17481            try {
17482                observer.onPackageDeleted(packageName,
17483                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17484            } catch (RemoteException re) {
17485            }
17486            return;
17487        }
17488
17489        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17490            try {
17491                observer.onPackageDeleted(packageName,
17492                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17493            } catch (RemoteException re) {
17494            }
17495            return;
17496        }
17497
17498        if (DEBUG_REMOVE) {
17499            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17500                    + " deleteAllUsers: " + deleteAllUsers + " version="
17501                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17502                    ? "VERSION_CODE_HIGHEST" : versionCode));
17503        }
17504        // Queue up an async operation since the package deletion may take a little while.
17505        mHandler.post(new Runnable() {
17506            public void run() {
17507                mHandler.removeCallbacks(this);
17508                int returnCode;
17509                if (!deleteAllUsers) {
17510                    returnCode = deletePackageX(internalPackageName, versionCode,
17511                            userId, deleteFlags);
17512                } else {
17513                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17514                            internalPackageName, users);
17515                    // If nobody is blocking uninstall, proceed with delete for all users
17516                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17517                        returnCode = deletePackageX(internalPackageName, versionCode,
17518                                userId, deleteFlags);
17519                    } else {
17520                        // Otherwise uninstall individually for users with blockUninstalls=false
17521                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17522                        for (int userId : users) {
17523                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17524                                returnCode = deletePackageX(internalPackageName, versionCode,
17525                                        userId, userFlags);
17526                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17527                                    Slog.w(TAG, "Package delete failed for user " + userId
17528                                            + ", returnCode " + returnCode);
17529                                }
17530                            }
17531                        }
17532                        // The app has only been marked uninstalled for certain users.
17533                        // We still need to report that delete was blocked
17534                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17535                    }
17536                }
17537                try {
17538                    observer.onPackageDeleted(packageName, returnCode, null);
17539                } catch (RemoteException e) {
17540                    Log.i(TAG, "Observer no longer exists.");
17541                } //end catch
17542            } //end run
17543        });
17544    }
17545
17546    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17547        if (pkg.staticSharedLibName != null) {
17548            return pkg.manifestPackageName;
17549        }
17550        return pkg.packageName;
17551    }
17552
17553    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17554        // Handle renamed packages
17555        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17556        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17557
17558        // Is this a static library?
17559        SparseArray<SharedLibraryEntry> versionedLib =
17560                mStaticLibsByDeclaringPackage.get(packageName);
17561        if (versionedLib == null || versionedLib.size() <= 0) {
17562            return packageName;
17563        }
17564
17565        // Figure out which lib versions the caller can see
17566        SparseIntArray versionsCallerCanSee = null;
17567        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17568        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17569                && callingAppId != Process.ROOT_UID) {
17570            versionsCallerCanSee = new SparseIntArray();
17571            String libName = versionedLib.valueAt(0).info.getName();
17572            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17573            if (uidPackages != null) {
17574                for (String uidPackage : uidPackages) {
17575                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17576                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17577                    if (libIdx >= 0) {
17578                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17579                        versionsCallerCanSee.append(libVersion, libVersion);
17580                    }
17581                }
17582            }
17583        }
17584
17585        // Caller can see nothing - done
17586        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17587            return packageName;
17588        }
17589
17590        // Find the version the caller can see and the app version code
17591        SharedLibraryEntry highestVersion = null;
17592        final int versionCount = versionedLib.size();
17593        for (int i = 0; i < versionCount; i++) {
17594            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17595            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17596                    libEntry.info.getVersion()) < 0) {
17597                continue;
17598            }
17599            // TODO: We will change version code to long, so in the new API it is long
17600            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17601            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17602                if (libVersionCode == versionCode) {
17603                    return libEntry.apk;
17604                }
17605            } else if (highestVersion == null) {
17606                highestVersion = libEntry;
17607            } else if (libVersionCode  > highestVersion.info
17608                    .getDeclaringPackage().getVersionCode()) {
17609                highestVersion = libEntry;
17610            }
17611        }
17612
17613        if (highestVersion != null) {
17614            return highestVersion.apk;
17615        }
17616
17617        return packageName;
17618    }
17619
17620    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17621        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17622              || callingUid == Process.SYSTEM_UID) {
17623            return true;
17624        }
17625        final int callingUserId = UserHandle.getUserId(callingUid);
17626        // If the caller installed the pkgName, then allow it to silently uninstall.
17627        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17628            return true;
17629        }
17630
17631        // Allow package verifier to silently uninstall.
17632        if (mRequiredVerifierPackage != null &&
17633                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17634            return true;
17635        }
17636
17637        // Allow package uninstaller to silently uninstall.
17638        if (mRequiredUninstallerPackage != null &&
17639                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17640            return true;
17641        }
17642
17643        // Allow storage manager to silently uninstall.
17644        if (mStorageManagerPackage != null &&
17645                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17646            return true;
17647        }
17648        return false;
17649    }
17650
17651    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17652        int[] result = EMPTY_INT_ARRAY;
17653        for (int userId : userIds) {
17654            if (getBlockUninstallForUser(packageName, userId)) {
17655                result = ArrayUtils.appendInt(result, userId);
17656            }
17657        }
17658        return result;
17659    }
17660
17661    @Override
17662    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17663        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17664    }
17665
17666    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17667        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17668                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17669        try {
17670            if (dpm != null) {
17671                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17672                        /* callingUserOnly =*/ false);
17673                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17674                        : deviceOwnerComponentName.getPackageName();
17675                // Does the package contains the device owner?
17676                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17677                // this check is probably not needed, since DO should be registered as a device
17678                // admin on some user too. (Original bug for this: b/17657954)
17679                if (packageName.equals(deviceOwnerPackageName)) {
17680                    return true;
17681                }
17682                // Does it contain a device admin for any user?
17683                int[] users;
17684                if (userId == UserHandle.USER_ALL) {
17685                    users = sUserManager.getUserIds();
17686                } else {
17687                    users = new int[]{userId};
17688                }
17689                for (int i = 0; i < users.length; ++i) {
17690                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17691                        return true;
17692                    }
17693                }
17694            }
17695        } catch (RemoteException e) {
17696        }
17697        return false;
17698    }
17699
17700    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17701        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17702    }
17703
17704    /**
17705     *  This method is an internal method that could be get invoked either
17706     *  to delete an installed package or to clean up a failed installation.
17707     *  After deleting an installed package, a broadcast is sent to notify any
17708     *  listeners that the package has been removed. For cleaning up a failed
17709     *  installation, the broadcast is not necessary since the package's
17710     *  installation wouldn't have sent the initial broadcast either
17711     *  The key steps in deleting a package are
17712     *  deleting the package information in internal structures like mPackages,
17713     *  deleting the packages base directories through installd
17714     *  updating mSettings to reflect current status
17715     *  persisting settings for later use
17716     *  sending a broadcast if necessary
17717     */
17718    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17719        final PackageRemovedInfo info = new PackageRemovedInfo();
17720        final boolean res;
17721
17722        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17723                ? UserHandle.USER_ALL : userId;
17724
17725        if (isPackageDeviceAdmin(packageName, removeUser)) {
17726            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17727            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17728        }
17729
17730        PackageSetting uninstalledPs = null;
17731        PackageParser.Package pkg = null;
17732
17733        // for the uninstall-updates case and restricted profiles, remember the per-
17734        // user handle installed state
17735        int[] allUsers;
17736        synchronized (mPackages) {
17737            uninstalledPs = mSettings.mPackages.get(packageName);
17738            if (uninstalledPs == null) {
17739                Slog.w(TAG, "Not removing non-existent package " + packageName);
17740                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17741            }
17742
17743            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17744                    && uninstalledPs.versionCode != versionCode) {
17745                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17746                        + uninstalledPs.versionCode + " != " + versionCode);
17747                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17748            }
17749
17750            // Static shared libs can be declared by any package, so let us not
17751            // allow removing a package if it provides a lib others depend on.
17752            pkg = mPackages.get(packageName);
17753            if (pkg != null && pkg.staticSharedLibName != null) {
17754                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17755                        pkg.staticSharedLibVersion);
17756                if (libEntry != null) {
17757                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17758                            libEntry.info, 0, userId);
17759                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17760                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17761                                + " hosting lib " + libEntry.info.getName() + " version "
17762                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17763                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17764                    }
17765                }
17766            }
17767
17768            allUsers = sUserManager.getUserIds();
17769            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17770        }
17771
17772        final int freezeUser;
17773        if (isUpdatedSystemApp(uninstalledPs)
17774                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17775            // We're downgrading a system app, which will apply to all users, so
17776            // freeze them all during the downgrade
17777            freezeUser = UserHandle.USER_ALL;
17778        } else {
17779            freezeUser = removeUser;
17780        }
17781
17782        synchronized (mInstallLock) {
17783            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17784            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17785                    deleteFlags, "deletePackageX")) {
17786                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17787                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17788            }
17789            synchronized (mPackages) {
17790                if (res) {
17791                    if (pkg != null) {
17792                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17793                    }
17794                    updateSequenceNumberLP(packageName, info.removedUsers);
17795                    updateInstantAppInstallerLocked(packageName);
17796                }
17797            }
17798        }
17799
17800        if (res) {
17801            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17802            info.sendPackageRemovedBroadcasts(killApp);
17803            info.sendSystemPackageUpdatedBroadcasts();
17804            info.sendSystemPackageAppearedBroadcasts();
17805        }
17806        // Force a gc here.
17807        Runtime.getRuntime().gc();
17808        // Delete the resources here after sending the broadcast to let
17809        // other processes clean up before deleting resources.
17810        if (info.args != null) {
17811            synchronized (mInstallLock) {
17812                info.args.doPostDeleteLI(true);
17813            }
17814        }
17815
17816        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17817    }
17818
17819    class PackageRemovedInfo {
17820        String removedPackage;
17821        int uid = -1;
17822        int removedAppId = -1;
17823        int[] origUsers;
17824        int[] removedUsers = null;
17825        int[] broadcastUsers = null;
17826        SparseArray<Integer> installReasons;
17827        boolean isRemovedPackageSystemUpdate = false;
17828        boolean isUpdate;
17829        boolean dataRemoved;
17830        boolean removedForAllUsers;
17831        boolean isStaticSharedLib;
17832        // Clean up resources deleted packages.
17833        InstallArgs args = null;
17834        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17835        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17836
17837        void sendPackageRemovedBroadcasts(boolean killApp) {
17838            sendPackageRemovedBroadcastInternal(killApp);
17839            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17840            for (int i = 0; i < childCount; i++) {
17841                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17842                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17843            }
17844        }
17845
17846        void sendSystemPackageUpdatedBroadcasts() {
17847            if (isRemovedPackageSystemUpdate) {
17848                sendSystemPackageUpdatedBroadcastsInternal();
17849                final int childCount = (removedChildPackages != null)
17850                        ? removedChildPackages.size() : 0;
17851                for (int i = 0; i < childCount; i++) {
17852                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17853                    if (childInfo.isRemovedPackageSystemUpdate) {
17854                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17855                    }
17856                }
17857            }
17858        }
17859
17860        void sendSystemPackageAppearedBroadcasts() {
17861            final int packageCount = (appearedChildPackages != null)
17862                    ? appearedChildPackages.size() : 0;
17863            for (int i = 0; i < packageCount; i++) {
17864                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17865                sendPackageAddedForNewUsers(installedInfo.name, true,
17866                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17867            }
17868        }
17869
17870        private void sendSystemPackageUpdatedBroadcastsInternal() {
17871            Bundle extras = new Bundle(2);
17872            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17873            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17874            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17875                    extras, 0, null, null, null);
17876            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17877                    extras, 0, null, null, null);
17878            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17879                    null, 0, removedPackage, null, null);
17880        }
17881
17882        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17883            // Don't send static shared library removal broadcasts as these
17884            // libs are visible only the the apps that depend on them an one
17885            // cannot remove the library if it has a dependency.
17886            if (isStaticSharedLib) {
17887                return;
17888            }
17889            Bundle extras = new Bundle(2);
17890            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17891            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17892            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17893            if (isUpdate || isRemovedPackageSystemUpdate) {
17894                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17895            }
17896            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17897            if (removedPackage != null) {
17898                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17899                        extras, 0, null, null, broadcastUsers);
17900                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17901                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17902                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17903                            null, null, broadcastUsers);
17904                }
17905            }
17906            if (removedAppId >= 0) {
17907                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17908                        broadcastUsers);
17909            }
17910        }
17911    }
17912
17913    /*
17914     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17915     * flag is not set, the data directory is removed as well.
17916     * make sure this flag is set for partially installed apps. If not its meaningless to
17917     * delete a partially installed application.
17918     */
17919    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17920            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17921        String packageName = ps.name;
17922        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17923        // Retrieve object to delete permissions for shared user later on
17924        final PackageParser.Package deletedPkg;
17925        final PackageSetting deletedPs;
17926        // reader
17927        synchronized (mPackages) {
17928            deletedPkg = mPackages.get(packageName);
17929            deletedPs = mSettings.mPackages.get(packageName);
17930            if (outInfo != null) {
17931                outInfo.removedPackage = packageName;
17932                outInfo.isStaticSharedLib = deletedPkg != null
17933                        && deletedPkg.staticSharedLibName != null;
17934                outInfo.removedUsers = deletedPs != null
17935                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17936                        : null;
17937                if (outInfo.removedUsers == null) {
17938                    outInfo.broadcastUsers = null;
17939                } else {
17940                    outInfo.broadcastUsers = EMPTY_INT_ARRAY;
17941                    int[] allUsers = outInfo.removedUsers;
17942                    for (int i = allUsers.length - 1; i >= 0; --i) {
17943                        final int userId = allUsers[i];
17944                        if (deletedPs.getInstantApp(userId)) {
17945                            continue;
17946                        }
17947                        outInfo.broadcastUsers =
17948                                ArrayUtils.appendInt(outInfo.broadcastUsers, userId);
17949                    }
17950                }
17951            }
17952        }
17953
17954        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17955
17956        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17957            final PackageParser.Package resolvedPkg;
17958            if (deletedPkg != null) {
17959                resolvedPkg = deletedPkg;
17960            } else {
17961                // We don't have a parsed package when it lives on an ejected
17962                // adopted storage device, so fake something together
17963                resolvedPkg = new PackageParser.Package(ps.name);
17964                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17965            }
17966            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17967                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17968            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17969            if (outInfo != null) {
17970                outInfo.dataRemoved = true;
17971            }
17972            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17973        }
17974
17975        int removedAppId = -1;
17976
17977        // writer
17978        synchronized (mPackages) {
17979            boolean installedStateChanged = false;
17980            if (deletedPs != null) {
17981                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17982                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17983                    clearDefaultBrowserIfNeeded(packageName);
17984                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17985                    removedAppId = mSettings.removePackageLPw(packageName);
17986                    if (outInfo != null) {
17987                        outInfo.removedAppId = removedAppId;
17988                    }
17989                    updatePermissionsLPw(deletedPs.name, null, 0);
17990                    if (deletedPs.sharedUser != null) {
17991                        // Remove permissions associated with package. Since runtime
17992                        // permissions are per user we have to kill the removed package
17993                        // or packages running under the shared user of the removed
17994                        // package if revoking the permissions requested only by the removed
17995                        // package is successful and this causes a change in gids.
17996                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17997                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17998                                    userId);
17999                            if (userIdToKill == UserHandle.USER_ALL
18000                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18001                                // If gids changed for this user, kill all affected packages.
18002                                mHandler.post(new Runnable() {
18003                                    @Override
18004                                    public void run() {
18005                                        // This has to happen with no lock held.
18006                                        killApplication(deletedPs.name, deletedPs.appId,
18007                                                KILL_APP_REASON_GIDS_CHANGED);
18008                                    }
18009                                });
18010                                break;
18011                            }
18012                        }
18013                    }
18014                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18015                }
18016                // make sure to preserve per-user disabled state if this removal was just
18017                // a downgrade of a system app to the factory package
18018                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18019                    if (DEBUG_REMOVE) {
18020                        Slog.d(TAG, "Propagating install state across downgrade");
18021                    }
18022                    for (int userId : allUserHandles) {
18023                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18024                        if (DEBUG_REMOVE) {
18025                            Slog.d(TAG, "    user " + userId + " => " + installed);
18026                        }
18027                        if (installed != ps.getInstalled(userId)) {
18028                            installedStateChanged = true;
18029                        }
18030                        ps.setInstalled(installed, userId);
18031                    }
18032                }
18033            }
18034            // can downgrade to reader
18035            if (writeSettings) {
18036                // Save settings now
18037                mSettings.writeLPr();
18038            }
18039            if (installedStateChanged) {
18040                mSettings.writeKernelMappingLPr(ps);
18041            }
18042        }
18043        if (removedAppId != -1) {
18044            // A user ID was deleted here. Go through all users and remove it
18045            // from KeyStore.
18046            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18047        }
18048    }
18049
18050    static boolean locationIsPrivileged(File path) {
18051        try {
18052            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18053                    .getCanonicalPath();
18054            return path.getCanonicalPath().startsWith(privilegedAppDir);
18055        } catch (IOException e) {
18056            Slog.e(TAG, "Unable to access code path " + path);
18057        }
18058        return false;
18059    }
18060
18061    /*
18062     * Tries to delete system package.
18063     */
18064    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18065            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18066            boolean writeSettings) {
18067        if (deletedPs.parentPackageName != null) {
18068            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18069            return false;
18070        }
18071
18072        final boolean applyUserRestrictions
18073                = (allUserHandles != null) && (outInfo.origUsers != null);
18074        final PackageSetting disabledPs;
18075        // Confirm if the system package has been updated
18076        // An updated system app can be deleted. This will also have to restore
18077        // the system pkg from system partition
18078        // reader
18079        synchronized (mPackages) {
18080            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18081        }
18082
18083        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18084                + " disabledPs=" + disabledPs);
18085
18086        if (disabledPs == null) {
18087            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18088            return false;
18089        } else if (DEBUG_REMOVE) {
18090            Slog.d(TAG, "Deleting system pkg from data partition");
18091        }
18092
18093        if (DEBUG_REMOVE) {
18094            if (applyUserRestrictions) {
18095                Slog.d(TAG, "Remembering install states:");
18096                for (int userId : allUserHandles) {
18097                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18098                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18099                }
18100            }
18101        }
18102
18103        // Delete the updated package
18104        outInfo.isRemovedPackageSystemUpdate = true;
18105        if (outInfo.removedChildPackages != null) {
18106            final int childCount = (deletedPs.childPackageNames != null)
18107                    ? deletedPs.childPackageNames.size() : 0;
18108            for (int i = 0; i < childCount; i++) {
18109                String childPackageName = deletedPs.childPackageNames.get(i);
18110                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18111                        .contains(childPackageName)) {
18112                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18113                            childPackageName);
18114                    if (childInfo != null) {
18115                        childInfo.isRemovedPackageSystemUpdate = true;
18116                    }
18117                }
18118            }
18119        }
18120
18121        if (disabledPs.versionCode < deletedPs.versionCode) {
18122            // Delete data for downgrades
18123            flags &= ~PackageManager.DELETE_KEEP_DATA;
18124        } else {
18125            // Preserve data by setting flag
18126            flags |= PackageManager.DELETE_KEEP_DATA;
18127        }
18128
18129        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18130                outInfo, writeSettings, disabledPs.pkg);
18131        if (!ret) {
18132            return false;
18133        }
18134
18135        // writer
18136        synchronized (mPackages) {
18137            // Reinstate the old system package
18138            enableSystemPackageLPw(disabledPs.pkg);
18139            // Remove any native libraries from the upgraded package.
18140            removeNativeBinariesLI(deletedPs);
18141        }
18142
18143        // Install the system package
18144        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18145        int parseFlags = mDefParseFlags
18146                | PackageParser.PARSE_MUST_BE_APK
18147                | PackageParser.PARSE_IS_SYSTEM
18148                | PackageParser.PARSE_IS_SYSTEM_DIR;
18149        if (locationIsPrivileged(disabledPs.codePath)) {
18150            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18151        }
18152
18153        final PackageParser.Package newPkg;
18154        try {
18155            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18156                0 /* currentTime */, null);
18157        } catch (PackageManagerException e) {
18158            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18159                    + e.getMessage());
18160            return false;
18161        }
18162
18163        try {
18164            // update shared libraries for the newly re-installed system package
18165            updateSharedLibrariesLPr(newPkg, null);
18166        } catch (PackageManagerException e) {
18167            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18168        }
18169
18170        prepareAppDataAfterInstallLIF(newPkg);
18171
18172        // writer
18173        synchronized (mPackages) {
18174            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18175
18176            // Propagate the permissions state as we do not want to drop on the floor
18177            // runtime permissions. The update permissions method below will take
18178            // care of removing obsolete permissions and grant install permissions.
18179            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18180            updatePermissionsLPw(newPkg.packageName, newPkg,
18181                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18182
18183            if (applyUserRestrictions) {
18184                boolean installedStateChanged = false;
18185                if (DEBUG_REMOVE) {
18186                    Slog.d(TAG, "Propagating install state across reinstall");
18187                }
18188                for (int userId : allUserHandles) {
18189                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18190                    if (DEBUG_REMOVE) {
18191                        Slog.d(TAG, "    user " + userId + " => " + installed);
18192                    }
18193                    if (installed != ps.getInstalled(userId)) {
18194                        installedStateChanged = true;
18195                    }
18196                    ps.setInstalled(installed, userId);
18197
18198                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18199                }
18200                // Regardless of writeSettings we need to ensure that this restriction
18201                // state propagation is persisted
18202                mSettings.writeAllUsersPackageRestrictionsLPr();
18203                if (installedStateChanged) {
18204                    mSettings.writeKernelMappingLPr(ps);
18205                }
18206            }
18207            // can downgrade to reader here
18208            if (writeSettings) {
18209                mSettings.writeLPr();
18210            }
18211        }
18212        return true;
18213    }
18214
18215    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18216            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18217            PackageRemovedInfo outInfo, boolean writeSettings,
18218            PackageParser.Package replacingPackage) {
18219        synchronized (mPackages) {
18220            if (outInfo != null) {
18221                outInfo.uid = ps.appId;
18222            }
18223
18224            if (outInfo != null && outInfo.removedChildPackages != null) {
18225                final int childCount = (ps.childPackageNames != null)
18226                        ? ps.childPackageNames.size() : 0;
18227                for (int i = 0; i < childCount; i++) {
18228                    String childPackageName = ps.childPackageNames.get(i);
18229                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18230                    if (childPs == null) {
18231                        return false;
18232                    }
18233                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18234                            childPackageName);
18235                    if (childInfo != null) {
18236                        childInfo.uid = childPs.appId;
18237                    }
18238                }
18239            }
18240        }
18241
18242        // Delete package data from internal structures and also remove data if flag is set
18243        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18244
18245        // Delete the child packages data
18246        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18247        for (int i = 0; i < childCount; i++) {
18248            PackageSetting childPs;
18249            synchronized (mPackages) {
18250                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18251            }
18252            if (childPs != null) {
18253                PackageRemovedInfo childOutInfo = (outInfo != null
18254                        && outInfo.removedChildPackages != null)
18255                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18256                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18257                        && (replacingPackage != null
18258                        && !replacingPackage.hasChildPackage(childPs.name))
18259                        ? flags & ~DELETE_KEEP_DATA : flags;
18260                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18261                        deleteFlags, writeSettings);
18262            }
18263        }
18264
18265        // Delete application code and resources only for parent packages
18266        if (ps.parentPackageName == null) {
18267            if (deleteCodeAndResources && (outInfo != null)) {
18268                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18269                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18270                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18271            }
18272        }
18273
18274        return true;
18275    }
18276
18277    @Override
18278    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18279            int userId) {
18280        mContext.enforceCallingOrSelfPermission(
18281                android.Manifest.permission.DELETE_PACKAGES, null);
18282        synchronized (mPackages) {
18283            PackageSetting ps = mSettings.mPackages.get(packageName);
18284            if (ps == null) {
18285                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18286                return false;
18287            }
18288            // Cannot block uninstall of static shared libs as they are
18289            // considered a part of the using app (emulating static linking).
18290            // Also static libs are installed always on internal storage.
18291            PackageParser.Package pkg = mPackages.get(packageName);
18292            if (pkg != null && pkg.staticSharedLibName != null) {
18293                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18294                        + " providing static shared library: " + pkg.staticSharedLibName);
18295                return false;
18296            }
18297            if (!ps.getInstalled(userId)) {
18298                // Can't block uninstall for an app that is not installed or enabled.
18299                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18300                return false;
18301            }
18302            ps.setBlockUninstall(blockUninstall, userId);
18303            mSettings.writePackageRestrictionsLPr(userId);
18304        }
18305        return true;
18306    }
18307
18308    @Override
18309    public boolean getBlockUninstallForUser(String packageName, int userId) {
18310        synchronized (mPackages) {
18311            PackageSetting ps = mSettings.mPackages.get(packageName);
18312            if (ps == null) {
18313                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18314                return false;
18315            }
18316            return ps.getBlockUninstall(userId);
18317        }
18318    }
18319
18320    @Override
18321    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18322        int callingUid = Binder.getCallingUid();
18323        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18324            throw new SecurityException(
18325                    "setRequiredForSystemUser can only be run by the system or root");
18326        }
18327        synchronized (mPackages) {
18328            PackageSetting ps = mSettings.mPackages.get(packageName);
18329            if (ps == null) {
18330                Log.w(TAG, "Package doesn't exist: " + packageName);
18331                return false;
18332            }
18333            if (systemUserApp) {
18334                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18335            } else {
18336                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18337            }
18338            mSettings.writeLPr();
18339        }
18340        return true;
18341    }
18342
18343    /*
18344     * This method handles package deletion in general
18345     */
18346    private boolean deletePackageLIF(String packageName, UserHandle user,
18347            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18348            PackageRemovedInfo outInfo, boolean writeSettings,
18349            PackageParser.Package replacingPackage) {
18350        if (packageName == null) {
18351            Slog.w(TAG, "Attempt to delete null packageName.");
18352            return false;
18353        }
18354
18355        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18356
18357        PackageSetting ps;
18358        synchronized (mPackages) {
18359            ps = mSettings.mPackages.get(packageName);
18360            if (ps == null) {
18361                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18362                return false;
18363            }
18364
18365            if (ps.parentPackageName != null && (!isSystemApp(ps)
18366                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18367                if (DEBUG_REMOVE) {
18368                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18369                            + ((user == null) ? UserHandle.USER_ALL : user));
18370                }
18371                final int removedUserId = (user != null) ? user.getIdentifier()
18372                        : UserHandle.USER_ALL;
18373                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18374                    return false;
18375                }
18376                markPackageUninstalledForUserLPw(ps, user);
18377                scheduleWritePackageRestrictionsLocked(user);
18378                return true;
18379            }
18380        }
18381
18382        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18383                && user.getIdentifier() != UserHandle.USER_ALL)) {
18384            // The caller is asking that the package only be deleted for a single
18385            // user.  To do this, we just mark its uninstalled state and delete
18386            // its data. If this is a system app, we only allow this to happen if
18387            // they have set the special DELETE_SYSTEM_APP which requests different
18388            // semantics than normal for uninstalling system apps.
18389            markPackageUninstalledForUserLPw(ps, user);
18390
18391            if (!isSystemApp(ps)) {
18392                // Do not uninstall the APK if an app should be cached
18393                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18394                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18395                    // Other user still have this package installed, so all
18396                    // we need to do is clear this user's data and save that
18397                    // it is uninstalled.
18398                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18399                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18400                        return false;
18401                    }
18402                    scheduleWritePackageRestrictionsLocked(user);
18403                    return true;
18404                } else {
18405                    // We need to set it back to 'installed' so the uninstall
18406                    // broadcasts will be sent correctly.
18407                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18408                    ps.setInstalled(true, user.getIdentifier());
18409                    mSettings.writeKernelMappingLPr(ps);
18410                }
18411            } else {
18412                // This is a system app, so we assume that the
18413                // other users still have this package installed, so all
18414                // we need to do is clear this user's data and save that
18415                // it is uninstalled.
18416                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18417                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18418                    return false;
18419                }
18420                scheduleWritePackageRestrictionsLocked(user);
18421                return true;
18422            }
18423        }
18424
18425        // If we are deleting a composite package for all users, keep track
18426        // of result for each child.
18427        if (ps.childPackageNames != null && outInfo != null) {
18428            synchronized (mPackages) {
18429                final int childCount = ps.childPackageNames.size();
18430                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18431                for (int i = 0; i < childCount; i++) {
18432                    String childPackageName = ps.childPackageNames.get(i);
18433                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18434                    childInfo.removedPackage = childPackageName;
18435                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18436                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18437                    if (childPs != null) {
18438                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18439                    }
18440                }
18441            }
18442        }
18443
18444        boolean ret = false;
18445        if (isSystemApp(ps)) {
18446            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18447            // When an updated system application is deleted we delete the existing resources
18448            // as well and fall back to existing code in system partition
18449            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18450        } else {
18451            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18452            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18453                    outInfo, writeSettings, replacingPackage);
18454        }
18455
18456        // Take a note whether we deleted the package for all users
18457        if (outInfo != null) {
18458            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18459            if (outInfo.removedChildPackages != null) {
18460                synchronized (mPackages) {
18461                    final int childCount = outInfo.removedChildPackages.size();
18462                    for (int i = 0; i < childCount; i++) {
18463                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18464                        if (childInfo != null) {
18465                            childInfo.removedForAllUsers = mPackages.get(
18466                                    childInfo.removedPackage) == null;
18467                        }
18468                    }
18469                }
18470            }
18471            // If we uninstalled an update to a system app there may be some
18472            // child packages that appeared as they are declared in the system
18473            // app but were not declared in the update.
18474            if (isSystemApp(ps)) {
18475                synchronized (mPackages) {
18476                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18477                    final int childCount = (updatedPs.childPackageNames != null)
18478                            ? updatedPs.childPackageNames.size() : 0;
18479                    for (int i = 0; i < childCount; i++) {
18480                        String childPackageName = updatedPs.childPackageNames.get(i);
18481                        if (outInfo.removedChildPackages == null
18482                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18483                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18484                            if (childPs == null) {
18485                                continue;
18486                            }
18487                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18488                            installRes.name = childPackageName;
18489                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18490                            installRes.pkg = mPackages.get(childPackageName);
18491                            installRes.uid = childPs.pkg.applicationInfo.uid;
18492                            if (outInfo.appearedChildPackages == null) {
18493                                outInfo.appearedChildPackages = new ArrayMap<>();
18494                            }
18495                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18496                        }
18497                    }
18498                }
18499            }
18500        }
18501
18502        return ret;
18503    }
18504
18505    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18506        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18507                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18508        for (int nextUserId : userIds) {
18509            if (DEBUG_REMOVE) {
18510                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18511            }
18512            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18513                    false /*installed*/,
18514                    true /*stopped*/,
18515                    true /*notLaunched*/,
18516                    false /*hidden*/,
18517                    false /*suspended*/,
18518                    false /*instantApp*/,
18519                    null /*lastDisableAppCaller*/,
18520                    null /*enabledComponents*/,
18521                    null /*disabledComponents*/,
18522                    false /*blockUninstall*/,
18523                    ps.readUserState(nextUserId).domainVerificationStatus,
18524                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18525        }
18526        mSettings.writeKernelMappingLPr(ps);
18527    }
18528
18529    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18530            PackageRemovedInfo outInfo) {
18531        final PackageParser.Package pkg;
18532        synchronized (mPackages) {
18533            pkg = mPackages.get(ps.name);
18534        }
18535
18536        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18537                : new int[] {userId};
18538        for (int nextUserId : userIds) {
18539            if (DEBUG_REMOVE) {
18540                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18541                        + nextUserId);
18542            }
18543
18544            destroyAppDataLIF(pkg, userId,
18545                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18546            destroyAppProfilesLIF(pkg, userId);
18547            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18548            schedulePackageCleaning(ps.name, nextUserId, false);
18549            synchronized (mPackages) {
18550                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18551                    scheduleWritePackageRestrictionsLocked(nextUserId);
18552                }
18553                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18554            }
18555        }
18556
18557        if (outInfo != null) {
18558            outInfo.removedPackage = ps.name;
18559            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18560            outInfo.removedAppId = ps.appId;
18561            outInfo.removedUsers = userIds;
18562            outInfo.broadcastUsers = userIds;
18563        }
18564
18565        return true;
18566    }
18567
18568    private final class ClearStorageConnection implements ServiceConnection {
18569        IMediaContainerService mContainerService;
18570
18571        @Override
18572        public void onServiceConnected(ComponentName name, IBinder service) {
18573            synchronized (this) {
18574                mContainerService = IMediaContainerService.Stub
18575                        .asInterface(Binder.allowBlocking(service));
18576                notifyAll();
18577            }
18578        }
18579
18580        @Override
18581        public void onServiceDisconnected(ComponentName name) {
18582        }
18583    }
18584
18585    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18586        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18587
18588        final boolean mounted;
18589        if (Environment.isExternalStorageEmulated()) {
18590            mounted = true;
18591        } else {
18592            final String status = Environment.getExternalStorageState();
18593
18594            mounted = status.equals(Environment.MEDIA_MOUNTED)
18595                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18596        }
18597
18598        if (!mounted) {
18599            return;
18600        }
18601
18602        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18603        int[] users;
18604        if (userId == UserHandle.USER_ALL) {
18605            users = sUserManager.getUserIds();
18606        } else {
18607            users = new int[] { userId };
18608        }
18609        final ClearStorageConnection conn = new ClearStorageConnection();
18610        if (mContext.bindServiceAsUser(
18611                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18612            try {
18613                for (int curUser : users) {
18614                    long timeout = SystemClock.uptimeMillis() + 5000;
18615                    synchronized (conn) {
18616                        long now;
18617                        while (conn.mContainerService == null &&
18618                                (now = SystemClock.uptimeMillis()) < timeout) {
18619                            try {
18620                                conn.wait(timeout - now);
18621                            } catch (InterruptedException e) {
18622                            }
18623                        }
18624                    }
18625                    if (conn.mContainerService == null) {
18626                        return;
18627                    }
18628
18629                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18630                    clearDirectory(conn.mContainerService,
18631                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18632                    if (allData) {
18633                        clearDirectory(conn.mContainerService,
18634                                userEnv.buildExternalStorageAppDataDirs(packageName));
18635                        clearDirectory(conn.mContainerService,
18636                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18637                    }
18638                }
18639            } finally {
18640                mContext.unbindService(conn);
18641            }
18642        }
18643    }
18644
18645    @Override
18646    public void clearApplicationProfileData(String packageName) {
18647        enforceSystemOrRoot("Only the system can clear all profile data");
18648
18649        final PackageParser.Package pkg;
18650        synchronized (mPackages) {
18651            pkg = mPackages.get(packageName);
18652        }
18653
18654        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18655            synchronized (mInstallLock) {
18656                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18657            }
18658        }
18659    }
18660
18661    @Override
18662    public void clearApplicationUserData(final String packageName,
18663            final IPackageDataObserver observer, final int userId) {
18664        mContext.enforceCallingOrSelfPermission(
18665                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18666
18667        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18668                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18669
18670        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18671            throw new SecurityException("Cannot clear data for a protected package: "
18672                    + packageName);
18673        }
18674        // Queue up an async operation since the package deletion may take a little while.
18675        mHandler.post(new Runnable() {
18676            public void run() {
18677                mHandler.removeCallbacks(this);
18678                final boolean succeeded;
18679                try (PackageFreezer freezer = freezePackage(packageName,
18680                        "clearApplicationUserData")) {
18681                    synchronized (mInstallLock) {
18682                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18683                    }
18684                    clearExternalStorageDataSync(packageName, userId, true);
18685                    synchronized (mPackages) {
18686                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18687                                packageName, userId);
18688                    }
18689                }
18690                if (succeeded) {
18691                    // invoke DeviceStorageMonitor's update method to clear any notifications
18692                    DeviceStorageMonitorInternal dsm = LocalServices
18693                            .getService(DeviceStorageMonitorInternal.class);
18694                    if (dsm != null) {
18695                        dsm.checkMemory();
18696                    }
18697                }
18698                if(observer != null) {
18699                    try {
18700                        observer.onRemoveCompleted(packageName, succeeded);
18701                    } catch (RemoteException e) {
18702                        Log.i(TAG, "Observer no longer exists.");
18703                    }
18704                } //end if observer
18705            } //end run
18706        });
18707    }
18708
18709    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18710        if (packageName == null) {
18711            Slog.w(TAG, "Attempt to delete null packageName.");
18712            return false;
18713        }
18714
18715        // Try finding details about the requested package
18716        PackageParser.Package pkg;
18717        synchronized (mPackages) {
18718            pkg = mPackages.get(packageName);
18719            if (pkg == null) {
18720                final PackageSetting ps = mSettings.mPackages.get(packageName);
18721                if (ps != null) {
18722                    pkg = ps.pkg;
18723                }
18724            }
18725
18726            if (pkg == null) {
18727                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18728                return false;
18729            }
18730
18731            PackageSetting ps = (PackageSetting) pkg.mExtras;
18732            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18733        }
18734
18735        clearAppDataLIF(pkg, userId,
18736                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18737
18738        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18739        removeKeystoreDataIfNeeded(userId, appId);
18740
18741        UserManagerInternal umInternal = getUserManagerInternal();
18742        final int flags;
18743        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18744            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18745        } else if (umInternal.isUserRunning(userId)) {
18746            flags = StorageManager.FLAG_STORAGE_DE;
18747        } else {
18748            flags = 0;
18749        }
18750        prepareAppDataContentsLIF(pkg, userId, flags);
18751
18752        return true;
18753    }
18754
18755    /**
18756     * Reverts user permission state changes (permissions and flags) in
18757     * all packages for a given user.
18758     *
18759     * @param userId The device user for which to do a reset.
18760     */
18761    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18762        final int packageCount = mPackages.size();
18763        for (int i = 0; i < packageCount; i++) {
18764            PackageParser.Package pkg = mPackages.valueAt(i);
18765            PackageSetting ps = (PackageSetting) pkg.mExtras;
18766            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18767        }
18768    }
18769
18770    private void resetNetworkPolicies(int userId) {
18771        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18772    }
18773
18774    /**
18775     * Reverts user permission state changes (permissions and flags).
18776     *
18777     * @param ps The package for which to reset.
18778     * @param userId The device user for which to do a reset.
18779     */
18780    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18781            final PackageSetting ps, final int userId) {
18782        if (ps.pkg == null) {
18783            return;
18784        }
18785
18786        // These are flags that can change base on user actions.
18787        final int userSettableMask = FLAG_PERMISSION_USER_SET
18788                | FLAG_PERMISSION_USER_FIXED
18789                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18790                | FLAG_PERMISSION_REVIEW_REQUIRED;
18791
18792        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18793                | FLAG_PERMISSION_POLICY_FIXED;
18794
18795        boolean writeInstallPermissions = false;
18796        boolean writeRuntimePermissions = false;
18797
18798        final int permissionCount = ps.pkg.requestedPermissions.size();
18799        for (int i = 0; i < permissionCount; i++) {
18800            String permission = ps.pkg.requestedPermissions.get(i);
18801
18802            BasePermission bp = mSettings.mPermissions.get(permission);
18803            if (bp == null) {
18804                continue;
18805            }
18806
18807            // If shared user we just reset the state to which only this app contributed.
18808            if (ps.sharedUser != null) {
18809                boolean used = false;
18810                final int packageCount = ps.sharedUser.packages.size();
18811                for (int j = 0; j < packageCount; j++) {
18812                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18813                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18814                            && pkg.pkg.requestedPermissions.contains(permission)) {
18815                        used = true;
18816                        break;
18817                    }
18818                }
18819                if (used) {
18820                    continue;
18821                }
18822            }
18823
18824            PermissionsState permissionsState = ps.getPermissionsState();
18825
18826            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18827
18828            // Always clear the user settable flags.
18829            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18830                    bp.name) != null;
18831            // If permission review is enabled and this is a legacy app, mark the
18832            // permission as requiring a review as this is the initial state.
18833            int flags = 0;
18834            if (mPermissionReviewRequired
18835                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18836                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18837            }
18838            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18839                if (hasInstallState) {
18840                    writeInstallPermissions = true;
18841                } else {
18842                    writeRuntimePermissions = true;
18843                }
18844            }
18845
18846            // Below is only runtime permission handling.
18847            if (!bp.isRuntime()) {
18848                continue;
18849            }
18850
18851            // Never clobber system or policy.
18852            if ((oldFlags & policyOrSystemFlags) != 0) {
18853                continue;
18854            }
18855
18856            // If this permission was granted by default, make sure it is.
18857            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18858                if (permissionsState.grantRuntimePermission(bp, userId)
18859                        != PERMISSION_OPERATION_FAILURE) {
18860                    writeRuntimePermissions = true;
18861                }
18862            // If permission review is enabled the permissions for a legacy apps
18863            // are represented as constantly granted runtime ones, so don't revoke.
18864            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18865                // Otherwise, reset the permission.
18866                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18867                switch (revokeResult) {
18868                    case PERMISSION_OPERATION_SUCCESS:
18869                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18870                        writeRuntimePermissions = true;
18871                        final int appId = ps.appId;
18872                        mHandler.post(new Runnable() {
18873                            @Override
18874                            public void run() {
18875                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18876                            }
18877                        });
18878                    } break;
18879                }
18880            }
18881        }
18882
18883        // Synchronously write as we are taking permissions away.
18884        if (writeRuntimePermissions) {
18885            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18886        }
18887
18888        // Synchronously write as we are taking permissions away.
18889        if (writeInstallPermissions) {
18890            mSettings.writeLPr();
18891        }
18892    }
18893
18894    /**
18895     * Remove entries from the keystore daemon. Will only remove it if the
18896     * {@code appId} is valid.
18897     */
18898    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18899        if (appId < 0) {
18900            return;
18901        }
18902
18903        final KeyStore keyStore = KeyStore.getInstance();
18904        if (keyStore != null) {
18905            if (userId == UserHandle.USER_ALL) {
18906                for (final int individual : sUserManager.getUserIds()) {
18907                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18908                }
18909            } else {
18910                keyStore.clearUid(UserHandle.getUid(userId, appId));
18911            }
18912        } else {
18913            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18914        }
18915    }
18916
18917    @Override
18918    public void deleteApplicationCacheFiles(final String packageName,
18919            final IPackageDataObserver observer) {
18920        final int userId = UserHandle.getCallingUserId();
18921        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18922    }
18923
18924    @Override
18925    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18926            final IPackageDataObserver observer) {
18927        mContext.enforceCallingOrSelfPermission(
18928                android.Manifest.permission.DELETE_CACHE_FILES, null);
18929        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18930                /* requireFullPermission= */ true, /* checkShell= */ false,
18931                "delete application cache files");
18932
18933        final PackageParser.Package pkg;
18934        synchronized (mPackages) {
18935            pkg = mPackages.get(packageName);
18936        }
18937
18938        // Queue up an async operation since the package deletion may take a little while.
18939        mHandler.post(new Runnable() {
18940            public void run() {
18941                synchronized (mInstallLock) {
18942                    final int flags = StorageManager.FLAG_STORAGE_DE
18943                            | StorageManager.FLAG_STORAGE_CE;
18944                    // We're only clearing cache files, so we don't care if the
18945                    // app is unfrozen and still able to run
18946                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18947                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18948                }
18949                clearExternalStorageDataSync(packageName, userId, false);
18950                if (observer != null) {
18951                    try {
18952                        observer.onRemoveCompleted(packageName, true);
18953                    } catch (RemoteException e) {
18954                        Log.i(TAG, "Observer no longer exists.");
18955                    }
18956                }
18957            }
18958        });
18959    }
18960
18961    @Override
18962    public void getPackageSizeInfo(final String packageName, int userHandle,
18963            final IPackageStatsObserver observer) {
18964        throw new UnsupportedOperationException(
18965                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18966    }
18967
18968    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18969        final PackageSetting ps;
18970        synchronized (mPackages) {
18971            ps = mSettings.mPackages.get(packageName);
18972            if (ps == null) {
18973                Slog.w(TAG, "Failed to find settings for " + packageName);
18974                return false;
18975            }
18976        }
18977
18978        final String[] packageNames = { packageName };
18979        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18980        final String[] codePaths = { ps.codePathString };
18981
18982        try {
18983            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18984                    ps.appId, ceDataInodes, codePaths, stats);
18985
18986            // For now, ignore code size of packages on system partition
18987            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18988                stats.codeSize = 0;
18989            }
18990
18991            // External clients expect these to be tracked separately
18992            stats.dataSize -= stats.cacheSize;
18993
18994        } catch (InstallerException e) {
18995            Slog.w(TAG, String.valueOf(e));
18996            return false;
18997        }
18998
18999        return true;
19000    }
19001
19002    private int getUidTargetSdkVersionLockedLPr(int uid) {
19003        Object obj = mSettings.getUserIdLPr(uid);
19004        if (obj instanceof SharedUserSetting) {
19005            final SharedUserSetting sus = (SharedUserSetting) obj;
19006            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19007            final Iterator<PackageSetting> it = sus.packages.iterator();
19008            while (it.hasNext()) {
19009                final PackageSetting ps = it.next();
19010                if (ps.pkg != null) {
19011                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19012                    if (v < vers) vers = v;
19013                }
19014            }
19015            return vers;
19016        } else if (obj instanceof PackageSetting) {
19017            final PackageSetting ps = (PackageSetting) obj;
19018            if (ps.pkg != null) {
19019                return ps.pkg.applicationInfo.targetSdkVersion;
19020            }
19021        }
19022        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19023    }
19024
19025    @Override
19026    public void addPreferredActivity(IntentFilter filter, int match,
19027            ComponentName[] set, ComponentName activity, int userId) {
19028        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19029                "Adding preferred");
19030    }
19031
19032    private void addPreferredActivityInternal(IntentFilter filter, int match,
19033            ComponentName[] set, ComponentName activity, boolean always, int userId,
19034            String opname) {
19035        // writer
19036        int callingUid = Binder.getCallingUid();
19037        enforceCrossUserPermission(callingUid, userId,
19038                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19039        if (filter.countActions() == 0) {
19040            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19041            return;
19042        }
19043        synchronized (mPackages) {
19044            if (mContext.checkCallingOrSelfPermission(
19045                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19046                    != PackageManager.PERMISSION_GRANTED) {
19047                if (getUidTargetSdkVersionLockedLPr(callingUid)
19048                        < Build.VERSION_CODES.FROYO) {
19049                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19050                            + callingUid);
19051                    return;
19052                }
19053                mContext.enforceCallingOrSelfPermission(
19054                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19055            }
19056
19057            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19058            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19059                    + userId + ":");
19060            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19061            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19062            scheduleWritePackageRestrictionsLocked(userId);
19063            postPreferredActivityChangedBroadcast(userId);
19064        }
19065    }
19066
19067    private void postPreferredActivityChangedBroadcast(int userId) {
19068        mHandler.post(() -> {
19069            final IActivityManager am = ActivityManager.getService();
19070            if (am == null) {
19071                return;
19072            }
19073
19074            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19075            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19076            try {
19077                am.broadcastIntent(null, intent, null, null,
19078                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19079                        null, false, false, userId);
19080            } catch (RemoteException e) {
19081            }
19082        });
19083    }
19084
19085    @Override
19086    public void replacePreferredActivity(IntentFilter filter, int match,
19087            ComponentName[] set, ComponentName activity, int userId) {
19088        if (filter.countActions() != 1) {
19089            throw new IllegalArgumentException(
19090                    "replacePreferredActivity expects filter to have only 1 action.");
19091        }
19092        if (filter.countDataAuthorities() != 0
19093                || filter.countDataPaths() != 0
19094                || filter.countDataSchemes() > 1
19095                || filter.countDataTypes() != 0) {
19096            throw new IllegalArgumentException(
19097                    "replacePreferredActivity expects filter to have no data authorities, " +
19098                    "paths, or types; and at most one scheme.");
19099        }
19100
19101        final int callingUid = Binder.getCallingUid();
19102        enforceCrossUserPermission(callingUid, userId,
19103                true /* requireFullPermission */, false /* checkShell */,
19104                "replace preferred activity");
19105        synchronized (mPackages) {
19106            if (mContext.checkCallingOrSelfPermission(
19107                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19108                    != PackageManager.PERMISSION_GRANTED) {
19109                if (getUidTargetSdkVersionLockedLPr(callingUid)
19110                        < Build.VERSION_CODES.FROYO) {
19111                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19112                            + Binder.getCallingUid());
19113                    return;
19114                }
19115                mContext.enforceCallingOrSelfPermission(
19116                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19117            }
19118
19119            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19120            if (pir != null) {
19121                // Get all of the existing entries that exactly match this filter.
19122                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19123                if (existing != null && existing.size() == 1) {
19124                    PreferredActivity cur = existing.get(0);
19125                    if (DEBUG_PREFERRED) {
19126                        Slog.i(TAG, "Checking replace of preferred:");
19127                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19128                        if (!cur.mPref.mAlways) {
19129                            Slog.i(TAG, "  -- CUR; not mAlways!");
19130                        } else {
19131                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19132                            Slog.i(TAG, "  -- CUR: mSet="
19133                                    + Arrays.toString(cur.mPref.mSetComponents));
19134                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19135                            Slog.i(TAG, "  -- NEW: mMatch="
19136                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19137                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19138                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19139                        }
19140                    }
19141                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19142                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19143                            && cur.mPref.sameSet(set)) {
19144                        // Setting the preferred activity to what it happens to be already
19145                        if (DEBUG_PREFERRED) {
19146                            Slog.i(TAG, "Replacing with same preferred activity "
19147                                    + cur.mPref.mShortComponent + " for user "
19148                                    + userId + ":");
19149                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19150                        }
19151                        return;
19152                    }
19153                }
19154
19155                if (existing != null) {
19156                    if (DEBUG_PREFERRED) {
19157                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19158                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19159                    }
19160                    for (int i = 0; i < existing.size(); i++) {
19161                        PreferredActivity pa = existing.get(i);
19162                        if (DEBUG_PREFERRED) {
19163                            Slog.i(TAG, "Removing existing preferred activity "
19164                                    + pa.mPref.mComponent + ":");
19165                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19166                        }
19167                        pir.removeFilter(pa);
19168                    }
19169                }
19170            }
19171            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19172                    "Replacing preferred");
19173        }
19174    }
19175
19176    @Override
19177    public void clearPackagePreferredActivities(String packageName) {
19178        final int uid = Binder.getCallingUid();
19179        // writer
19180        synchronized (mPackages) {
19181            PackageParser.Package pkg = mPackages.get(packageName);
19182            if (pkg == null || pkg.applicationInfo.uid != uid) {
19183                if (mContext.checkCallingOrSelfPermission(
19184                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19185                        != PackageManager.PERMISSION_GRANTED) {
19186                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
19187                            < Build.VERSION_CODES.FROYO) {
19188                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19189                                + Binder.getCallingUid());
19190                        return;
19191                    }
19192                    mContext.enforceCallingOrSelfPermission(
19193                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19194                }
19195            }
19196
19197            int user = UserHandle.getCallingUserId();
19198            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19199                scheduleWritePackageRestrictionsLocked(user);
19200            }
19201        }
19202    }
19203
19204    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19205    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19206        ArrayList<PreferredActivity> removed = null;
19207        boolean changed = false;
19208        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19209            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19210            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19211            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19212                continue;
19213            }
19214            Iterator<PreferredActivity> it = pir.filterIterator();
19215            while (it.hasNext()) {
19216                PreferredActivity pa = it.next();
19217                // Mark entry for removal only if it matches the package name
19218                // and the entry is of type "always".
19219                if (packageName == null ||
19220                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19221                                && pa.mPref.mAlways)) {
19222                    if (removed == null) {
19223                        removed = new ArrayList<PreferredActivity>();
19224                    }
19225                    removed.add(pa);
19226                }
19227            }
19228            if (removed != null) {
19229                for (int j=0; j<removed.size(); j++) {
19230                    PreferredActivity pa = removed.get(j);
19231                    pir.removeFilter(pa);
19232                }
19233                changed = true;
19234            }
19235        }
19236        if (changed) {
19237            postPreferredActivityChangedBroadcast(userId);
19238        }
19239        return changed;
19240    }
19241
19242    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19243    private void clearIntentFilterVerificationsLPw(int userId) {
19244        final int packageCount = mPackages.size();
19245        for (int i = 0; i < packageCount; i++) {
19246            PackageParser.Package pkg = mPackages.valueAt(i);
19247            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19248        }
19249    }
19250
19251    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19252    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19253        if (userId == UserHandle.USER_ALL) {
19254            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19255                    sUserManager.getUserIds())) {
19256                for (int oneUserId : sUserManager.getUserIds()) {
19257                    scheduleWritePackageRestrictionsLocked(oneUserId);
19258                }
19259            }
19260        } else {
19261            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19262                scheduleWritePackageRestrictionsLocked(userId);
19263            }
19264        }
19265    }
19266
19267    void clearDefaultBrowserIfNeeded(String packageName) {
19268        for (int oneUserId : sUserManager.getUserIds()) {
19269            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19270            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19271            if (packageName.equals(defaultBrowserPackageName)) {
19272                setDefaultBrowserPackageName(null, oneUserId);
19273            }
19274        }
19275    }
19276
19277    @Override
19278    public void resetApplicationPreferences(int userId) {
19279        mContext.enforceCallingOrSelfPermission(
19280                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19281        final long identity = Binder.clearCallingIdentity();
19282        // writer
19283        try {
19284            synchronized (mPackages) {
19285                clearPackagePreferredActivitiesLPw(null, userId);
19286                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19287                // TODO: We have to reset the default SMS and Phone. This requires
19288                // significant refactoring to keep all default apps in the package
19289                // manager (cleaner but more work) or have the services provide
19290                // callbacks to the package manager to request a default app reset.
19291                applyFactoryDefaultBrowserLPw(userId);
19292                clearIntentFilterVerificationsLPw(userId);
19293                primeDomainVerificationsLPw(userId);
19294                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19295                scheduleWritePackageRestrictionsLocked(userId);
19296            }
19297            resetNetworkPolicies(userId);
19298        } finally {
19299            Binder.restoreCallingIdentity(identity);
19300        }
19301    }
19302
19303    @Override
19304    public int getPreferredActivities(List<IntentFilter> outFilters,
19305            List<ComponentName> outActivities, String packageName) {
19306
19307        int num = 0;
19308        final int userId = UserHandle.getCallingUserId();
19309        // reader
19310        synchronized (mPackages) {
19311            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19312            if (pir != null) {
19313                final Iterator<PreferredActivity> it = pir.filterIterator();
19314                while (it.hasNext()) {
19315                    final PreferredActivity pa = it.next();
19316                    if (packageName == null
19317                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19318                                    && pa.mPref.mAlways)) {
19319                        if (outFilters != null) {
19320                            outFilters.add(new IntentFilter(pa));
19321                        }
19322                        if (outActivities != null) {
19323                            outActivities.add(pa.mPref.mComponent);
19324                        }
19325                    }
19326                }
19327            }
19328        }
19329
19330        return num;
19331    }
19332
19333    @Override
19334    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19335            int userId) {
19336        int callingUid = Binder.getCallingUid();
19337        if (callingUid != Process.SYSTEM_UID) {
19338            throw new SecurityException(
19339                    "addPersistentPreferredActivity can only be run by the system");
19340        }
19341        if (filter.countActions() == 0) {
19342            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19343            return;
19344        }
19345        synchronized (mPackages) {
19346            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19347                    ":");
19348            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19349            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19350                    new PersistentPreferredActivity(filter, activity));
19351            scheduleWritePackageRestrictionsLocked(userId);
19352            postPreferredActivityChangedBroadcast(userId);
19353        }
19354    }
19355
19356    @Override
19357    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19358        int callingUid = Binder.getCallingUid();
19359        if (callingUid != Process.SYSTEM_UID) {
19360            throw new SecurityException(
19361                    "clearPackagePersistentPreferredActivities can only be run by the system");
19362        }
19363        ArrayList<PersistentPreferredActivity> removed = null;
19364        boolean changed = false;
19365        synchronized (mPackages) {
19366            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19367                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19368                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19369                        .valueAt(i);
19370                if (userId != thisUserId) {
19371                    continue;
19372                }
19373                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19374                while (it.hasNext()) {
19375                    PersistentPreferredActivity ppa = it.next();
19376                    // Mark entry for removal only if it matches the package name.
19377                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19378                        if (removed == null) {
19379                            removed = new ArrayList<PersistentPreferredActivity>();
19380                        }
19381                        removed.add(ppa);
19382                    }
19383                }
19384                if (removed != null) {
19385                    for (int j=0; j<removed.size(); j++) {
19386                        PersistentPreferredActivity ppa = removed.get(j);
19387                        ppir.removeFilter(ppa);
19388                    }
19389                    changed = true;
19390                }
19391            }
19392
19393            if (changed) {
19394                scheduleWritePackageRestrictionsLocked(userId);
19395                postPreferredActivityChangedBroadcast(userId);
19396            }
19397        }
19398    }
19399
19400    /**
19401     * Common machinery for picking apart a restored XML blob and passing
19402     * it to a caller-supplied functor to be applied to the running system.
19403     */
19404    private void restoreFromXml(XmlPullParser parser, int userId,
19405            String expectedStartTag, BlobXmlRestorer functor)
19406            throws IOException, XmlPullParserException {
19407        int type;
19408        while ((type = parser.next()) != XmlPullParser.START_TAG
19409                && type != XmlPullParser.END_DOCUMENT) {
19410        }
19411        if (type != XmlPullParser.START_TAG) {
19412            // oops didn't find a start tag?!
19413            if (DEBUG_BACKUP) {
19414                Slog.e(TAG, "Didn't find start tag during restore");
19415            }
19416            return;
19417        }
19418Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19419        // this is supposed to be TAG_PREFERRED_BACKUP
19420        if (!expectedStartTag.equals(parser.getName())) {
19421            if (DEBUG_BACKUP) {
19422                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19423            }
19424            return;
19425        }
19426
19427        // skip interfering stuff, then we're aligned with the backing implementation
19428        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19429Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19430        functor.apply(parser, userId);
19431    }
19432
19433    private interface BlobXmlRestorer {
19434        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19435    }
19436
19437    /**
19438     * Non-Binder method, support for the backup/restore mechanism: write the
19439     * full set of preferred activities in its canonical XML format.  Returns the
19440     * XML output as a byte array, or null if there is none.
19441     */
19442    @Override
19443    public byte[] getPreferredActivityBackup(int userId) {
19444        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19445            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19446        }
19447
19448        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19449        try {
19450            final XmlSerializer serializer = new FastXmlSerializer();
19451            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19452            serializer.startDocument(null, true);
19453            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19454
19455            synchronized (mPackages) {
19456                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19457            }
19458
19459            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19460            serializer.endDocument();
19461            serializer.flush();
19462        } catch (Exception e) {
19463            if (DEBUG_BACKUP) {
19464                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19465            }
19466            return null;
19467        }
19468
19469        return dataStream.toByteArray();
19470    }
19471
19472    @Override
19473    public void restorePreferredActivities(byte[] backup, int userId) {
19474        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19475            throw new SecurityException("Only the system may call restorePreferredActivities()");
19476        }
19477
19478        try {
19479            final XmlPullParser parser = Xml.newPullParser();
19480            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19481            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19482                    new BlobXmlRestorer() {
19483                        @Override
19484                        public void apply(XmlPullParser parser, int userId)
19485                                throws XmlPullParserException, IOException {
19486                            synchronized (mPackages) {
19487                                mSettings.readPreferredActivitiesLPw(parser, userId);
19488                            }
19489                        }
19490                    } );
19491        } catch (Exception e) {
19492            if (DEBUG_BACKUP) {
19493                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19494            }
19495        }
19496    }
19497
19498    /**
19499     * Non-Binder method, support for the backup/restore mechanism: write the
19500     * default browser (etc) settings in its canonical XML format.  Returns the default
19501     * browser XML representation as a byte array, or null if there is none.
19502     */
19503    @Override
19504    public byte[] getDefaultAppsBackup(int userId) {
19505        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19506            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19507        }
19508
19509        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19510        try {
19511            final XmlSerializer serializer = new FastXmlSerializer();
19512            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19513            serializer.startDocument(null, true);
19514            serializer.startTag(null, TAG_DEFAULT_APPS);
19515
19516            synchronized (mPackages) {
19517                mSettings.writeDefaultAppsLPr(serializer, userId);
19518            }
19519
19520            serializer.endTag(null, TAG_DEFAULT_APPS);
19521            serializer.endDocument();
19522            serializer.flush();
19523        } catch (Exception e) {
19524            if (DEBUG_BACKUP) {
19525                Slog.e(TAG, "Unable to write default apps for backup", e);
19526            }
19527            return null;
19528        }
19529
19530        return dataStream.toByteArray();
19531    }
19532
19533    @Override
19534    public void restoreDefaultApps(byte[] backup, int userId) {
19535        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19536            throw new SecurityException("Only the system may call restoreDefaultApps()");
19537        }
19538
19539        try {
19540            final XmlPullParser parser = Xml.newPullParser();
19541            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19542            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19543                    new BlobXmlRestorer() {
19544                        @Override
19545                        public void apply(XmlPullParser parser, int userId)
19546                                throws XmlPullParserException, IOException {
19547                            synchronized (mPackages) {
19548                                mSettings.readDefaultAppsLPw(parser, userId);
19549                            }
19550                        }
19551                    } );
19552        } catch (Exception e) {
19553            if (DEBUG_BACKUP) {
19554                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19555            }
19556        }
19557    }
19558
19559    @Override
19560    public byte[] getIntentFilterVerificationBackup(int userId) {
19561        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19562            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19563        }
19564
19565        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19566        try {
19567            final XmlSerializer serializer = new FastXmlSerializer();
19568            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19569            serializer.startDocument(null, true);
19570            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19571
19572            synchronized (mPackages) {
19573                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19574            }
19575
19576            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19577            serializer.endDocument();
19578            serializer.flush();
19579        } catch (Exception e) {
19580            if (DEBUG_BACKUP) {
19581                Slog.e(TAG, "Unable to write default apps for backup", e);
19582            }
19583            return null;
19584        }
19585
19586        return dataStream.toByteArray();
19587    }
19588
19589    @Override
19590    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19591        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19592            throw new SecurityException("Only the system may call restorePreferredActivities()");
19593        }
19594
19595        try {
19596            final XmlPullParser parser = Xml.newPullParser();
19597            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19598            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19599                    new BlobXmlRestorer() {
19600                        @Override
19601                        public void apply(XmlPullParser parser, int userId)
19602                                throws XmlPullParserException, IOException {
19603                            synchronized (mPackages) {
19604                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19605                                mSettings.writeLPr();
19606                            }
19607                        }
19608                    } );
19609        } catch (Exception e) {
19610            if (DEBUG_BACKUP) {
19611                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19612            }
19613        }
19614    }
19615
19616    @Override
19617    public byte[] getPermissionGrantBackup(int userId) {
19618        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19619            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19620        }
19621
19622        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19623        try {
19624            final XmlSerializer serializer = new FastXmlSerializer();
19625            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19626            serializer.startDocument(null, true);
19627            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19628
19629            synchronized (mPackages) {
19630                serializeRuntimePermissionGrantsLPr(serializer, userId);
19631            }
19632
19633            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19634            serializer.endDocument();
19635            serializer.flush();
19636        } catch (Exception e) {
19637            if (DEBUG_BACKUP) {
19638                Slog.e(TAG, "Unable to write default apps for backup", e);
19639            }
19640            return null;
19641        }
19642
19643        return dataStream.toByteArray();
19644    }
19645
19646    @Override
19647    public void restorePermissionGrants(byte[] backup, int userId) {
19648        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19649            throw new SecurityException("Only the system may call restorePermissionGrants()");
19650        }
19651
19652        try {
19653            final XmlPullParser parser = Xml.newPullParser();
19654            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19655            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19656                    new BlobXmlRestorer() {
19657                        @Override
19658                        public void apply(XmlPullParser parser, int userId)
19659                                throws XmlPullParserException, IOException {
19660                            synchronized (mPackages) {
19661                                processRestoredPermissionGrantsLPr(parser, userId);
19662                            }
19663                        }
19664                    } );
19665        } catch (Exception e) {
19666            if (DEBUG_BACKUP) {
19667                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19668            }
19669        }
19670    }
19671
19672    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19673            throws IOException {
19674        serializer.startTag(null, TAG_ALL_GRANTS);
19675
19676        final int N = mSettings.mPackages.size();
19677        for (int i = 0; i < N; i++) {
19678            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19679            boolean pkgGrantsKnown = false;
19680
19681            PermissionsState packagePerms = ps.getPermissionsState();
19682
19683            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19684                final int grantFlags = state.getFlags();
19685                // only look at grants that are not system/policy fixed
19686                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19687                    final boolean isGranted = state.isGranted();
19688                    // And only back up the user-twiddled state bits
19689                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19690                        final String packageName = mSettings.mPackages.keyAt(i);
19691                        if (!pkgGrantsKnown) {
19692                            serializer.startTag(null, TAG_GRANT);
19693                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19694                            pkgGrantsKnown = true;
19695                        }
19696
19697                        final boolean userSet =
19698                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19699                        final boolean userFixed =
19700                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19701                        final boolean revoke =
19702                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19703
19704                        serializer.startTag(null, TAG_PERMISSION);
19705                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19706                        if (isGranted) {
19707                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19708                        }
19709                        if (userSet) {
19710                            serializer.attribute(null, ATTR_USER_SET, "true");
19711                        }
19712                        if (userFixed) {
19713                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19714                        }
19715                        if (revoke) {
19716                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19717                        }
19718                        serializer.endTag(null, TAG_PERMISSION);
19719                    }
19720                }
19721            }
19722
19723            if (pkgGrantsKnown) {
19724                serializer.endTag(null, TAG_GRANT);
19725            }
19726        }
19727
19728        serializer.endTag(null, TAG_ALL_GRANTS);
19729    }
19730
19731    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19732            throws XmlPullParserException, IOException {
19733        String pkgName = null;
19734        int outerDepth = parser.getDepth();
19735        int type;
19736        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19737                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19738            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19739                continue;
19740            }
19741
19742            final String tagName = parser.getName();
19743            if (tagName.equals(TAG_GRANT)) {
19744                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19745                if (DEBUG_BACKUP) {
19746                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19747                }
19748            } else if (tagName.equals(TAG_PERMISSION)) {
19749
19750                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19751                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19752
19753                int newFlagSet = 0;
19754                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19755                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19756                }
19757                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19758                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19759                }
19760                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19761                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19762                }
19763                if (DEBUG_BACKUP) {
19764                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19765                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19766                }
19767                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19768                if (ps != null) {
19769                    // Already installed so we apply the grant immediately
19770                    if (DEBUG_BACKUP) {
19771                        Slog.v(TAG, "        + already installed; applying");
19772                    }
19773                    PermissionsState perms = ps.getPermissionsState();
19774                    BasePermission bp = mSettings.mPermissions.get(permName);
19775                    if (bp != null) {
19776                        if (isGranted) {
19777                            perms.grantRuntimePermission(bp, userId);
19778                        }
19779                        if (newFlagSet != 0) {
19780                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19781                        }
19782                    }
19783                } else {
19784                    // Need to wait for post-restore install to apply the grant
19785                    if (DEBUG_BACKUP) {
19786                        Slog.v(TAG, "        - not yet installed; saving for later");
19787                    }
19788                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19789                            isGranted, newFlagSet, userId);
19790                }
19791            } else {
19792                PackageManagerService.reportSettingsProblem(Log.WARN,
19793                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19794                XmlUtils.skipCurrentTag(parser);
19795            }
19796        }
19797
19798        scheduleWriteSettingsLocked();
19799        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19800    }
19801
19802    @Override
19803    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19804            int sourceUserId, int targetUserId, int flags) {
19805        mContext.enforceCallingOrSelfPermission(
19806                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19807        int callingUid = Binder.getCallingUid();
19808        enforceOwnerRights(ownerPackage, callingUid);
19809        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19810        if (intentFilter.countActions() == 0) {
19811            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19812            return;
19813        }
19814        synchronized (mPackages) {
19815            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19816                    ownerPackage, targetUserId, flags);
19817            CrossProfileIntentResolver resolver =
19818                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19819            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19820            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19821            if (existing != null) {
19822                int size = existing.size();
19823                for (int i = 0; i < size; i++) {
19824                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19825                        return;
19826                    }
19827                }
19828            }
19829            resolver.addFilter(newFilter);
19830            scheduleWritePackageRestrictionsLocked(sourceUserId);
19831        }
19832    }
19833
19834    @Override
19835    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19836        mContext.enforceCallingOrSelfPermission(
19837                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19838        int callingUid = Binder.getCallingUid();
19839        enforceOwnerRights(ownerPackage, callingUid);
19840        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19841        synchronized (mPackages) {
19842            CrossProfileIntentResolver resolver =
19843                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19844            ArraySet<CrossProfileIntentFilter> set =
19845                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19846            for (CrossProfileIntentFilter filter : set) {
19847                if (filter.getOwnerPackage().equals(ownerPackage)) {
19848                    resolver.removeFilter(filter);
19849                }
19850            }
19851            scheduleWritePackageRestrictionsLocked(sourceUserId);
19852        }
19853    }
19854
19855    // Enforcing that callingUid is owning pkg on userId
19856    private void enforceOwnerRights(String pkg, int callingUid) {
19857        // The system owns everything.
19858        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19859            return;
19860        }
19861        int callingUserId = UserHandle.getUserId(callingUid);
19862        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19863        if (pi == null) {
19864            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19865                    + callingUserId);
19866        }
19867        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19868            throw new SecurityException("Calling uid " + callingUid
19869                    + " does not own package " + pkg);
19870        }
19871    }
19872
19873    @Override
19874    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19875        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19876    }
19877
19878    /**
19879     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19880     * then reports the most likely home activity or null if there are more than one.
19881     */
19882    public ComponentName getDefaultHomeActivity(int userId) {
19883        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19884        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19885        if (cn != null) {
19886            return cn;
19887        }
19888
19889        // Find the launcher with the highest priority and return that component if there are no
19890        // other home activity with the same priority.
19891        int lastPriority = Integer.MIN_VALUE;
19892        ComponentName lastComponent = null;
19893        final int size = allHomeCandidates.size();
19894        for (int i = 0; i < size; i++) {
19895            final ResolveInfo ri = allHomeCandidates.get(i);
19896            if (ri.priority > lastPriority) {
19897                lastComponent = ri.activityInfo.getComponentName();
19898                lastPriority = ri.priority;
19899            } else if (ri.priority == lastPriority) {
19900                // Two components found with same priority.
19901                lastComponent = null;
19902            }
19903        }
19904        return lastComponent;
19905    }
19906
19907    private Intent getHomeIntent() {
19908        Intent intent = new Intent(Intent.ACTION_MAIN);
19909        intent.addCategory(Intent.CATEGORY_HOME);
19910        intent.addCategory(Intent.CATEGORY_DEFAULT);
19911        return intent;
19912    }
19913
19914    private IntentFilter getHomeFilter() {
19915        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19916        filter.addCategory(Intent.CATEGORY_HOME);
19917        filter.addCategory(Intent.CATEGORY_DEFAULT);
19918        return filter;
19919    }
19920
19921    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19922            int userId) {
19923        Intent intent  = getHomeIntent();
19924        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19925                PackageManager.GET_META_DATA, userId);
19926        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19927                true, false, false, userId);
19928
19929        allHomeCandidates.clear();
19930        if (list != null) {
19931            for (ResolveInfo ri : list) {
19932                allHomeCandidates.add(ri);
19933            }
19934        }
19935        return (preferred == null || preferred.activityInfo == null)
19936                ? null
19937                : new ComponentName(preferred.activityInfo.packageName,
19938                        preferred.activityInfo.name);
19939    }
19940
19941    @Override
19942    public void setHomeActivity(ComponentName comp, int userId) {
19943        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19944        getHomeActivitiesAsUser(homeActivities, userId);
19945
19946        boolean found = false;
19947
19948        final int size = homeActivities.size();
19949        final ComponentName[] set = new ComponentName[size];
19950        for (int i = 0; i < size; i++) {
19951            final ResolveInfo candidate = homeActivities.get(i);
19952            final ActivityInfo info = candidate.activityInfo;
19953            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19954            set[i] = activityName;
19955            if (!found && activityName.equals(comp)) {
19956                found = true;
19957            }
19958        }
19959        if (!found) {
19960            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19961                    + userId);
19962        }
19963        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19964                set, comp, userId);
19965    }
19966
19967    private @Nullable String getSetupWizardPackageName() {
19968        final Intent intent = new Intent(Intent.ACTION_MAIN);
19969        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19970
19971        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19972                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19973                        | MATCH_DISABLED_COMPONENTS,
19974                UserHandle.myUserId());
19975        if (matches.size() == 1) {
19976            return matches.get(0).getComponentInfo().packageName;
19977        } else {
19978            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19979                    + ": matches=" + matches);
19980            return null;
19981        }
19982    }
19983
19984    private @Nullable String getStorageManagerPackageName() {
19985        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19986
19987        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19988                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19989                        | MATCH_DISABLED_COMPONENTS,
19990                UserHandle.myUserId());
19991        if (matches.size() == 1) {
19992            return matches.get(0).getComponentInfo().packageName;
19993        } else {
19994            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19995                    + matches.size() + ": matches=" + matches);
19996            return null;
19997        }
19998    }
19999
20000    @Override
20001    public void setApplicationEnabledSetting(String appPackageName,
20002            int newState, int flags, int userId, String callingPackage) {
20003        if (!sUserManager.exists(userId)) return;
20004        if (callingPackage == null) {
20005            callingPackage = Integer.toString(Binder.getCallingUid());
20006        }
20007        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20008    }
20009
20010    @Override
20011    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20012        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20013        synchronized (mPackages) {
20014            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20015            if (pkgSetting != null) {
20016                pkgSetting.setUpdateAvailable(updateAvailable);
20017            }
20018        }
20019    }
20020
20021    @Override
20022    public void setComponentEnabledSetting(ComponentName componentName,
20023            int newState, int flags, int userId) {
20024        if (!sUserManager.exists(userId)) return;
20025        setEnabledSetting(componentName.getPackageName(),
20026                componentName.getClassName(), newState, flags, userId, null);
20027    }
20028
20029    private void setEnabledSetting(final String packageName, String className, int newState,
20030            final int flags, int userId, String callingPackage) {
20031        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20032              || newState == COMPONENT_ENABLED_STATE_ENABLED
20033              || newState == COMPONENT_ENABLED_STATE_DISABLED
20034              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20035              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20036            throw new IllegalArgumentException("Invalid new component state: "
20037                    + newState);
20038        }
20039        PackageSetting pkgSetting;
20040        final int uid = Binder.getCallingUid();
20041        final int permission;
20042        if (uid == Process.SYSTEM_UID) {
20043            permission = PackageManager.PERMISSION_GRANTED;
20044        } else {
20045            permission = mContext.checkCallingOrSelfPermission(
20046                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20047        }
20048        enforceCrossUserPermission(uid, userId,
20049                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20050        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20051        boolean sendNow = false;
20052        boolean isApp = (className == null);
20053        String componentName = isApp ? packageName : className;
20054        int packageUid = -1;
20055        ArrayList<String> components;
20056
20057        // writer
20058        synchronized (mPackages) {
20059            pkgSetting = mSettings.mPackages.get(packageName);
20060            if (pkgSetting == null) {
20061                if (className == null) {
20062                    throw new IllegalArgumentException("Unknown package: " + packageName);
20063                }
20064                throw new IllegalArgumentException(
20065                        "Unknown component: " + packageName + "/" + className);
20066            }
20067        }
20068
20069        // Limit who can change which apps
20070        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
20071            // Don't allow apps that don't have permission to modify other apps
20072            if (!allowedByPermission) {
20073                throw new SecurityException(
20074                        "Permission Denial: attempt to change component state from pid="
20075                        + Binder.getCallingPid()
20076                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
20077            }
20078            // Don't allow changing protected packages.
20079            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20080                throw new SecurityException("Cannot disable a protected package: " + packageName);
20081            }
20082        }
20083
20084        synchronized (mPackages) {
20085            if (uid == Process.SHELL_UID
20086                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20087                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20088                // unless it is a test package.
20089                int oldState = pkgSetting.getEnabled(userId);
20090                if (className == null
20091                    &&
20092                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20093                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20094                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20095                    &&
20096                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20097                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20098                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20099                    // ok
20100                } else {
20101                    throw new SecurityException(
20102                            "Shell cannot change component state for " + packageName + "/"
20103                            + className + " to " + newState);
20104                }
20105            }
20106            if (className == null) {
20107                // We're dealing with an application/package level state change
20108                if (pkgSetting.getEnabled(userId) == newState) {
20109                    // Nothing to do
20110                    return;
20111                }
20112                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20113                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20114                    // Don't care about who enables an app.
20115                    callingPackage = null;
20116                }
20117                pkgSetting.setEnabled(newState, userId, callingPackage);
20118                // pkgSetting.pkg.mSetEnabled = newState;
20119            } else {
20120                // We're dealing with a component level state change
20121                // First, verify that this is a valid class name.
20122                PackageParser.Package pkg = pkgSetting.pkg;
20123                if (pkg == null || !pkg.hasComponentClassName(className)) {
20124                    if (pkg != null &&
20125                            pkg.applicationInfo.targetSdkVersion >=
20126                                    Build.VERSION_CODES.JELLY_BEAN) {
20127                        throw new IllegalArgumentException("Component class " + className
20128                                + " does not exist in " + packageName);
20129                    } else {
20130                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20131                                + className + " does not exist in " + packageName);
20132                    }
20133                }
20134                switch (newState) {
20135                case COMPONENT_ENABLED_STATE_ENABLED:
20136                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20137                        return;
20138                    }
20139                    break;
20140                case COMPONENT_ENABLED_STATE_DISABLED:
20141                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20142                        return;
20143                    }
20144                    break;
20145                case COMPONENT_ENABLED_STATE_DEFAULT:
20146                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20147                        return;
20148                    }
20149                    break;
20150                default:
20151                    Slog.e(TAG, "Invalid new component state: " + newState);
20152                    return;
20153                }
20154            }
20155            scheduleWritePackageRestrictionsLocked(userId);
20156            updateSequenceNumberLP(packageName, new int[] { userId });
20157            final long callingId = Binder.clearCallingIdentity();
20158            try {
20159                updateInstantAppInstallerLocked(packageName);
20160            } finally {
20161                Binder.restoreCallingIdentity(callingId);
20162            }
20163            components = mPendingBroadcasts.get(userId, packageName);
20164            final boolean newPackage = components == null;
20165            if (newPackage) {
20166                components = new ArrayList<String>();
20167            }
20168            if (!components.contains(componentName)) {
20169                components.add(componentName);
20170            }
20171            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20172                sendNow = true;
20173                // Purge entry from pending broadcast list if another one exists already
20174                // since we are sending one right away.
20175                mPendingBroadcasts.remove(userId, packageName);
20176            } else {
20177                if (newPackage) {
20178                    mPendingBroadcasts.put(userId, packageName, components);
20179                }
20180                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20181                    // Schedule a message
20182                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20183                }
20184            }
20185        }
20186
20187        long callingId = Binder.clearCallingIdentity();
20188        try {
20189            if (sendNow) {
20190                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20191                sendPackageChangedBroadcast(packageName,
20192                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20193            }
20194        } finally {
20195            Binder.restoreCallingIdentity(callingId);
20196        }
20197    }
20198
20199    @Override
20200    public void flushPackageRestrictionsAsUser(int userId) {
20201        if (!sUserManager.exists(userId)) {
20202            return;
20203        }
20204        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20205                false /* checkShell */, "flushPackageRestrictions");
20206        synchronized (mPackages) {
20207            mSettings.writePackageRestrictionsLPr(userId);
20208            mDirtyUsers.remove(userId);
20209            if (mDirtyUsers.isEmpty()) {
20210                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20211            }
20212        }
20213    }
20214
20215    private void sendPackageChangedBroadcast(String packageName,
20216            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20217        if (DEBUG_INSTALL)
20218            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20219                    + componentNames);
20220        Bundle extras = new Bundle(4);
20221        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20222        String nameList[] = new String[componentNames.size()];
20223        componentNames.toArray(nameList);
20224        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20225        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20226        extras.putInt(Intent.EXTRA_UID, packageUid);
20227        // If this is not reporting a change of the overall package, then only send it
20228        // to registered receivers.  We don't want to launch a swath of apps for every
20229        // little component state change.
20230        final int flags = !componentNames.contains(packageName)
20231                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20232        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20233                new int[] {UserHandle.getUserId(packageUid)});
20234    }
20235
20236    @Override
20237    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20238        if (!sUserManager.exists(userId)) return;
20239        final int uid = Binder.getCallingUid();
20240        final int permission = mContext.checkCallingOrSelfPermission(
20241                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20242        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20243        enforceCrossUserPermission(uid, userId,
20244                true /* requireFullPermission */, true /* checkShell */, "stop package");
20245        // writer
20246        synchronized (mPackages) {
20247            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20248                    allowedByPermission, uid, userId)) {
20249                scheduleWritePackageRestrictionsLocked(userId);
20250            }
20251        }
20252    }
20253
20254    @Override
20255    public String getInstallerPackageName(String packageName) {
20256        // reader
20257        synchronized (mPackages) {
20258            return mSettings.getInstallerPackageNameLPr(packageName);
20259        }
20260    }
20261
20262    public boolean isOrphaned(String packageName) {
20263        // reader
20264        synchronized (mPackages) {
20265            return mSettings.isOrphaned(packageName);
20266        }
20267    }
20268
20269    @Override
20270    public int getApplicationEnabledSetting(String packageName, int userId) {
20271        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20272        int uid = Binder.getCallingUid();
20273        enforceCrossUserPermission(uid, userId,
20274                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20275        // reader
20276        synchronized (mPackages) {
20277            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20278        }
20279    }
20280
20281    @Override
20282    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20283        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20284        int uid = Binder.getCallingUid();
20285        enforceCrossUserPermission(uid, userId,
20286                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20287        // reader
20288        synchronized (mPackages) {
20289            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20290        }
20291    }
20292
20293    @Override
20294    public void enterSafeMode() {
20295        enforceSystemOrRoot("Only the system can request entering safe mode");
20296
20297        if (!mSystemReady) {
20298            mSafeMode = true;
20299        }
20300    }
20301
20302    @Override
20303    public void systemReady() {
20304        mSystemReady = true;
20305        final ContentResolver resolver = mContext.getContentResolver();
20306        ContentObserver co = new ContentObserver(mHandler) {
20307            @Override
20308            public void onChange(boolean selfChange) {
20309                mEphemeralAppsDisabled =
20310                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20311                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20312            }
20313        };
20314        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20315                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20316                false, co, UserHandle.USER_SYSTEM);
20317        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20318                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20319        co.onChange(true);
20320
20321        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20322        // disabled after already being started.
20323        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20324                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20325
20326        // Read the compatibilty setting when the system is ready.
20327        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20328                mContext.getContentResolver(),
20329                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20330        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20331        if (DEBUG_SETTINGS) {
20332            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20333        }
20334
20335        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20336
20337        synchronized (mPackages) {
20338            // Verify that all of the preferred activity components actually
20339            // exist.  It is possible for applications to be updated and at
20340            // that point remove a previously declared activity component that
20341            // had been set as a preferred activity.  We try to clean this up
20342            // the next time we encounter that preferred activity, but it is
20343            // possible for the user flow to never be able to return to that
20344            // situation so here we do a sanity check to make sure we haven't
20345            // left any junk around.
20346            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20347            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20348                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20349                removed.clear();
20350                for (PreferredActivity pa : pir.filterSet()) {
20351                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20352                        removed.add(pa);
20353                    }
20354                }
20355                if (removed.size() > 0) {
20356                    for (int r=0; r<removed.size(); r++) {
20357                        PreferredActivity pa = removed.get(r);
20358                        Slog.w(TAG, "Removing dangling preferred activity: "
20359                                + pa.mPref.mComponent);
20360                        pir.removeFilter(pa);
20361                    }
20362                    mSettings.writePackageRestrictionsLPr(
20363                            mSettings.mPreferredActivities.keyAt(i));
20364                }
20365            }
20366
20367            for (int userId : UserManagerService.getInstance().getUserIds()) {
20368                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20369                    grantPermissionsUserIds = ArrayUtils.appendInt(
20370                            grantPermissionsUserIds, userId);
20371                }
20372            }
20373        }
20374        sUserManager.systemReady();
20375
20376        // If we upgraded grant all default permissions before kicking off.
20377        for (int userId : grantPermissionsUserIds) {
20378            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20379        }
20380
20381        // If we did not grant default permissions, we preload from this the
20382        // default permission exceptions lazily to ensure we don't hit the
20383        // disk on a new user creation.
20384        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20385            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20386        }
20387
20388        // Kick off any messages waiting for system ready
20389        if (mPostSystemReadyMessages != null) {
20390            for (Message msg : mPostSystemReadyMessages) {
20391                msg.sendToTarget();
20392            }
20393            mPostSystemReadyMessages = null;
20394        }
20395
20396        // Watch for external volumes that come and go over time
20397        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20398        storage.registerListener(mStorageListener);
20399
20400        mInstallerService.systemReady();
20401        mPackageDexOptimizer.systemReady();
20402
20403        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20404                StorageManagerInternal.class);
20405        StorageManagerInternal.addExternalStoragePolicy(
20406                new StorageManagerInternal.ExternalStorageMountPolicy() {
20407            @Override
20408            public int getMountMode(int uid, String packageName) {
20409                if (Process.isIsolated(uid)) {
20410                    return Zygote.MOUNT_EXTERNAL_NONE;
20411                }
20412                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20413                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20414                }
20415                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20416                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20417                }
20418                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20419                    return Zygote.MOUNT_EXTERNAL_READ;
20420                }
20421                return Zygote.MOUNT_EXTERNAL_WRITE;
20422            }
20423
20424            @Override
20425            public boolean hasExternalStorage(int uid, String packageName) {
20426                return true;
20427            }
20428        });
20429
20430        // Now that we're mostly running, clean up stale users and apps
20431        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20432        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20433
20434        if (mPrivappPermissionsViolations != null) {
20435            Slog.wtf(TAG,"Signature|privileged permissions not in "
20436                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20437            mPrivappPermissionsViolations = null;
20438        }
20439    }
20440
20441    public void waitForAppDataPrepared() {
20442        if (mPrepareAppDataFuture == null) {
20443            return;
20444        }
20445        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20446        mPrepareAppDataFuture = null;
20447    }
20448
20449    @Override
20450    public boolean isSafeMode() {
20451        return mSafeMode;
20452    }
20453
20454    @Override
20455    public boolean hasSystemUidErrors() {
20456        return mHasSystemUidErrors;
20457    }
20458
20459    static String arrayToString(int[] array) {
20460        StringBuffer buf = new StringBuffer(128);
20461        buf.append('[');
20462        if (array != null) {
20463            for (int i=0; i<array.length; i++) {
20464                if (i > 0) buf.append(", ");
20465                buf.append(array[i]);
20466            }
20467        }
20468        buf.append(']');
20469        return buf.toString();
20470    }
20471
20472    static class DumpState {
20473        public static final int DUMP_LIBS = 1 << 0;
20474        public static final int DUMP_FEATURES = 1 << 1;
20475        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20476        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20477        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20478        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20479        public static final int DUMP_PERMISSIONS = 1 << 6;
20480        public static final int DUMP_PACKAGES = 1 << 7;
20481        public static final int DUMP_SHARED_USERS = 1 << 8;
20482        public static final int DUMP_MESSAGES = 1 << 9;
20483        public static final int DUMP_PROVIDERS = 1 << 10;
20484        public static final int DUMP_VERIFIERS = 1 << 11;
20485        public static final int DUMP_PREFERRED = 1 << 12;
20486        public static final int DUMP_PREFERRED_XML = 1 << 13;
20487        public static final int DUMP_KEYSETS = 1 << 14;
20488        public static final int DUMP_VERSION = 1 << 15;
20489        public static final int DUMP_INSTALLS = 1 << 16;
20490        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20491        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20492        public static final int DUMP_FROZEN = 1 << 19;
20493        public static final int DUMP_DEXOPT = 1 << 20;
20494        public static final int DUMP_COMPILER_STATS = 1 << 21;
20495        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20496
20497        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20498
20499        private int mTypes;
20500
20501        private int mOptions;
20502
20503        private boolean mTitlePrinted;
20504
20505        private SharedUserSetting mSharedUser;
20506
20507        public boolean isDumping(int type) {
20508            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20509                return true;
20510            }
20511
20512            return (mTypes & type) != 0;
20513        }
20514
20515        public void setDump(int type) {
20516            mTypes |= type;
20517        }
20518
20519        public boolean isOptionEnabled(int option) {
20520            return (mOptions & option) != 0;
20521        }
20522
20523        public void setOptionEnabled(int option) {
20524            mOptions |= option;
20525        }
20526
20527        public boolean onTitlePrinted() {
20528            final boolean printed = mTitlePrinted;
20529            mTitlePrinted = true;
20530            return printed;
20531        }
20532
20533        public boolean getTitlePrinted() {
20534            return mTitlePrinted;
20535        }
20536
20537        public void setTitlePrinted(boolean enabled) {
20538            mTitlePrinted = enabled;
20539        }
20540
20541        public SharedUserSetting getSharedUser() {
20542            return mSharedUser;
20543        }
20544
20545        public void setSharedUser(SharedUserSetting user) {
20546            mSharedUser = user;
20547        }
20548    }
20549
20550    @Override
20551    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20552            FileDescriptor err, String[] args, ShellCallback callback,
20553            ResultReceiver resultReceiver) {
20554        (new PackageManagerShellCommand(this)).exec(
20555                this, in, out, err, args, callback, resultReceiver);
20556    }
20557
20558    @Override
20559    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20560        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20561
20562        DumpState dumpState = new DumpState();
20563        boolean fullPreferred = false;
20564        boolean checkin = false;
20565
20566        String packageName = null;
20567        ArraySet<String> permissionNames = null;
20568
20569        int opti = 0;
20570        while (opti < args.length) {
20571            String opt = args[opti];
20572            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20573                break;
20574            }
20575            opti++;
20576
20577            if ("-a".equals(opt)) {
20578                // Right now we only know how to print all.
20579            } else if ("-h".equals(opt)) {
20580                pw.println("Package manager dump options:");
20581                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20582                pw.println("    --checkin: dump for a checkin");
20583                pw.println("    -f: print details of intent filters");
20584                pw.println("    -h: print this help");
20585                pw.println("  cmd may be one of:");
20586                pw.println("    l[ibraries]: list known shared libraries");
20587                pw.println("    f[eatures]: list device features");
20588                pw.println("    k[eysets]: print known keysets");
20589                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20590                pw.println("    perm[issions]: dump permissions");
20591                pw.println("    permission [name ...]: dump declaration and use of given permission");
20592                pw.println("    pref[erred]: print preferred package settings");
20593                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20594                pw.println("    prov[iders]: dump content providers");
20595                pw.println("    p[ackages]: dump installed packages");
20596                pw.println("    s[hared-users]: dump shared user IDs");
20597                pw.println("    m[essages]: print collected runtime messages");
20598                pw.println("    v[erifiers]: print package verifier info");
20599                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20600                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20601                pw.println("    version: print database version info");
20602                pw.println("    write: write current settings now");
20603                pw.println("    installs: details about install sessions");
20604                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20605                pw.println("    dexopt: dump dexopt state");
20606                pw.println("    compiler-stats: dump compiler statistics");
20607                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20608                pw.println("    <package.name>: info about given package");
20609                return;
20610            } else if ("--checkin".equals(opt)) {
20611                checkin = true;
20612            } else if ("-f".equals(opt)) {
20613                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20614            } else if ("--proto".equals(opt)) {
20615                dumpProto(fd);
20616                return;
20617            } else {
20618                pw.println("Unknown argument: " + opt + "; use -h for help");
20619            }
20620        }
20621
20622        // Is the caller requesting to dump a particular piece of data?
20623        if (opti < args.length) {
20624            String cmd = args[opti];
20625            opti++;
20626            // Is this a package name?
20627            if ("android".equals(cmd) || cmd.contains(".")) {
20628                packageName = cmd;
20629                // When dumping a single package, we always dump all of its
20630                // filter information since the amount of data will be reasonable.
20631                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20632            } else if ("check-permission".equals(cmd)) {
20633                if (opti >= args.length) {
20634                    pw.println("Error: check-permission missing permission argument");
20635                    return;
20636                }
20637                String perm = args[opti];
20638                opti++;
20639                if (opti >= args.length) {
20640                    pw.println("Error: check-permission missing package argument");
20641                    return;
20642                }
20643
20644                String pkg = args[opti];
20645                opti++;
20646                int user = UserHandle.getUserId(Binder.getCallingUid());
20647                if (opti < args.length) {
20648                    try {
20649                        user = Integer.parseInt(args[opti]);
20650                    } catch (NumberFormatException e) {
20651                        pw.println("Error: check-permission user argument is not a number: "
20652                                + args[opti]);
20653                        return;
20654                    }
20655                }
20656
20657                // Normalize package name to handle renamed packages and static libs
20658                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20659
20660                pw.println(checkPermission(perm, pkg, user));
20661                return;
20662            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20663                dumpState.setDump(DumpState.DUMP_LIBS);
20664            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20665                dumpState.setDump(DumpState.DUMP_FEATURES);
20666            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20667                if (opti >= args.length) {
20668                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20669                            | DumpState.DUMP_SERVICE_RESOLVERS
20670                            | DumpState.DUMP_RECEIVER_RESOLVERS
20671                            | DumpState.DUMP_CONTENT_RESOLVERS);
20672                } else {
20673                    while (opti < args.length) {
20674                        String name = args[opti];
20675                        if ("a".equals(name) || "activity".equals(name)) {
20676                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20677                        } else if ("s".equals(name) || "service".equals(name)) {
20678                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20679                        } else if ("r".equals(name) || "receiver".equals(name)) {
20680                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20681                        } else if ("c".equals(name) || "content".equals(name)) {
20682                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20683                        } else {
20684                            pw.println("Error: unknown resolver table type: " + name);
20685                            return;
20686                        }
20687                        opti++;
20688                    }
20689                }
20690            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20691                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20692            } else if ("permission".equals(cmd)) {
20693                if (opti >= args.length) {
20694                    pw.println("Error: permission requires permission name");
20695                    return;
20696                }
20697                permissionNames = new ArraySet<>();
20698                while (opti < args.length) {
20699                    permissionNames.add(args[opti]);
20700                    opti++;
20701                }
20702                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20703                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20704            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20705                dumpState.setDump(DumpState.DUMP_PREFERRED);
20706            } else if ("preferred-xml".equals(cmd)) {
20707                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20708                if (opti < args.length && "--full".equals(args[opti])) {
20709                    fullPreferred = true;
20710                    opti++;
20711                }
20712            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20713                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20714            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20715                dumpState.setDump(DumpState.DUMP_PACKAGES);
20716            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20717                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20718            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20719                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20720            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20721                dumpState.setDump(DumpState.DUMP_MESSAGES);
20722            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20723                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20724            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20725                    || "intent-filter-verifiers".equals(cmd)) {
20726                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20727            } else if ("version".equals(cmd)) {
20728                dumpState.setDump(DumpState.DUMP_VERSION);
20729            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20730                dumpState.setDump(DumpState.DUMP_KEYSETS);
20731            } else if ("installs".equals(cmd)) {
20732                dumpState.setDump(DumpState.DUMP_INSTALLS);
20733            } else if ("frozen".equals(cmd)) {
20734                dumpState.setDump(DumpState.DUMP_FROZEN);
20735            } else if ("dexopt".equals(cmd)) {
20736                dumpState.setDump(DumpState.DUMP_DEXOPT);
20737            } else if ("compiler-stats".equals(cmd)) {
20738                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20739            } else if ("enabled-overlays".equals(cmd)) {
20740                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20741            } else if ("write".equals(cmd)) {
20742                synchronized (mPackages) {
20743                    mSettings.writeLPr();
20744                    pw.println("Settings written.");
20745                    return;
20746                }
20747            }
20748        }
20749
20750        if (checkin) {
20751            pw.println("vers,1");
20752        }
20753
20754        // reader
20755        synchronized (mPackages) {
20756            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20757                if (!checkin) {
20758                    if (dumpState.onTitlePrinted())
20759                        pw.println();
20760                    pw.println("Database versions:");
20761                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20762                }
20763            }
20764
20765            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20766                if (!checkin) {
20767                    if (dumpState.onTitlePrinted())
20768                        pw.println();
20769                    pw.println("Verifiers:");
20770                    pw.print("  Required: ");
20771                    pw.print(mRequiredVerifierPackage);
20772                    pw.print(" (uid=");
20773                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20774                            UserHandle.USER_SYSTEM));
20775                    pw.println(")");
20776                } else if (mRequiredVerifierPackage != null) {
20777                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20778                    pw.print(",");
20779                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20780                            UserHandle.USER_SYSTEM));
20781                }
20782            }
20783
20784            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20785                    packageName == null) {
20786                if (mIntentFilterVerifierComponent != null) {
20787                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20788                    if (!checkin) {
20789                        if (dumpState.onTitlePrinted())
20790                            pw.println();
20791                        pw.println("Intent Filter Verifier:");
20792                        pw.print("  Using: ");
20793                        pw.print(verifierPackageName);
20794                        pw.print(" (uid=");
20795                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20796                                UserHandle.USER_SYSTEM));
20797                        pw.println(")");
20798                    } else if (verifierPackageName != null) {
20799                        pw.print("ifv,"); pw.print(verifierPackageName);
20800                        pw.print(",");
20801                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20802                                UserHandle.USER_SYSTEM));
20803                    }
20804                } else {
20805                    pw.println();
20806                    pw.println("No Intent Filter Verifier available!");
20807                }
20808            }
20809
20810            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20811                boolean printedHeader = false;
20812                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20813                while (it.hasNext()) {
20814                    String libName = it.next();
20815                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20816                    if (versionedLib == null) {
20817                        continue;
20818                    }
20819                    final int versionCount = versionedLib.size();
20820                    for (int i = 0; i < versionCount; i++) {
20821                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20822                        if (!checkin) {
20823                            if (!printedHeader) {
20824                                if (dumpState.onTitlePrinted())
20825                                    pw.println();
20826                                pw.println("Libraries:");
20827                                printedHeader = true;
20828                            }
20829                            pw.print("  ");
20830                        } else {
20831                            pw.print("lib,");
20832                        }
20833                        pw.print(libEntry.info.getName());
20834                        if (libEntry.info.isStatic()) {
20835                            pw.print(" version=" + libEntry.info.getVersion());
20836                        }
20837                        if (!checkin) {
20838                            pw.print(" -> ");
20839                        }
20840                        if (libEntry.path != null) {
20841                            pw.print(" (jar) ");
20842                            pw.print(libEntry.path);
20843                        } else {
20844                            pw.print(" (apk) ");
20845                            pw.print(libEntry.apk);
20846                        }
20847                        pw.println();
20848                    }
20849                }
20850            }
20851
20852            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20853                if (dumpState.onTitlePrinted())
20854                    pw.println();
20855                if (!checkin) {
20856                    pw.println("Features:");
20857                }
20858
20859                synchronized (mAvailableFeatures) {
20860                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20861                        if (checkin) {
20862                            pw.print("feat,");
20863                            pw.print(feat.name);
20864                            pw.print(",");
20865                            pw.println(feat.version);
20866                        } else {
20867                            pw.print("  ");
20868                            pw.print(feat.name);
20869                            if (feat.version > 0) {
20870                                pw.print(" version=");
20871                                pw.print(feat.version);
20872                            }
20873                            pw.println();
20874                        }
20875                    }
20876                }
20877            }
20878
20879            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20880                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20881                        : "Activity Resolver Table:", "  ", packageName,
20882                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20883                    dumpState.setTitlePrinted(true);
20884                }
20885            }
20886            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20887                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20888                        : "Receiver Resolver Table:", "  ", packageName,
20889                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20890                    dumpState.setTitlePrinted(true);
20891                }
20892            }
20893            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20894                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20895                        : "Service Resolver Table:", "  ", packageName,
20896                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20897                    dumpState.setTitlePrinted(true);
20898                }
20899            }
20900            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20901                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20902                        : "Provider Resolver Table:", "  ", packageName,
20903                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20904                    dumpState.setTitlePrinted(true);
20905                }
20906            }
20907
20908            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20909                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20910                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20911                    int user = mSettings.mPreferredActivities.keyAt(i);
20912                    if (pir.dump(pw,
20913                            dumpState.getTitlePrinted()
20914                                ? "\nPreferred Activities User " + user + ":"
20915                                : "Preferred Activities User " + user + ":", "  ",
20916                            packageName, true, false)) {
20917                        dumpState.setTitlePrinted(true);
20918                    }
20919                }
20920            }
20921
20922            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20923                pw.flush();
20924                FileOutputStream fout = new FileOutputStream(fd);
20925                BufferedOutputStream str = new BufferedOutputStream(fout);
20926                XmlSerializer serializer = new FastXmlSerializer();
20927                try {
20928                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20929                    serializer.startDocument(null, true);
20930                    serializer.setFeature(
20931                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20932                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20933                    serializer.endDocument();
20934                    serializer.flush();
20935                } catch (IllegalArgumentException e) {
20936                    pw.println("Failed writing: " + e);
20937                } catch (IllegalStateException e) {
20938                    pw.println("Failed writing: " + e);
20939                } catch (IOException e) {
20940                    pw.println("Failed writing: " + e);
20941                }
20942            }
20943
20944            if (!checkin
20945                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20946                    && packageName == null) {
20947                pw.println();
20948                int count = mSettings.mPackages.size();
20949                if (count == 0) {
20950                    pw.println("No applications!");
20951                    pw.println();
20952                } else {
20953                    final String prefix = "  ";
20954                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20955                    if (allPackageSettings.size() == 0) {
20956                        pw.println("No domain preferred apps!");
20957                        pw.println();
20958                    } else {
20959                        pw.println("App verification status:");
20960                        pw.println();
20961                        count = 0;
20962                        for (PackageSetting ps : allPackageSettings) {
20963                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20964                            if (ivi == null || ivi.getPackageName() == null) continue;
20965                            pw.println(prefix + "Package: " + ivi.getPackageName());
20966                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20967                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20968                            pw.println();
20969                            count++;
20970                        }
20971                        if (count == 0) {
20972                            pw.println(prefix + "No app verification established.");
20973                            pw.println();
20974                        }
20975                        for (int userId : sUserManager.getUserIds()) {
20976                            pw.println("App linkages for user " + userId + ":");
20977                            pw.println();
20978                            count = 0;
20979                            for (PackageSetting ps : allPackageSettings) {
20980                                final long status = ps.getDomainVerificationStatusForUser(userId);
20981                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20982                                        && !DEBUG_DOMAIN_VERIFICATION) {
20983                                    continue;
20984                                }
20985                                pw.println(prefix + "Package: " + ps.name);
20986                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20987                                String statusStr = IntentFilterVerificationInfo.
20988                                        getStatusStringFromValue(status);
20989                                pw.println(prefix + "Status:  " + statusStr);
20990                                pw.println();
20991                                count++;
20992                            }
20993                            if (count == 0) {
20994                                pw.println(prefix + "No configured app linkages.");
20995                                pw.println();
20996                            }
20997                        }
20998                    }
20999                }
21000            }
21001
21002            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21003                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21004                if (packageName == null && permissionNames == null) {
21005                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21006                        if (iperm == 0) {
21007                            if (dumpState.onTitlePrinted())
21008                                pw.println();
21009                            pw.println("AppOp Permissions:");
21010                        }
21011                        pw.print("  AppOp Permission ");
21012                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21013                        pw.println(":");
21014                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21015                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21016                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21017                        }
21018                    }
21019                }
21020            }
21021
21022            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21023                boolean printedSomething = false;
21024                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21025                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21026                        continue;
21027                    }
21028                    if (!printedSomething) {
21029                        if (dumpState.onTitlePrinted())
21030                            pw.println();
21031                        pw.println("Registered ContentProviders:");
21032                        printedSomething = true;
21033                    }
21034                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21035                    pw.print("    "); pw.println(p.toString());
21036                }
21037                printedSomething = false;
21038                for (Map.Entry<String, PackageParser.Provider> entry :
21039                        mProvidersByAuthority.entrySet()) {
21040                    PackageParser.Provider p = entry.getValue();
21041                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21042                        continue;
21043                    }
21044                    if (!printedSomething) {
21045                        if (dumpState.onTitlePrinted())
21046                            pw.println();
21047                        pw.println("ContentProvider Authorities:");
21048                        printedSomething = true;
21049                    }
21050                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21051                    pw.print("    "); pw.println(p.toString());
21052                    if (p.info != null && p.info.applicationInfo != null) {
21053                        final String appInfo = p.info.applicationInfo.toString();
21054                        pw.print("      applicationInfo="); pw.println(appInfo);
21055                    }
21056                }
21057            }
21058
21059            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21060                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21061            }
21062
21063            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21064                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21065            }
21066
21067            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21068                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21069            }
21070
21071            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21072                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21073            }
21074
21075            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21076                // XXX should handle packageName != null by dumping only install data that
21077                // the given package is involved with.
21078                if (dumpState.onTitlePrinted()) pw.println();
21079
21080                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21081                ipw.println();
21082                ipw.println("Frozen packages:");
21083                ipw.increaseIndent();
21084                if (mFrozenPackages.size() == 0) {
21085                    ipw.println("(none)");
21086                } else {
21087                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21088                        ipw.println(mFrozenPackages.valueAt(i));
21089                    }
21090                }
21091                ipw.decreaseIndent();
21092            }
21093
21094            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21095                if (dumpState.onTitlePrinted()) pw.println();
21096                dumpDexoptStateLPr(pw, packageName);
21097            }
21098
21099            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21100                if (dumpState.onTitlePrinted()) pw.println();
21101                dumpCompilerStatsLPr(pw, packageName);
21102            }
21103
21104            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21105                if (dumpState.onTitlePrinted()) pw.println();
21106                dumpEnabledOverlaysLPr(pw);
21107            }
21108
21109            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21110                if (dumpState.onTitlePrinted()) pw.println();
21111                mSettings.dumpReadMessagesLPr(pw, dumpState);
21112
21113                pw.println();
21114                pw.println("Package warning messages:");
21115                BufferedReader in = null;
21116                String line = null;
21117                try {
21118                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21119                    while ((line = in.readLine()) != null) {
21120                        if (line.contains("ignored: updated version")) continue;
21121                        pw.println(line);
21122                    }
21123                } catch (IOException ignored) {
21124                } finally {
21125                    IoUtils.closeQuietly(in);
21126                }
21127            }
21128
21129            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21130                BufferedReader in = null;
21131                String line = null;
21132                try {
21133                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21134                    while ((line = in.readLine()) != null) {
21135                        if (line.contains("ignored: updated version")) continue;
21136                        pw.print("msg,");
21137                        pw.println(line);
21138                    }
21139                } catch (IOException ignored) {
21140                } finally {
21141                    IoUtils.closeQuietly(in);
21142                }
21143            }
21144        }
21145
21146        // PackageInstaller should be called outside of mPackages lock
21147        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21148            // XXX should handle packageName != null by dumping only install data that
21149            // the given package is involved with.
21150            if (dumpState.onTitlePrinted()) pw.println();
21151            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21152        }
21153    }
21154
21155    private void dumpProto(FileDescriptor fd) {
21156        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21157
21158        synchronized (mPackages) {
21159            final long requiredVerifierPackageToken =
21160                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21161            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21162            proto.write(
21163                    PackageServiceDumpProto.PackageShortProto.UID,
21164                    getPackageUid(
21165                            mRequiredVerifierPackage,
21166                            MATCH_DEBUG_TRIAGED_MISSING,
21167                            UserHandle.USER_SYSTEM));
21168            proto.end(requiredVerifierPackageToken);
21169
21170            if (mIntentFilterVerifierComponent != null) {
21171                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21172                final long verifierPackageToken =
21173                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21174                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21175                proto.write(
21176                        PackageServiceDumpProto.PackageShortProto.UID,
21177                        getPackageUid(
21178                                verifierPackageName,
21179                                MATCH_DEBUG_TRIAGED_MISSING,
21180                                UserHandle.USER_SYSTEM));
21181                proto.end(verifierPackageToken);
21182            }
21183
21184            dumpSharedLibrariesProto(proto);
21185            dumpFeaturesProto(proto);
21186            mSettings.dumpPackagesProto(proto);
21187            mSettings.dumpSharedUsersProto(proto);
21188            dumpMessagesProto(proto);
21189        }
21190        proto.flush();
21191    }
21192
21193    private void dumpMessagesProto(ProtoOutputStream proto) {
21194        BufferedReader in = null;
21195        String line = null;
21196        try {
21197            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21198            while ((line = in.readLine()) != null) {
21199                if (line.contains("ignored: updated version")) continue;
21200                proto.write(PackageServiceDumpProto.MESSAGES, line);
21201            }
21202        } catch (IOException ignored) {
21203        } finally {
21204            IoUtils.closeQuietly(in);
21205        }
21206    }
21207
21208    private void dumpFeaturesProto(ProtoOutputStream proto) {
21209        synchronized (mAvailableFeatures) {
21210            final int count = mAvailableFeatures.size();
21211            for (int i = 0; i < count; i++) {
21212                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21213                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21214                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21215                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21216                proto.end(featureToken);
21217            }
21218        }
21219    }
21220
21221    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21222        final int count = mSharedLibraries.size();
21223        for (int i = 0; i < count; i++) {
21224            final String libName = mSharedLibraries.keyAt(i);
21225            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21226            if (versionedLib == null) {
21227                continue;
21228            }
21229            final int versionCount = versionedLib.size();
21230            for (int j = 0; j < versionCount; j++) {
21231                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21232                final long sharedLibraryToken =
21233                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21234                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21235                final boolean isJar = (libEntry.path != null);
21236                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21237                if (isJar) {
21238                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21239                } else {
21240                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21241                }
21242                proto.end(sharedLibraryToken);
21243            }
21244        }
21245    }
21246
21247    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21248        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21249        ipw.println();
21250        ipw.println("Dexopt state:");
21251        ipw.increaseIndent();
21252        Collection<PackageParser.Package> packages = null;
21253        if (packageName != null) {
21254            PackageParser.Package targetPackage = mPackages.get(packageName);
21255            if (targetPackage != null) {
21256                packages = Collections.singletonList(targetPackage);
21257            } else {
21258                ipw.println("Unable to find package: " + packageName);
21259                return;
21260            }
21261        } else {
21262            packages = mPackages.values();
21263        }
21264
21265        for (PackageParser.Package pkg : packages) {
21266            ipw.println("[" + pkg.packageName + "]");
21267            ipw.increaseIndent();
21268            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21269            ipw.decreaseIndent();
21270        }
21271    }
21272
21273    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21274        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21275        ipw.println();
21276        ipw.println("Compiler stats:");
21277        ipw.increaseIndent();
21278        Collection<PackageParser.Package> packages = null;
21279        if (packageName != null) {
21280            PackageParser.Package targetPackage = mPackages.get(packageName);
21281            if (targetPackage != null) {
21282                packages = Collections.singletonList(targetPackage);
21283            } else {
21284                ipw.println("Unable to find package: " + packageName);
21285                return;
21286            }
21287        } else {
21288            packages = mPackages.values();
21289        }
21290
21291        for (PackageParser.Package pkg : packages) {
21292            ipw.println("[" + pkg.packageName + "]");
21293            ipw.increaseIndent();
21294
21295            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21296            if (stats == null) {
21297                ipw.println("(No recorded stats)");
21298            } else {
21299                stats.dump(ipw);
21300            }
21301            ipw.decreaseIndent();
21302        }
21303    }
21304
21305    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21306        pw.println("Enabled overlay paths:");
21307        final int N = mEnabledOverlayPaths.size();
21308        for (int i = 0; i < N; i++) {
21309            final int userId = mEnabledOverlayPaths.keyAt(i);
21310            pw.println(String.format("    User %d:", userId));
21311            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21312                mEnabledOverlayPaths.valueAt(i);
21313            final int M = userSpecificOverlays.size();
21314            for (int j = 0; j < M; j++) {
21315                final String targetPackageName = userSpecificOverlays.keyAt(j);
21316                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21317                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21318            }
21319        }
21320    }
21321
21322    private String dumpDomainString(String packageName) {
21323        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21324                .getList();
21325        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21326
21327        ArraySet<String> result = new ArraySet<>();
21328        if (iviList.size() > 0) {
21329            for (IntentFilterVerificationInfo ivi : iviList) {
21330                for (String host : ivi.getDomains()) {
21331                    result.add(host);
21332                }
21333            }
21334        }
21335        if (filters != null && filters.size() > 0) {
21336            for (IntentFilter filter : filters) {
21337                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21338                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21339                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21340                    result.addAll(filter.getHostsList());
21341                }
21342            }
21343        }
21344
21345        StringBuilder sb = new StringBuilder(result.size() * 16);
21346        for (String domain : result) {
21347            if (sb.length() > 0) sb.append(" ");
21348            sb.append(domain);
21349        }
21350        return sb.toString();
21351    }
21352
21353    // ------- apps on sdcard specific code -------
21354    static final boolean DEBUG_SD_INSTALL = false;
21355
21356    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21357
21358    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21359
21360    private boolean mMediaMounted = false;
21361
21362    static String getEncryptKey() {
21363        try {
21364            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21365                    SD_ENCRYPTION_KEYSTORE_NAME);
21366            if (sdEncKey == null) {
21367                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21368                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21369                if (sdEncKey == null) {
21370                    Slog.e(TAG, "Failed to create encryption keys");
21371                    return null;
21372                }
21373            }
21374            return sdEncKey;
21375        } catch (NoSuchAlgorithmException nsae) {
21376            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21377            return null;
21378        } catch (IOException ioe) {
21379            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21380            return null;
21381        }
21382    }
21383
21384    /*
21385     * Update media status on PackageManager.
21386     */
21387    @Override
21388    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21389        int callingUid = Binder.getCallingUid();
21390        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21391            throw new SecurityException("Media status can only be updated by the system");
21392        }
21393        // reader; this apparently protects mMediaMounted, but should probably
21394        // be a different lock in that case.
21395        synchronized (mPackages) {
21396            Log.i(TAG, "Updating external media status from "
21397                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21398                    + (mediaStatus ? "mounted" : "unmounted"));
21399            if (DEBUG_SD_INSTALL)
21400                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21401                        + ", mMediaMounted=" + mMediaMounted);
21402            if (mediaStatus == mMediaMounted) {
21403                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21404                        : 0, -1);
21405                mHandler.sendMessage(msg);
21406                return;
21407            }
21408            mMediaMounted = mediaStatus;
21409        }
21410        // Queue up an async operation since the package installation may take a
21411        // little while.
21412        mHandler.post(new Runnable() {
21413            public void run() {
21414                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21415            }
21416        });
21417    }
21418
21419    /**
21420     * Called by StorageManagerService when the initial ASECs to scan are available.
21421     * Should block until all the ASEC containers are finished being scanned.
21422     */
21423    public void scanAvailableAsecs() {
21424        updateExternalMediaStatusInner(true, false, false);
21425    }
21426
21427    /*
21428     * Collect information of applications on external media, map them against
21429     * existing containers and update information based on current mount status.
21430     * Please note that we always have to report status if reportStatus has been
21431     * set to true especially when unloading packages.
21432     */
21433    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21434            boolean externalStorage) {
21435        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21436        int[] uidArr = EmptyArray.INT;
21437
21438        final String[] list = PackageHelper.getSecureContainerList();
21439        if (ArrayUtils.isEmpty(list)) {
21440            Log.i(TAG, "No secure containers found");
21441        } else {
21442            // Process list of secure containers and categorize them
21443            // as active or stale based on their package internal state.
21444
21445            // reader
21446            synchronized (mPackages) {
21447                for (String cid : list) {
21448                    // Leave stages untouched for now; installer service owns them
21449                    if (PackageInstallerService.isStageName(cid)) continue;
21450
21451                    if (DEBUG_SD_INSTALL)
21452                        Log.i(TAG, "Processing container " + cid);
21453                    String pkgName = getAsecPackageName(cid);
21454                    if (pkgName == null) {
21455                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21456                        continue;
21457                    }
21458                    if (DEBUG_SD_INSTALL)
21459                        Log.i(TAG, "Looking for pkg : " + pkgName);
21460
21461                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21462                    if (ps == null) {
21463                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21464                        continue;
21465                    }
21466
21467                    /*
21468                     * Skip packages that are not external if we're unmounting
21469                     * external storage.
21470                     */
21471                    if (externalStorage && !isMounted && !isExternal(ps)) {
21472                        continue;
21473                    }
21474
21475                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21476                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21477                    // The package status is changed only if the code path
21478                    // matches between settings and the container id.
21479                    if (ps.codePathString != null
21480                            && ps.codePathString.startsWith(args.getCodePath())) {
21481                        if (DEBUG_SD_INSTALL) {
21482                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21483                                    + " at code path: " + ps.codePathString);
21484                        }
21485
21486                        // We do have a valid package installed on sdcard
21487                        processCids.put(args, ps.codePathString);
21488                        final int uid = ps.appId;
21489                        if (uid != -1) {
21490                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21491                        }
21492                    } else {
21493                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21494                                + ps.codePathString);
21495                    }
21496                }
21497            }
21498
21499            Arrays.sort(uidArr);
21500        }
21501
21502        // Process packages with valid entries.
21503        if (isMounted) {
21504            if (DEBUG_SD_INSTALL)
21505                Log.i(TAG, "Loading packages");
21506            loadMediaPackages(processCids, uidArr, externalStorage);
21507            startCleaningPackages();
21508            mInstallerService.onSecureContainersAvailable();
21509        } else {
21510            if (DEBUG_SD_INSTALL)
21511                Log.i(TAG, "Unloading packages");
21512            unloadMediaPackages(processCids, uidArr, reportStatus);
21513        }
21514    }
21515
21516    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21517            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21518        final int size = infos.size();
21519        final String[] packageNames = new String[size];
21520        final int[] packageUids = new int[size];
21521        for (int i = 0; i < size; i++) {
21522            final ApplicationInfo info = infos.get(i);
21523            packageNames[i] = info.packageName;
21524            packageUids[i] = info.uid;
21525        }
21526        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21527                finishedReceiver);
21528    }
21529
21530    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21531            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21532        sendResourcesChangedBroadcast(mediaStatus, replacing,
21533                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21534    }
21535
21536    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21537            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21538        int size = pkgList.length;
21539        if (size > 0) {
21540            // Send broadcasts here
21541            Bundle extras = new Bundle();
21542            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21543            if (uidArr != null) {
21544                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21545            }
21546            if (replacing) {
21547                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21548            }
21549            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21550                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21551            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21552        }
21553    }
21554
21555   /*
21556     * Look at potentially valid container ids from processCids If package
21557     * information doesn't match the one on record or package scanning fails,
21558     * the cid is added to list of removeCids. We currently don't delete stale
21559     * containers.
21560     */
21561    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21562            boolean externalStorage) {
21563        ArrayList<String> pkgList = new ArrayList<String>();
21564        Set<AsecInstallArgs> keys = processCids.keySet();
21565
21566        for (AsecInstallArgs args : keys) {
21567            String codePath = processCids.get(args);
21568            if (DEBUG_SD_INSTALL)
21569                Log.i(TAG, "Loading container : " + args.cid);
21570            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21571            try {
21572                // Make sure there are no container errors first.
21573                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21574                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21575                            + " when installing from sdcard");
21576                    continue;
21577                }
21578                // Check code path here.
21579                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21580                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21581                            + " does not match one in settings " + codePath);
21582                    continue;
21583                }
21584                // Parse package
21585                int parseFlags = mDefParseFlags;
21586                if (args.isExternalAsec()) {
21587                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21588                }
21589                if (args.isFwdLocked()) {
21590                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21591                }
21592
21593                synchronized (mInstallLock) {
21594                    PackageParser.Package pkg = null;
21595                    try {
21596                        // Sadly we don't know the package name yet to freeze it
21597                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21598                                SCAN_IGNORE_FROZEN, 0, null);
21599                    } catch (PackageManagerException e) {
21600                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21601                    }
21602                    // Scan the package
21603                    if (pkg != null) {
21604                        /*
21605                         * TODO why is the lock being held? doPostInstall is
21606                         * called in other places without the lock. This needs
21607                         * to be straightened out.
21608                         */
21609                        // writer
21610                        synchronized (mPackages) {
21611                            retCode = PackageManager.INSTALL_SUCCEEDED;
21612                            pkgList.add(pkg.packageName);
21613                            // Post process args
21614                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21615                                    pkg.applicationInfo.uid);
21616                        }
21617                    } else {
21618                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21619                    }
21620                }
21621
21622            } finally {
21623                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21624                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21625                }
21626            }
21627        }
21628        // writer
21629        synchronized (mPackages) {
21630            // If the platform SDK has changed since the last time we booted,
21631            // we need to re-grant app permission to catch any new ones that
21632            // appear. This is really a hack, and means that apps can in some
21633            // cases get permissions that the user didn't initially explicitly
21634            // allow... it would be nice to have some better way to handle
21635            // this situation.
21636            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21637                    : mSettings.getInternalVersion();
21638            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21639                    : StorageManager.UUID_PRIVATE_INTERNAL;
21640
21641            int updateFlags = UPDATE_PERMISSIONS_ALL;
21642            if (ver.sdkVersion != mSdkVersion) {
21643                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21644                        + mSdkVersion + "; regranting permissions for external");
21645                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21646            }
21647            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21648
21649            // Yay, everything is now upgraded
21650            ver.forceCurrent();
21651
21652            // can downgrade to reader
21653            // Persist settings
21654            mSettings.writeLPr();
21655        }
21656        // Send a broadcast to let everyone know we are done processing
21657        if (pkgList.size() > 0) {
21658            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21659        }
21660    }
21661
21662   /*
21663     * Utility method to unload a list of specified containers
21664     */
21665    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21666        // Just unmount all valid containers.
21667        for (AsecInstallArgs arg : cidArgs) {
21668            synchronized (mInstallLock) {
21669                arg.doPostDeleteLI(false);
21670           }
21671       }
21672   }
21673
21674    /*
21675     * Unload packages mounted on external media. This involves deleting package
21676     * data from internal structures, sending broadcasts about disabled packages,
21677     * gc'ing to free up references, unmounting all secure containers
21678     * corresponding to packages on external media, and posting a
21679     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21680     * that we always have to post this message if status has been requested no
21681     * matter what.
21682     */
21683    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21684            final boolean reportStatus) {
21685        if (DEBUG_SD_INSTALL)
21686            Log.i(TAG, "unloading media packages");
21687        ArrayList<String> pkgList = new ArrayList<String>();
21688        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21689        final Set<AsecInstallArgs> keys = processCids.keySet();
21690        for (AsecInstallArgs args : keys) {
21691            String pkgName = args.getPackageName();
21692            if (DEBUG_SD_INSTALL)
21693                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21694            // Delete package internally
21695            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21696            synchronized (mInstallLock) {
21697                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21698                final boolean res;
21699                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21700                        "unloadMediaPackages")) {
21701                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21702                            null);
21703                }
21704                if (res) {
21705                    pkgList.add(pkgName);
21706                } else {
21707                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21708                    failedList.add(args);
21709                }
21710            }
21711        }
21712
21713        // reader
21714        synchronized (mPackages) {
21715            // We didn't update the settings after removing each package;
21716            // write them now for all packages.
21717            mSettings.writeLPr();
21718        }
21719
21720        // We have to absolutely send UPDATED_MEDIA_STATUS only
21721        // after confirming that all the receivers processed the ordered
21722        // broadcast when packages get disabled, force a gc to clean things up.
21723        // and unload all the containers.
21724        if (pkgList.size() > 0) {
21725            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21726                    new IIntentReceiver.Stub() {
21727                public void performReceive(Intent intent, int resultCode, String data,
21728                        Bundle extras, boolean ordered, boolean sticky,
21729                        int sendingUser) throws RemoteException {
21730                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21731                            reportStatus ? 1 : 0, 1, keys);
21732                    mHandler.sendMessage(msg);
21733                }
21734            });
21735        } else {
21736            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21737                    keys);
21738            mHandler.sendMessage(msg);
21739        }
21740    }
21741
21742    private void loadPrivatePackages(final VolumeInfo vol) {
21743        mHandler.post(new Runnable() {
21744            @Override
21745            public void run() {
21746                loadPrivatePackagesInner(vol);
21747            }
21748        });
21749    }
21750
21751    private void loadPrivatePackagesInner(VolumeInfo vol) {
21752        final String volumeUuid = vol.fsUuid;
21753        if (TextUtils.isEmpty(volumeUuid)) {
21754            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21755            return;
21756        }
21757
21758        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21759        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21760        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21761
21762        final VersionInfo ver;
21763        final List<PackageSetting> packages;
21764        synchronized (mPackages) {
21765            ver = mSettings.findOrCreateVersion(volumeUuid);
21766            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21767        }
21768
21769        for (PackageSetting ps : packages) {
21770            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21771            synchronized (mInstallLock) {
21772                final PackageParser.Package pkg;
21773                try {
21774                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21775                    loaded.add(pkg.applicationInfo);
21776
21777                } catch (PackageManagerException e) {
21778                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21779                }
21780
21781                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21782                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21783                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21784                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21785                }
21786            }
21787        }
21788
21789        // Reconcile app data for all started/unlocked users
21790        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21791        final UserManager um = mContext.getSystemService(UserManager.class);
21792        UserManagerInternal umInternal = getUserManagerInternal();
21793        for (UserInfo user : um.getUsers()) {
21794            final int flags;
21795            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21796                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21797            } else if (umInternal.isUserRunning(user.id)) {
21798                flags = StorageManager.FLAG_STORAGE_DE;
21799            } else {
21800                continue;
21801            }
21802
21803            try {
21804                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21805                synchronized (mInstallLock) {
21806                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21807                }
21808            } catch (IllegalStateException e) {
21809                // Device was probably ejected, and we'll process that event momentarily
21810                Slog.w(TAG, "Failed to prepare storage: " + e);
21811            }
21812        }
21813
21814        synchronized (mPackages) {
21815            int updateFlags = UPDATE_PERMISSIONS_ALL;
21816            if (ver.sdkVersion != mSdkVersion) {
21817                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21818                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21819                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21820            }
21821            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21822
21823            // Yay, everything is now upgraded
21824            ver.forceCurrent();
21825
21826            mSettings.writeLPr();
21827        }
21828
21829        for (PackageFreezer freezer : freezers) {
21830            freezer.close();
21831        }
21832
21833        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21834        sendResourcesChangedBroadcast(true, false, loaded, null);
21835    }
21836
21837    private void unloadPrivatePackages(final VolumeInfo vol) {
21838        mHandler.post(new Runnable() {
21839            @Override
21840            public void run() {
21841                unloadPrivatePackagesInner(vol);
21842            }
21843        });
21844    }
21845
21846    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21847        final String volumeUuid = vol.fsUuid;
21848        if (TextUtils.isEmpty(volumeUuid)) {
21849            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21850            return;
21851        }
21852
21853        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21854        synchronized (mInstallLock) {
21855        synchronized (mPackages) {
21856            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21857            for (PackageSetting ps : packages) {
21858                if (ps.pkg == null) continue;
21859
21860                final ApplicationInfo info = ps.pkg.applicationInfo;
21861                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21862                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21863
21864                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21865                        "unloadPrivatePackagesInner")) {
21866                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21867                            false, null)) {
21868                        unloaded.add(info);
21869                    } else {
21870                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21871                    }
21872                }
21873
21874                // Try very hard to release any references to this package
21875                // so we don't risk the system server being killed due to
21876                // open FDs
21877                AttributeCache.instance().removePackage(ps.name);
21878            }
21879
21880            mSettings.writeLPr();
21881        }
21882        }
21883
21884        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21885        sendResourcesChangedBroadcast(false, false, unloaded, null);
21886
21887        // Try very hard to release any references to this path so we don't risk
21888        // the system server being killed due to open FDs
21889        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21890
21891        for (int i = 0; i < 3; i++) {
21892            System.gc();
21893            System.runFinalization();
21894        }
21895    }
21896
21897    private void assertPackageKnown(String volumeUuid, String packageName)
21898            throws PackageManagerException {
21899        synchronized (mPackages) {
21900            // Normalize package name to handle renamed packages
21901            packageName = normalizePackageNameLPr(packageName);
21902
21903            final PackageSetting ps = mSettings.mPackages.get(packageName);
21904            if (ps == null) {
21905                throw new PackageManagerException("Package " + packageName + " is unknown");
21906            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21907                throw new PackageManagerException(
21908                        "Package " + packageName + " found on unknown volume " + volumeUuid
21909                                + "; expected volume " + ps.volumeUuid);
21910            }
21911        }
21912    }
21913
21914    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21915            throws PackageManagerException {
21916        synchronized (mPackages) {
21917            // Normalize package name to handle renamed packages
21918            packageName = normalizePackageNameLPr(packageName);
21919
21920            final PackageSetting ps = mSettings.mPackages.get(packageName);
21921            if (ps == null) {
21922                throw new PackageManagerException("Package " + packageName + " is unknown");
21923            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21924                throw new PackageManagerException(
21925                        "Package " + packageName + " found on unknown volume " + volumeUuid
21926                                + "; expected volume " + ps.volumeUuid);
21927            } else if (!ps.getInstalled(userId)) {
21928                throw new PackageManagerException(
21929                        "Package " + packageName + " not installed for user " + userId);
21930            }
21931        }
21932    }
21933
21934    private List<String> collectAbsoluteCodePaths() {
21935        synchronized (mPackages) {
21936            List<String> codePaths = new ArrayList<>();
21937            final int packageCount = mSettings.mPackages.size();
21938            for (int i = 0; i < packageCount; i++) {
21939                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21940                codePaths.add(ps.codePath.getAbsolutePath());
21941            }
21942            return codePaths;
21943        }
21944    }
21945
21946    /**
21947     * Examine all apps present on given mounted volume, and destroy apps that
21948     * aren't expected, either due to uninstallation or reinstallation on
21949     * another volume.
21950     */
21951    private void reconcileApps(String volumeUuid) {
21952        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21953        List<File> filesToDelete = null;
21954
21955        final File[] files = FileUtils.listFilesOrEmpty(
21956                Environment.getDataAppDirectory(volumeUuid));
21957        for (File file : files) {
21958            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21959                    && !PackageInstallerService.isStageName(file.getName());
21960            if (!isPackage) {
21961                // Ignore entries which are not packages
21962                continue;
21963            }
21964
21965            String absolutePath = file.getAbsolutePath();
21966
21967            boolean pathValid = false;
21968            final int absoluteCodePathCount = absoluteCodePaths.size();
21969            for (int i = 0; i < absoluteCodePathCount; i++) {
21970                String absoluteCodePath = absoluteCodePaths.get(i);
21971                if (absolutePath.startsWith(absoluteCodePath)) {
21972                    pathValid = true;
21973                    break;
21974                }
21975            }
21976
21977            if (!pathValid) {
21978                if (filesToDelete == null) {
21979                    filesToDelete = new ArrayList<>();
21980                }
21981                filesToDelete.add(file);
21982            }
21983        }
21984
21985        if (filesToDelete != null) {
21986            final int fileToDeleteCount = filesToDelete.size();
21987            for (int i = 0; i < fileToDeleteCount; i++) {
21988                File fileToDelete = filesToDelete.get(i);
21989                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21990                synchronized (mInstallLock) {
21991                    removeCodePathLI(fileToDelete);
21992                }
21993            }
21994        }
21995    }
21996
21997    /**
21998     * Reconcile all app data for the given user.
21999     * <p>
22000     * Verifies that directories exist and that ownership and labeling is
22001     * correct for all installed apps on all mounted volumes.
22002     */
22003    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22004        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22005        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22006            final String volumeUuid = vol.getFsUuid();
22007            synchronized (mInstallLock) {
22008                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22009            }
22010        }
22011    }
22012
22013    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22014            boolean migrateAppData) {
22015        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22016    }
22017
22018    /**
22019     * Reconcile all app data on given mounted volume.
22020     * <p>
22021     * Destroys app data that isn't expected, either due to uninstallation or
22022     * reinstallation on another volume.
22023     * <p>
22024     * Verifies that directories exist and that ownership and labeling is
22025     * correct for all installed apps.
22026     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22027     */
22028    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22029            boolean migrateAppData, boolean onlyCoreApps) {
22030        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22031                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22032        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22033
22034        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22035        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22036
22037        // First look for stale data that doesn't belong, and check if things
22038        // have changed since we did our last restorecon
22039        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22040            if (StorageManager.isFileEncryptedNativeOrEmulated()
22041                    && !StorageManager.isUserKeyUnlocked(userId)) {
22042                throw new RuntimeException(
22043                        "Yikes, someone asked us to reconcile CE storage while " + userId
22044                                + " was still locked; this would have caused massive data loss!");
22045            }
22046
22047            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22048            for (File file : files) {
22049                final String packageName = file.getName();
22050                try {
22051                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22052                } catch (PackageManagerException e) {
22053                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22054                    try {
22055                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22056                                StorageManager.FLAG_STORAGE_CE, 0);
22057                    } catch (InstallerException e2) {
22058                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22059                    }
22060                }
22061            }
22062        }
22063        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22064            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22065            for (File file : files) {
22066                final String packageName = file.getName();
22067                try {
22068                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22069                } catch (PackageManagerException e) {
22070                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22071                    try {
22072                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22073                                StorageManager.FLAG_STORAGE_DE, 0);
22074                    } catch (InstallerException e2) {
22075                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22076                    }
22077                }
22078            }
22079        }
22080
22081        // Ensure that data directories are ready to roll for all packages
22082        // installed for this volume and user
22083        final List<PackageSetting> packages;
22084        synchronized (mPackages) {
22085            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22086        }
22087        int preparedCount = 0;
22088        for (PackageSetting ps : packages) {
22089            final String packageName = ps.name;
22090            if (ps.pkg == null) {
22091                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22092                // TODO: might be due to legacy ASEC apps; we should circle back
22093                // and reconcile again once they're scanned
22094                continue;
22095            }
22096            // Skip non-core apps if requested
22097            if (onlyCoreApps && !ps.pkg.coreApp) {
22098                result.add(packageName);
22099                continue;
22100            }
22101
22102            if (ps.getInstalled(userId)) {
22103                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22104                preparedCount++;
22105            }
22106        }
22107
22108        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22109        return result;
22110    }
22111
22112    /**
22113     * Prepare app data for the given app just after it was installed or
22114     * upgraded. This method carefully only touches users that it's installed
22115     * for, and it forces a restorecon to handle any seinfo changes.
22116     * <p>
22117     * Verifies that directories exist and that ownership and labeling is
22118     * correct for all installed apps. If there is an ownership mismatch, it
22119     * will try recovering system apps by wiping data; third-party app data is
22120     * left intact.
22121     * <p>
22122     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22123     */
22124    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22125        final PackageSetting ps;
22126        synchronized (mPackages) {
22127            ps = mSettings.mPackages.get(pkg.packageName);
22128            mSettings.writeKernelMappingLPr(ps);
22129        }
22130
22131        final UserManager um = mContext.getSystemService(UserManager.class);
22132        UserManagerInternal umInternal = getUserManagerInternal();
22133        for (UserInfo user : um.getUsers()) {
22134            final int flags;
22135            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22136                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22137            } else if (umInternal.isUserRunning(user.id)) {
22138                flags = StorageManager.FLAG_STORAGE_DE;
22139            } else {
22140                continue;
22141            }
22142
22143            if (ps.getInstalled(user.id)) {
22144                // TODO: when user data is locked, mark that we're still dirty
22145                prepareAppDataLIF(pkg, user.id, flags);
22146            }
22147        }
22148    }
22149
22150    /**
22151     * Prepare app data for the given app.
22152     * <p>
22153     * Verifies that directories exist and that ownership and labeling is
22154     * correct for all installed apps. If there is an ownership mismatch, this
22155     * will try recovering system apps by wiping data; third-party app data is
22156     * left intact.
22157     */
22158    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22159        if (pkg == null) {
22160            Slog.wtf(TAG, "Package was null!", new Throwable());
22161            return;
22162        }
22163        prepareAppDataLeafLIF(pkg, userId, flags);
22164        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22165        for (int i = 0; i < childCount; i++) {
22166            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22167        }
22168    }
22169
22170    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22171            boolean maybeMigrateAppData) {
22172        prepareAppDataLIF(pkg, userId, flags);
22173
22174        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22175            // We may have just shuffled around app data directories, so
22176            // prepare them one more time
22177            prepareAppDataLIF(pkg, userId, flags);
22178        }
22179    }
22180
22181    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22182        if (DEBUG_APP_DATA) {
22183            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22184                    + Integer.toHexString(flags));
22185        }
22186
22187        final String volumeUuid = pkg.volumeUuid;
22188        final String packageName = pkg.packageName;
22189        final ApplicationInfo app = pkg.applicationInfo;
22190        final int appId = UserHandle.getAppId(app.uid);
22191
22192        Preconditions.checkNotNull(app.seInfo);
22193
22194        long ceDataInode = -1;
22195        try {
22196            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22197                    appId, app.seInfo, app.targetSdkVersion);
22198        } catch (InstallerException e) {
22199            if (app.isSystemApp()) {
22200                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22201                        + ", but trying to recover: " + e);
22202                destroyAppDataLeafLIF(pkg, userId, flags);
22203                try {
22204                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22205                            appId, app.seInfo, app.targetSdkVersion);
22206                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22207                } catch (InstallerException e2) {
22208                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22209                }
22210            } else {
22211                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22212            }
22213        }
22214
22215        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22216            // TODO: mark this structure as dirty so we persist it!
22217            synchronized (mPackages) {
22218                final PackageSetting ps = mSettings.mPackages.get(packageName);
22219                if (ps != null) {
22220                    ps.setCeDataInode(ceDataInode, userId);
22221                }
22222            }
22223        }
22224
22225        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22226    }
22227
22228    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22229        if (pkg == null) {
22230            Slog.wtf(TAG, "Package was null!", new Throwable());
22231            return;
22232        }
22233        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22234        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22235        for (int i = 0; i < childCount; i++) {
22236            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22237        }
22238    }
22239
22240    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22241        final String volumeUuid = pkg.volumeUuid;
22242        final String packageName = pkg.packageName;
22243        final ApplicationInfo app = pkg.applicationInfo;
22244
22245        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22246            // Create a native library symlink only if we have native libraries
22247            // and if the native libraries are 32 bit libraries. We do not provide
22248            // this symlink for 64 bit libraries.
22249            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22250                final String nativeLibPath = app.nativeLibraryDir;
22251                try {
22252                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22253                            nativeLibPath, userId);
22254                } catch (InstallerException e) {
22255                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22256                }
22257            }
22258        }
22259    }
22260
22261    /**
22262     * For system apps on non-FBE devices, this method migrates any existing
22263     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22264     * requested by the app.
22265     */
22266    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22267        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22268                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22269            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22270                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22271            try {
22272                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22273                        storageTarget);
22274            } catch (InstallerException e) {
22275                logCriticalInfo(Log.WARN,
22276                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22277            }
22278            return true;
22279        } else {
22280            return false;
22281        }
22282    }
22283
22284    public PackageFreezer freezePackage(String packageName, String killReason) {
22285        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22286    }
22287
22288    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22289        return new PackageFreezer(packageName, userId, killReason);
22290    }
22291
22292    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22293            String killReason) {
22294        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22295    }
22296
22297    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22298            String killReason) {
22299        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22300            return new PackageFreezer();
22301        } else {
22302            return freezePackage(packageName, userId, killReason);
22303        }
22304    }
22305
22306    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22307            String killReason) {
22308        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22309    }
22310
22311    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22312            String killReason) {
22313        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22314            return new PackageFreezer();
22315        } else {
22316            return freezePackage(packageName, userId, killReason);
22317        }
22318    }
22319
22320    /**
22321     * Class that freezes and kills the given package upon creation, and
22322     * unfreezes it upon closing. This is typically used when doing surgery on
22323     * app code/data to prevent the app from running while you're working.
22324     */
22325    private class PackageFreezer implements AutoCloseable {
22326        private final String mPackageName;
22327        private final PackageFreezer[] mChildren;
22328
22329        private final boolean mWeFroze;
22330
22331        private final AtomicBoolean mClosed = new AtomicBoolean();
22332        private final CloseGuard mCloseGuard = CloseGuard.get();
22333
22334        /**
22335         * Create and return a stub freezer that doesn't actually do anything,
22336         * typically used when someone requested
22337         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22338         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22339         */
22340        public PackageFreezer() {
22341            mPackageName = null;
22342            mChildren = null;
22343            mWeFroze = false;
22344            mCloseGuard.open("close");
22345        }
22346
22347        public PackageFreezer(String packageName, int userId, String killReason) {
22348            synchronized (mPackages) {
22349                mPackageName = packageName;
22350                mWeFroze = mFrozenPackages.add(mPackageName);
22351
22352                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22353                if (ps != null) {
22354                    killApplication(ps.name, ps.appId, userId, killReason);
22355                }
22356
22357                final PackageParser.Package p = mPackages.get(packageName);
22358                if (p != null && p.childPackages != null) {
22359                    final int N = p.childPackages.size();
22360                    mChildren = new PackageFreezer[N];
22361                    for (int i = 0; i < N; i++) {
22362                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22363                                userId, killReason);
22364                    }
22365                } else {
22366                    mChildren = null;
22367                }
22368            }
22369            mCloseGuard.open("close");
22370        }
22371
22372        @Override
22373        protected void finalize() throws Throwable {
22374            try {
22375                mCloseGuard.warnIfOpen();
22376                close();
22377            } finally {
22378                super.finalize();
22379            }
22380        }
22381
22382        @Override
22383        public void close() {
22384            mCloseGuard.close();
22385            if (mClosed.compareAndSet(false, true)) {
22386                synchronized (mPackages) {
22387                    if (mWeFroze) {
22388                        mFrozenPackages.remove(mPackageName);
22389                    }
22390
22391                    if (mChildren != null) {
22392                        for (PackageFreezer freezer : mChildren) {
22393                            freezer.close();
22394                        }
22395                    }
22396                }
22397            }
22398        }
22399    }
22400
22401    /**
22402     * Verify that given package is currently frozen.
22403     */
22404    private void checkPackageFrozen(String packageName) {
22405        synchronized (mPackages) {
22406            if (!mFrozenPackages.contains(packageName)) {
22407                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22408            }
22409        }
22410    }
22411
22412    @Override
22413    public int movePackage(final String packageName, final String volumeUuid) {
22414        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22415
22416        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22417        final int moveId = mNextMoveId.getAndIncrement();
22418        mHandler.post(new Runnable() {
22419            @Override
22420            public void run() {
22421                try {
22422                    movePackageInternal(packageName, volumeUuid, moveId, user);
22423                } catch (PackageManagerException e) {
22424                    Slog.w(TAG, "Failed to move " + packageName, e);
22425                    mMoveCallbacks.notifyStatusChanged(moveId,
22426                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22427                }
22428            }
22429        });
22430        return moveId;
22431    }
22432
22433    private void movePackageInternal(final String packageName, final String volumeUuid,
22434            final int moveId, UserHandle user) throws PackageManagerException {
22435        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22436        final PackageManager pm = mContext.getPackageManager();
22437
22438        final boolean currentAsec;
22439        final String currentVolumeUuid;
22440        final File codeFile;
22441        final String installerPackageName;
22442        final String packageAbiOverride;
22443        final int appId;
22444        final String seinfo;
22445        final String label;
22446        final int targetSdkVersion;
22447        final PackageFreezer freezer;
22448        final int[] installedUserIds;
22449
22450        // reader
22451        synchronized (mPackages) {
22452            final PackageParser.Package pkg = mPackages.get(packageName);
22453            final PackageSetting ps = mSettings.mPackages.get(packageName);
22454            if (pkg == null || ps == null) {
22455                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22456            }
22457
22458            if (pkg.applicationInfo.isSystemApp()) {
22459                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22460                        "Cannot move system application");
22461            }
22462
22463            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22464            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22465                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22466            if (isInternalStorage && !allow3rdPartyOnInternal) {
22467                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22468                        "3rd party apps are not allowed on internal storage");
22469            }
22470
22471            if (pkg.applicationInfo.isExternalAsec()) {
22472                currentAsec = true;
22473                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22474            } else if (pkg.applicationInfo.isForwardLocked()) {
22475                currentAsec = true;
22476                currentVolumeUuid = "forward_locked";
22477            } else {
22478                currentAsec = false;
22479                currentVolumeUuid = ps.volumeUuid;
22480
22481                final File probe = new File(pkg.codePath);
22482                final File probeOat = new File(probe, "oat");
22483                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22484                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22485                            "Move only supported for modern cluster style installs");
22486                }
22487            }
22488
22489            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22490                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22491                        "Package already moved to " + volumeUuid);
22492            }
22493            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22494                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22495                        "Device admin cannot be moved");
22496            }
22497
22498            if (mFrozenPackages.contains(packageName)) {
22499                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22500                        "Failed to move already frozen package");
22501            }
22502
22503            codeFile = new File(pkg.codePath);
22504            installerPackageName = ps.installerPackageName;
22505            packageAbiOverride = ps.cpuAbiOverrideString;
22506            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22507            seinfo = pkg.applicationInfo.seInfo;
22508            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22509            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22510            freezer = freezePackage(packageName, "movePackageInternal");
22511            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22512        }
22513
22514        final Bundle extras = new Bundle();
22515        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22516        extras.putString(Intent.EXTRA_TITLE, label);
22517        mMoveCallbacks.notifyCreated(moveId, extras);
22518
22519        int installFlags;
22520        final boolean moveCompleteApp;
22521        final File measurePath;
22522
22523        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22524            installFlags = INSTALL_INTERNAL;
22525            moveCompleteApp = !currentAsec;
22526            measurePath = Environment.getDataAppDirectory(volumeUuid);
22527        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22528            installFlags = INSTALL_EXTERNAL;
22529            moveCompleteApp = false;
22530            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22531        } else {
22532            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22533            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22534                    || !volume.isMountedWritable()) {
22535                freezer.close();
22536                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22537                        "Move location not mounted private volume");
22538            }
22539
22540            Preconditions.checkState(!currentAsec);
22541
22542            installFlags = INSTALL_INTERNAL;
22543            moveCompleteApp = true;
22544            measurePath = Environment.getDataAppDirectory(volumeUuid);
22545        }
22546
22547        final PackageStats stats = new PackageStats(null, -1);
22548        synchronized (mInstaller) {
22549            for (int userId : installedUserIds) {
22550                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22551                    freezer.close();
22552                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22553                            "Failed to measure package size");
22554                }
22555            }
22556        }
22557
22558        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22559                + stats.dataSize);
22560
22561        final long startFreeBytes = measurePath.getUsableSpace();
22562        final long sizeBytes;
22563        if (moveCompleteApp) {
22564            sizeBytes = stats.codeSize + stats.dataSize;
22565        } else {
22566            sizeBytes = stats.codeSize;
22567        }
22568
22569        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22570            freezer.close();
22571            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22572                    "Not enough free space to move");
22573        }
22574
22575        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22576
22577        final CountDownLatch installedLatch = new CountDownLatch(1);
22578        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22579            @Override
22580            public void onUserActionRequired(Intent intent) throws RemoteException {
22581                throw new IllegalStateException();
22582            }
22583
22584            @Override
22585            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22586                    Bundle extras) throws RemoteException {
22587                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22588                        + PackageManager.installStatusToString(returnCode, msg));
22589
22590                installedLatch.countDown();
22591                freezer.close();
22592
22593                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22594                switch (status) {
22595                    case PackageInstaller.STATUS_SUCCESS:
22596                        mMoveCallbacks.notifyStatusChanged(moveId,
22597                                PackageManager.MOVE_SUCCEEDED);
22598                        break;
22599                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22600                        mMoveCallbacks.notifyStatusChanged(moveId,
22601                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22602                        break;
22603                    default:
22604                        mMoveCallbacks.notifyStatusChanged(moveId,
22605                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22606                        break;
22607                }
22608            }
22609        };
22610
22611        final MoveInfo move;
22612        if (moveCompleteApp) {
22613            // Kick off a thread to report progress estimates
22614            new Thread() {
22615                @Override
22616                public void run() {
22617                    while (true) {
22618                        try {
22619                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22620                                break;
22621                            }
22622                        } catch (InterruptedException ignored) {
22623                        }
22624
22625                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22626                        final int progress = 10 + (int) MathUtils.constrain(
22627                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22628                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22629                    }
22630                }
22631            }.start();
22632
22633            final String dataAppName = codeFile.getName();
22634            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22635                    dataAppName, appId, seinfo, targetSdkVersion);
22636        } else {
22637            move = null;
22638        }
22639
22640        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22641
22642        final Message msg = mHandler.obtainMessage(INIT_COPY);
22643        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22644        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22645                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22646                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22647                PackageManager.INSTALL_REASON_UNKNOWN);
22648        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22649        msg.obj = params;
22650
22651        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22652                System.identityHashCode(msg.obj));
22653        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22654                System.identityHashCode(msg.obj));
22655
22656        mHandler.sendMessage(msg);
22657    }
22658
22659    @Override
22660    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22661        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22662
22663        final int realMoveId = mNextMoveId.getAndIncrement();
22664        final Bundle extras = new Bundle();
22665        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22666        mMoveCallbacks.notifyCreated(realMoveId, extras);
22667
22668        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22669            @Override
22670            public void onCreated(int moveId, Bundle extras) {
22671                // Ignored
22672            }
22673
22674            @Override
22675            public void onStatusChanged(int moveId, int status, long estMillis) {
22676                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22677            }
22678        };
22679
22680        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22681        storage.setPrimaryStorageUuid(volumeUuid, callback);
22682        return realMoveId;
22683    }
22684
22685    @Override
22686    public int getMoveStatus(int moveId) {
22687        mContext.enforceCallingOrSelfPermission(
22688                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22689        return mMoveCallbacks.mLastStatus.get(moveId);
22690    }
22691
22692    @Override
22693    public void registerMoveCallback(IPackageMoveObserver callback) {
22694        mContext.enforceCallingOrSelfPermission(
22695                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22696        mMoveCallbacks.register(callback);
22697    }
22698
22699    @Override
22700    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22701        mContext.enforceCallingOrSelfPermission(
22702                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22703        mMoveCallbacks.unregister(callback);
22704    }
22705
22706    @Override
22707    public boolean setInstallLocation(int loc) {
22708        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22709                null);
22710        if (getInstallLocation() == loc) {
22711            return true;
22712        }
22713        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22714                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22715            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22716                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22717            return true;
22718        }
22719        return false;
22720   }
22721
22722    @Override
22723    public int getInstallLocation() {
22724        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22725                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22726                PackageHelper.APP_INSTALL_AUTO);
22727    }
22728
22729    /** Called by UserManagerService */
22730    void cleanUpUser(UserManagerService userManager, int userHandle) {
22731        synchronized (mPackages) {
22732            mDirtyUsers.remove(userHandle);
22733            mUserNeedsBadging.delete(userHandle);
22734            mSettings.removeUserLPw(userHandle);
22735            mPendingBroadcasts.remove(userHandle);
22736            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22737            removeUnusedPackagesLPw(userManager, userHandle);
22738        }
22739    }
22740
22741    /**
22742     * We're removing userHandle and would like to remove any downloaded packages
22743     * that are no longer in use by any other user.
22744     * @param userHandle the user being removed
22745     */
22746    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22747        final boolean DEBUG_CLEAN_APKS = false;
22748        int [] users = userManager.getUserIds();
22749        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22750        while (psit.hasNext()) {
22751            PackageSetting ps = psit.next();
22752            if (ps.pkg == null) {
22753                continue;
22754            }
22755            final String packageName = ps.pkg.packageName;
22756            // Skip over if system app
22757            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22758                continue;
22759            }
22760            if (DEBUG_CLEAN_APKS) {
22761                Slog.i(TAG, "Checking package " + packageName);
22762            }
22763            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22764            if (keep) {
22765                if (DEBUG_CLEAN_APKS) {
22766                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22767                }
22768            } else {
22769                for (int i = 0; i < users.length; i++) {
22770                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22771                        keep = true;
22772                        if (DEBUG_CLEAN_APKS) {
22773                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22774                                    + users[i]);
22775                        }
22776                        break;
22777                    }
22778                }
22779            }
22780            if (!keep) {
22781                if (DEBUG_CLEAN_APKS) {
22782                    Slog.i(TAG, "  Removing package " + packageName);
22783                }
22784                mHandler.post(new Runnable() {
22785                    public void run() {
22786                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22787                                userHandle, 0);
22788                    } //end run
22789                });
22790            }
22791        }
22792    }
22793
22794    /** Called by UserManagerService */
22795    void createNewUser(int userId, String[] disallowedPackages) {
22796        synchronized (mInstallLock) {
22797            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22798        }
22799        synchronized (mPackages) {
22800            scheduleWritePackageRestrictionsLocked(userId);
22801            scheduleWritePackageListLocked(userId);
22802            applyFactoryDefaultBrowserLPw(userId);
22803            primeDomainVerificationsLPw(userId);
22804        }
22805    }
22806
22807    void onNewUserCreated(final int userId) {
22808        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22809        // If permission review for legacy apps is required, we represent
22810        // dagerous permissions for such apps as always granted runtime
22811        // permissions to keep per user flag state whether review is needed.
22812        // Hence, if a new user is added we have to propagate dangerous
22813        // permission grants for these legacy apps.
22814        if (mPermissionReviewRequired) {
22815            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22816                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22817        }
22818    }
22819
22820    @Override
22821    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22822        mContext.enforceCallingOrSelfPermission(
22823                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22824                "Only package verification agents can read the verifier device identity");
22825
22826        synchronized (mPackages) {
22827            return mSettings.getVerifierDeviceIdentityLPw();
22828        }
22829    }
22830
22831    @Override
22832    public void setPermissionEnforced(String permission, boolean enforced) {
22833        // TODO: Now that we no longer change GID for storage, this should to away.
22834        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22835                "setPermissionEnforced");
22836        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22837            synchronized (mPackages) {
22838                if (mSettings.mReadExternalStorageEnforced == null
22839                        || mSettings.mReadExternalStorageEnforced != enforced) {
22840                    mSettings.mReadExternalStorageEnforced = enforced;
22841                    mSettings.writeLPr();
22842                }
22843            }
22844            // kill any non-foreground processes so we restart them and
22845            // grant/revoke the GID.
22846            final IActivityManager am = ActivityManager.getService();
22847            if (am != null) {
22848                final long token = Binder.clearCallingIdentity();
22849                try {
22850                    am.killProcessesBelowForeground("setPermissionEnforcement");
22851                } catch (RemoteException e) {
22852                } finally {
22853                    Binder.restoreCallingIdentity(token);
22854                }
22855            }
22856        } else {
22857            throw new IllegalArgumentException("No selective enforcement for " + permission);
22858        }
22859    }
22860
22861    @Override
22862    @Deprecated
22863    public boolean isPermissionEnforced(String permission) {
22864        return true;
22865    }
22866
22867    @Override
22868    public boolean isStorageLow() {
22869        final long token = Binder.clearCallingIdentity();
22870        try {
22871            final DeviceStorageMonitorInternal
22872                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22873            if (dsm != null) {
22874                return dsm.isMemoryLow();
22875            } else {
22876                return false;
22877            }
22878        } finally {
22879            Binder.restoreCallingIdentity(token);
22880        }
22881    }
22882
22883    @Override
22884    public IPackageInstaller getPackageInstaller() {
22885        return mInstallerService;
22886    }
22887
22888    private boolean userNeedsBadging(int userId) {
22889        int index = mUserNeedsBadging.indexOfKey(userId);
22890        if (index < 0) {
22891            final UserInfo userInfo;
22892            final long token = Binder.clearCallingIdentity();
22893            try {
22894                userInfo = sUserManager.getUserInfo(userId);
22895            } finally {
22896                Binder.restoreCallingIdentity(token);
22897            }
22898            final boolean b;
22899            if (userInfo != null && userInfo.isManagedProfile()) {
22900                b = true;
22901            } else {
22902                b = false;
22903            }
22904            mUserNeedsBadging.put(userId, b);
22905            return b;
22906        }
22907        return mUserNeedsBadging.valueAt(index);
22908    }
22909
22910    @Override
22911    public KeySet getKeySetByAlias(String packageName, String alias) {
22912        if (packageName == null || alias == null) {
22913            return null;
22914        }
22915        synchronized(mPackages) {
22916            final PackageParser.Package pkg = mPackages.get(packageName);
22917            if (pkg == null) {
22918                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22919                throw new IllegalArgumentException("Unknown package: " + packageName);
22920            }
22921            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22922            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22923        }
22924    }
22925
22926    @Override
22927    public KeySet getSigningKeySet(String packageName) {
22928        if (packageName == null) {
22929            return null;
22930        }
22931        synchronized(mPackages) {
22932            final PackageParser.Package pkg = mPackages.get(packageName);
22933            if (pkg == null) {
22934                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22935                throw new IllegalArgumentException("Unknown package: " + packageName);
22936            }
22937            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22938                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22939                throw new SecurityException("May not access signing KeySet of other apps.");
22940            }
22941            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22942            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22943        }
22944    }
22945
22946    @Override
22947    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22948        if (packageName == null || ks == null) {
22949            return false;
22950        }
22951        synchronized(mPackages) {
22952            final PackageParser.Package pkg = mPackages.get(packageName);
22953            if (pkg == null) {
22954                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22955                throw new IllegalArgumentException("Unknown package: " + packageName);
22956            }
22957            IBinder ksh = ks.getToken();
22958            if (ksh instanceof KeySetHandle) {
22959                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22960                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22961            }
22962            return false;
22963        }
22964    }
22965
22966    @Override
22967    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22968        if (packageName == null || ks == null) {
22969            return false;
22970        }
22971        synchronized(mPackages) {
22972            final PackageParser.Package pkg = mPackages.get(packageName);
22973            if (pkg == null) {
22974                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22975                throw new IllegalArgumentException("Unknown package: " + packageName);
22976            }
22977            IBinder ksh = ks.getToken();
22978            if (ksh instanceof KeySetHandle) {
22979                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22980                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22981            }
22982            return false;
22983        }
22984    }
22985
22986    private void deletePackageIfUnusedLPr(final String packageName) {
22987        PackageSetting ps = mSettings.mPackages.get(packageName);
22988        if (ps == null) {
22989            return;
22990        }
22991        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22992            // TODO Implement atomic delete if package is unused
22993            // It is currently possible that the package will be deleted even if it is installed
22994            // after this method returns.
22995            mHandler.post(new Runnable() {
22996                public void run() {
22997                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22998                            0, PackageManager.DELETE_ALL_USERS);
22999                }
23000            });
23001        }
23002    }
23003
23004    /**
23005     * Check and throw if the given before/after packages would be considered a
23006     * downgrade.
23007     */
23008    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23009            throws PackageManagerException {
23010        if (after.versionCode < before.mVersionCode) {
23011            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23012                    "Update version code " + after.versionCode + " is older than current "
23013                    + before.mVersionCode);
23014        } else if (after.versionCode == before.mVersionCode) {
23015            if (after.baseRevisionCode < before.baseRevisionCode) {
23016                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23017                        "Update base revision code " + after.baseRevisionCode
23018                        + " is older than current " + before.baseRevisionCode);
23019            }
23020
23021            if (!ArrayUtils.isEmpty(after.splitNames)) {
23022                for (int i = 0; i < after.splitNames.length; i++) {
23023                    final String splitName = after.splitNames[i];
23024                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23025                    if (j != -1) {
23026                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23027                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23028                                    "Update split " + splitName + " revision code "
23029                                    + after.splitRevisionCodes[i] + " is older than current "
23030                                    + before.splitRevisionCodes[j]);
23031                        }
23032                    }
23033                }
23034            }
23035        }
23036    }
23037
23038    private static class MoveCallbacks extends Handler {
23039        private static final int MSG_CREATED = 1;
23040        private static final int MSG_STATUS_CHANGED = 2;
23041
23042        private final RemoteCallbackList<IPackageMoveObserver>
23043                mCallbacks = new RemoteCallbackList<>();
23044
23045        private final SparseIntArray mLastStatus = new SparseIntArray();
23046
23047        public MoveCallbacks(Looper looper) {
23048            super(looper);
23049        }
23050
23051        public void register(IPackageMoveObserver callback) {
23052            mCallbacks.register(callback);
23053        }
23054
23055        public void unregister(IPackageMoveObserver callback) {
23056            mCallbacks.unregister(callback);
23057        }
23058
23059        @Override
23060        public void handleMessage(Message msg) {
23061            final SomeArgs args = (SomeArgs) msg.obj;
23062            final int n = mCallbacks.beginBroadcast();
23063            for (int i = 0; i < n; i++) {
23064                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23065                try {
23066                    invokeCallback(callback, msg.what, args);
23067                } catch (RemoteException ignored) {
23068                }
23069            }
23070            mCallbacks.finishBroadcast();
23071            args.recycle();
23072        }
23073
23074        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23075                throws RemoteException {
23076            switch (what) {
23077                case MSG_CREATED: {
23078                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23079                    break;
23080                }
23081                case MSG_STATUS_CHANGED: {
23082                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23083                    break;
23084                }
23085            }
23086        }
23087
23088        private void notifyCreated(int moveId, Bundle extras) {
23089            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23090
23091            final SomeArgs args = SomeArgs.obtain();
23092            args.argi1 = moveId;
23093            args.arg2 = extras;
23094            obtainMessage(MSG_CREATED, args).sendToTarget();
23095        }
23096
23097        private void notifyStatusChanged(int moveId, int status) {
23098            notifyStatusChanged(moveId, status, -1);
23099        }
23100
23101        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23102            Slog.v(TAG, "Move " + moveId + " status " + status);
23103
23104            final SomeArgs args = SomeArgs.obtain();
23105            args.argi1 = moveId;
23106            args.argi2 = status;
23107            args.arg3 = estMillis;
23108            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23109
23110            synchronized (mLastStatus) {
23111                mLastStatus.put(moveId, status);
23112            }
23113        }
23114    }
23115
23116    private final static class OnPermissionChangeListeners extends Handler {
23117        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23118
23119        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23120                new RemoteCallbackList<>();
23121
23122        public OnPermissionChangeListeners(Looper looper) {
23123            super(looper);
23124        }
23125
23126        @Override
23127        public void handleMessage(Message msg) {
23128            switch (msg.what) {
23129                case MSG_ON_PERMISSIONS_CHANGED: {
23130                    final int uid = msg.arg1;
23131                    handleOnPermissionsChanged(uid);
23132                } break;
23133            }
23134        }
23135
23136        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23137            mPermissionListeners.register(listener);
23138
23139        }
23140
23141        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23142            mPermissionListeners.unregister(listener);
23143        }
23144
23145        public void onPermissionsChanged(int uid) {
23146            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23147                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23148            }
23149        }
23150
23151        private void handleOnPermissionsChanged(int uid) {
23152            final int count = mPermissionListeners.beginBroadcast();
23153            try {
23154                for (int i = 0; i < count; i++) {
23155                    IOnPermissionsChangeListener callback = mPermissionListeners
23156                            .getBroadcastItem(i);
23157                    try {
23158                        callback.onPermissionsChanged(uid);
23159                    } catch (RemoteException e) {
23160                        Log.e(TAG, "Permission listener is dead", e);
23161                    }
23162                }
23163            } finally {
23164                mPermissionListeners.finishBroadcast();
23165            }
23166        }
23167    }
23168
23169    private class PackageManagerInternalImpl extends PackageManagerInternal {
23170        @Override
23171        public void setLocationPackagesProvider(PackagesProvider provider) {
23172            synchronized (mPackages) {
23173                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23174            }
23175        }
23176
23177        @Override
23178        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23179            synchronized (mPackages) {
23180                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23181            }
23182        }
23183
23184        @Override
23185        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23186            synchronized (mPackages) {
23187                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23188            }
23189        }
23190
23191        @Override
23192        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23193            synchronized (mPackages) {
23194                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23195            }
23196        }
23197
23198        @Override
23199        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23200            synchronized (mPackages) {
23201                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23202            }
23203        }
23204
23205        @Override
23206        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23207            synchronized (mPackages) {
23208                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23209            }
23210        }
23211
23212        @Override
23213        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23214            synchronized (mPackages) {
23215                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23216                        packageName, userId);
23217            }
23218        }
23219
23220        @Override
23221        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23222            synchronized (mPackages) {
23223                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23224                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23225                        packageName, userId);
23226            }
23227        }
23228
23229        @Override
23230        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23231            synchronized (mPackages) {
23232                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23233                        packageName, userId);
23234            }
23235        }
23236
23237        @Override
23238        public void setKeepUninstalledPackages(final List<String> packageList) {
23239            Preconditions.checkNotNull(packageList);
23240            List<String> removedFromList = null;
23241            synchronized (mPackages) {
23242                if (mKeepUninstalledPackages != null) {
23243                    final int packagesCount = mKeepUninstalledPackages.size();
23244                    for (int i = 0; i < packagesCount; i++) {
23245                        String oldPackage = mKeepUninstalledPackages.get(i);
23246                        if (packageList != null && packageList.contains(oldPackage)) {
23247                            continue;
23248                        }
23249                        if (removedFromList == null) {
23250                            removedFromList = new ArrayList<>();
23251                        }
23252                        removedFromList.add(oldPackage);
23253                    }
23254                }
23255                mKeepUninstalledPackages = new ArrayList<>(packageList);
23256                if (removedFromList != null) {
23257                    final int removedCount = removedFromList.size();
23258                    for (int i = 0; i < removedCount; i++) {
23259                        deletePackageIfUnusedLPr(removedFromList.get(i));
23260                    }
23261                }
23262            }
23263        }
23264
23265        @Override
23266        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23267            synchronized (mPackages) {
23268                // If we do not support permission review, done.
23269                if (!mPermissionReviewRequired) {
23270                    return false;
23271                }
23272
23273                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23274                if (packageSetting == null) {
23275                    return false;
23276                }
23277
23278                // Permission review applies only to apps not supporting the new permission model.
23279                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23280                    return false;
23281                }
23282
23283                // Legacy apps have the permission and get user consent on launch.
23284                PermissionsState permissionsState = packageSetting.getPermissionsState();
23285                return permissionsState.isPermissionReviewRequired(userId);
23286            }
23287        }
23288
23289        @Override
23290        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23291            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23292        }
23293
23294        @Override
23295        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23296                int userId) {
23297            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23298        }
23299
23300        @Override
23301        public void setDeviceAndProfileOwnerPackages(
23302                int deviceOwnerUserId, String deviceOwnerPackage,
23303                SparseArray<String> profileOwnerPackages) {
23304            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23305                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23306        }
23307
23308        @Override
23309        public boolean isPackageDataProtected(int userId, String packageName) {
23310            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23311        }
23312
23313        @Override
23314        public boolean isPackageEphemeral(int userId, String packageName) {
23315            synchronized (mPackages) {
23316                final PackageSetting ps = mSettings.mPackages.get(packageName);
23317                return ps != null ? ps.getInstantApp(userId) : false;
23318            }
23319        }
23320
23321        @Override
23322        public boolean wasPackageEverLaunched(String packageName, int userId) {
23323            synchronized (mPackages) {
23324                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23325            }
23326        }
23327
23328        @Override
23329        public void grantRuntimePermission(String packageName, String name, int userId,
23330                boolean overridePolicy) {
23331            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23332                    overridePolicy);
23333        }
23334
23335        @Override
23336        public void revokeRuntimePermission(String packageName, String name, int userId,
23337                boolean overridePolicy) {
23338            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23339                    overridePolicy);
23340        }
23341
23342        @Override
23343        public String getNameForUid(int uid) {
23344            return PackageManagerService.this.getNameForUid(uid);
23345        }
23346
23347        @Override
23348        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23349                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23350            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23351                    responseObj, origIntent, resolvedType, callingPackage, userId);
23352        }
23353
23354        @Override
23355        public void grantEphemeralAccess(int userId, Intent intent,
23356                int targetAppId, int ephemeralAppId) {
23357            synchronized (mPackages) {
23358                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23359                        targetAppId, ephemeralAppId);
23360            }
23361        }
23362
23363        @Override
23364        public boolean isInstantAppInstallerComponent(ComponentName component) {
23365            synchronized (mPackages) {
23366                return mInstantAppInstallerActivity != null
23367                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23368            }
23369        }
23370
23371        @Override
23372        public void pruneInstantApps() {
23373            synchronized (mPackages) {
23374                mInstantAppRegistry.pruneInstantAppsLPw();
23375            }
23376        }
23377
23378        @Override
23379        public String getSetupWizardPackageName() {
23380            return mSetupWizardPackage;
23381        }
23382
23383        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23384            if (policy != null) {
23385                mExternalSourcesPolicy = policy;
23386            }
23387        }
23388
23389        @Override
23390        public boolean isPackagePersistent(String packageName) {
23391            synchronized (mPackages) {
23392                PackageParser.Package pkg = mPackages.get(packageName);
23393                return pkg != null
23394                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23395                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23396                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23397                        : false;
23398            }
23399        }
23400
23401        @Override
23402        public List<PackageInfo> getOverlayPackages(int userId) {
23403            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23404            synchronized (mPackages) {
23405                for (PackageParser.Package p : mPackages.values()) {
23406                    if (p.mOverlayTarget != null) {
23407                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23408                        if (pkg != null) {
23409                            overlayPackages.add(pkg);
23410                        }
23411                    }
23412                }
23413            }
23414            return overlayPackages;
23415        }
23416
23417        @Override
23418        public List<String> getTargetPackageNames(int userId) {
23419            List<String> targetPackages = new ArrayList<>();
23420            synchronized (mPackages) {
23421                for (PackageParser.Package p : mPackages.values()) {
23422                    if (p.mOverlayTarget == null) {
23423                        targetPackages.add(p.packageName);
23424                    }
23425                }
23426            }
23427            return targetPackages;
23428        }
23429
23430        @Override
23431        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23432                @Nullable List<String> overlayPackageNames) {
23433            synchronized (mPackages) {
23434                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23435                    Slog.e(TAG, "failed to find package " + targetPackageName);
23436                    return false;
23437                }
23438
23439                ArrayList<String> paths = null;
23440                if (overlayPackageNames != null) {
23441                    final int N = overlayPackageNames.size();
23442                    paths = new ArrayList<>(N);
23443                    for (int i = 0; i < N; i++) {
23444                        final String packageName = overlayPackageNames.get(i);
23445                        final PackageParser.Package pkg = mPackages.get(packageName);
23446                        if (pkg == null) {
23447                            Slog.e(TAG, "failed to find package " + packageName);
23448                            return false;
23449                        }
23450                        paths.add(pkg.baseCodePath);
23451                    }
23452                }
23453
23454                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23455                    mEnabledOverlayPaths.get(userId);
23456                if (userSpecificOverlays == null) {
23457                    userSpecificOverlays = new ArrayMap<>();
23458                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23459                }
23460
23461                if (paths != null && paths.size() > 0) {
23462                    userSpecificOverlays.put(targetPackageName, paths);
23463                } else {
23464                    userSpecificOverlays.remove(targetPackageName);
23465                }
23466                return true;
23467            }
23468        }
23469
23470        @Override
23471        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23472                int flags, int userId) {
23473            return resolveIntentInternal(
23474                    intent, resolvedType, flags, userId, true /*includeInstantApps*/);
23475        }
23476
23477        @Override
23478        public ResolveInfo resolveService(Intent intent, String resolvedType,
23479                int flags, int userId, int callingUid) {
23480            return resolveServiceInternal(
23481                    intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/);
23482        }
23483
23484        @Override
23485        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23486            synchronized (mPackages) {
23487                mIsolatedOwners.put(isolatedUid, ownerUid);
23488            }
23489        }
23490
23491        @Override
23492        public void removeIsolatedUid(int isolatedUid) {
23493            synchronized (mPackages) {
23494                mIsolatedOwners.delete(isolatedUid);
23495            }
23496        }
23497    }
23498
23499    @Override
23500    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23501        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23502        synchronized (mPackages) {
23503            final long identity = Binder.clearCallingIdentity();
23504            try {
23505                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23506                        packageNames, userId);
23507            } finally {
23508                Binder.restoreCallingIdentity(identity);
23509            }
23510        }
23511    }
23512
23513    @Override
23514    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23515        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23516        synchronized (mPackages) {
23517            final long identity = Binder.clearCallingIdentity();
23518            try {
23519                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23520                        packageNames, userId);
23521            } finally {
23522                Binder.restoreCallingIdentity(identity);
23523            }
23524        }
23525    }
23526
23527    private static void enforceSystemOrPhoneCaller(String tag) {
23528        int callingUid = Binder.getCallingUid();
23529        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23530            throw new SecurityException(
23531                    "Cannot call " + tag + " from UID " + callingUid);
23532        }
23533    }
23534
23535    boolean isHistoricalPackageUsageAvailable() {
23536        return mPackageUsage.isHistoricalPackageUsageAvailable();
23537    }
23538
23539    /**
23540     * Return a <b>copy</b> of the collection of packages known to the package manager.
23541     * @return A copy of the values of mPackages.
23542     */
23543    Collection<PackageParser.Package> getPackages() {
23544        synchronized (mPackages) {
23545            return new ArrayList<>(mPackages.values());
23546        }
23547    }
23548
23549    /**
23550     * Logs process start information (including base APK hash) to the security log.
23551     * @hide
23552     */
23553    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23554            String apkFile, int pid) {
23555        if (!SecurityLog.isLoggingEnabled()) {
23556            return;
23557        }
23558        Bundle data = new Bundle();
23559        data.putLong("startTimestamp", System.currentTimeMillis());
23560        data.putString("processName", processName);
23561        data.putInt("uid", uid);
23562        data.putString("seinfo", seinfo);
23563        data.putString("apkFile", apkFile);
23564        data.putInt("pid", pid);
23565        Message msg = mProcessLoggingHandler.obtainMessage(
23566                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23567        msg.setData(data);
23568        mProcessLoggingHandler.sendMessage(msg);
23569    }
23570
23571    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23572        return mCompilerStats.getPackageStats(pkgName);
23573    }
23574
23575    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23576        return getOrCreateCompilerPackageStats(pkg.packageName);
23577    }
23578
23579    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23580        return mCompilerStats.getOrCreatePackageStats(pkgName);
23581    }
23582
23583    public void deleteCompilerPackageStats(String pkgName) {
23584        mCompilerStats.deletePackageStats(pkgName);
23585    }
23586
23587    @Override
23588    public int getInstallReason(String packageName, int userId) {
23589        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23590                true /* requireFullPermission */, false /* checkShell */,
23591                "get install reason");
23592        synchronized (mPackages) {
23593            final PackageSetting ps = mSettings.mPackages.get(packageName);
23594            if (ps != null) {
23595                return ps.getInstallReason(userId);
23596            }
23597        }
23598        return PackageManager.INSTALL_REASON_UNKNOWN;
23599    }
23600
23601    @Override
23602    public boolean canRequestPackageInstalls(String packageName, int userId) {
23603        int callingUid = Binder.getCallingUid();
23604        int uid = getPackageUid(packageName, 0, userId);
23605        if (callingUid != uid && callingUid != Process.ROOT_UID
23606                && callingUid != Process.SYSTEM_UID) {
23607            throw new SecurityException(
23608                    "Caller uid " + callingUid + " does not own package " + packageName);
23609        }
23610        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23611        if (info == null) {
23612            return false;
23613        }
23614        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23615            throw new UnsupportedOperationException(
23616                    "Operation only supported on apps targeting Android O or higher");
23617        }
23618        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23619        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23620        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23621            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23622        }
23623        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23624            return false;
23625        }
23626        if (mExternalSourcesPolicy != null) {
23627            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23628            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23629                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23630            }
23631        }
23632        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23633    }
23634
23635    @Override
23636    public ComponentName getInstantAppResolverSettingsComponent() {
23637        return mInstantAppResolverSettingsComponent;
23638    }
23639
23640    @Override
23641    public ComponentName getInstantAppInstallerComponent() {
23642        return mInstantAppInstallerActivity == null
23643                ? null : mInstantAppInstallerActivity.getComponentName();
23644    }
23645}
23646