PackageManagerService.java revision b70e4bfe0776a3446ccfddd5a10b1ff155f60e34
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.Installer.DEXOPT_PUBLIC;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ChangedPackages;
130import android.content.pm.ComponentInfo;
131import android.content.pm.InstantAppRequest;
132import android.content.pm.AuxiliaryResolveInfo;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IOnPermissionsChangeListener;
136import android.content.pm.IPackageDataObserver;
137import android.content.pm.IPackageDeleteObserver;
138import android.content.pm.IPackageDeleteObserver2;
139import android.content.pm.IPackageInstallObserver2;
140import android.content.pm.IPackageInstaller;
141import android.content.pm.IPackageManager;
142import android.content.pm.IPackageMoveObserver;
143import android.content.pm.IPackageStatsObserver;
144import android.content.pm.InstantAppInfo;
145import android.content.pm.InstantAppResolveInfo;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.SELinuxUtil;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
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.FastPrintWriter;
258import com.android.internal.util.FastXmlSerializer;
259import com.android.internal.util.IndentingPrintWriter;
260import com.android.internal.util.Preconditions;
261import com.android.internal.util.XmlUtils;
262import com.android.server.AttributeCache;
263import com.android.server.DeviceIdleController;
264import com.android.server.EventLogTags;
265import com.android.server.FgThread;
266import com.android.server.IntentResolver;
267import com.android.server.LocalServices;
268import com.android.server.LockGuard;
269import com.android.server.ServiceThread;
270import com.android.server.SystemConfig;
271import com.android.server.SystemServerInitThreadPool;
272import com.android.server.Watchdog;
273import com.android.server.net.NetworkPolicyManagerInternal;
274import com.android.server.pm.BackgroundDexOptService;
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.FileNotFoundException;
301import java.io.FileOutputStream;
302import java.io.FileReader;
303import java.io.FilenameFilter;
304import java.io.IOException;
305import java.io.PrintWriter;
306import java.nio.charset.StandardCharsets;
307import java.security.DigestInputStream;
308import java.security.MessageDigest;
309import java.security.NoSuchAlgorithmException;
310import java.security.PublicKey;
311import java.security.SecureRandom;
312import java.security.cert.Certificate;
313import java.security.cert.CertificateEncodingException;
314import java.security.cert.CertificateException;
315import java.text.SimpleDateFormat;
316import java.util.ArrayList;
317import java.util.Arrays;
318import java.util.Collection;
319import java.util.Collections;
320import java.util.Comparator;
321import java.util.Date;
322import java.util.HashMap;
323import java.util.HashSet;
324import java.util.Iterator;
325import java.util.List;
326import java.util.Map;
327import java.util.Objects;
328import java.util.Set;
329import java.util.concurrent.CountDownLatch;
330import java.util.concurrent.Future;
331import java.util.concurrent.TimeUnit;
332import java.util.concurrent.atomic.AtomicBoolean;
333import java.util.concurrent.atomic.AtomicInteger;
334
335/**
336 * Keep track of all those APKs everywhere.
337 * <p>
338 * Internally there are two important locks:
339 * <ul>
340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
341 * and other related state. It is a fine-grained lock that should only be held
342 * momentarily, as it's one of the most contended locks in the system.
343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
344 * operations typically involve heavy lifting of application data on disk. Since
345 * {@code installd} is single-threaded, and it's operations can often be slow,
346 * this lock should never be acquired while already holding {@link #mPackages}.
347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
348 * holding {@link #mInstallLock}.
349 * </ul>
350 * Many internal methods rely on the caller to hold the appropriate locks, and
351 * this contract is expressed through method name suffixes:
352 * <ul>
353 * <li>fooLI(): the caller must hold {@link #mInstallLock}
354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
355 * being modified must be frozen
356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
358 * </ul>
359 * <p>
360 * Because this class is very central to the platform's security; please run all
361 * CTS and unit tests whenever making modifications:
362 *
363 * <pre>
364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
366 * </pre>
367 */
368public class PackageManagerService extends IPackageManager.Stub {
369    static final String TAG = "PackageManager";
370    static final boolean DEBUG_SETTINGS = false;
371    static final boolean DEBUG_PREFERRED = false;
372    static final boolean DEBUG_UPGRADE = false;
373    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
374    private static final boolean DEBUG_BACKUP = false;
375    private static final boolean DEBUG_INSTALL = false;
376    private static final boolean DEBUG_REMOVE = false;
377    private static final boolean DEBUG_BROADCASTS = false;
378    private static final boolean DEBUG_SHOW_INFO = false;
379    private static final boolean DEBUG_PACKAGE_INFO = false;
380    private static final boolean DEBUG_INTENT_MATCHING = false;
381    private static final boolean DEBUG_PACKAGE_SCANNING = false;
382    private static final boolean DEBUG_VERIFY = false;
383    private static final boolean DEBUG_FILTERS = false;
384
385    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
386    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
387    // user, but by default initialize to this.
388    public static final boolean DEBUG_DEXOPT = false;
389
390    private static final boolean DEBUG_ABI_SELECTION = false;
391    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
392    private static final boolean DEBUG_TRIAGED_MISSING = false;
393    private static final boolean DEBUG_APP_DATA = false;
394
395    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
396    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
397
398    private static final boolean DISABLE_EPHEMERAL_APPS = false;
399    private static final boolean HIDE_EPHEMERAL_APIS = false;
400
401    private static final boolean ENABLE_FREE_CACHE_V2 =
402            SystemProperties.getBoolean("fw.free_cache_v2", true);
403
404    private static final int RADIO_UID = Process.PHONE_UID;
405    private static final int LOG_UID = Process.LOG_UID;
406    private static final int NFC_UID = Process.NFC_UID;
407    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
408    private static final int SHELL_UID = Process.SHELL_UID;
409
410    // Cap the size of permission trees that 3rd party apps can define
411    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
412
413    // Suffix used during package installation when copying/moving
414    // package apks to install directory.
415    private static final String INSTALL_PACKAGE_SUFFIX = "-";
416
417    static final int SCAN_NO_DEX = 1<<1;
418    static final int SCAN_FORCE_DEX = 1<<2;
419    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
420    static final int SCAN_NEW_INSTALL = 1<<4;
421    static final int SCAN_UPDATE_TIME = 1<<5;
422    static final int SCAN_BOOTING = 1<<6;
423    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
424    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
425    static final int SCAN_REPLACING = 1<<9;
426    static final int SCAN_REQUIRE_KNOWN = 1<<10;
427    static final int SCAN_MOVE = 1<<11;
428    static final int SCAN_INITIAL = 1<<12;
429    static final int SCAN_CHECK_ONLY = 1<<13;
430    static final int SCAN_DONT_KILL_APP = 1<<14;
431    static final int SCAN_IGNORE_FROZEN = 1<<15;
432    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
433    static final int SCAN_AS_INSTANT_APP = 1<<17;
434    static final int SCAN_AS_FULL_APP = 1<<18;
435    /** Should not be with the scan flags */
436    static final int FLAGS_REMOVE_CHATTY = 1<<31;
437
438    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
439
440    private static final int[] EMPTY_INT_ARRAY = new int[0];
441
442    /**
443     * Timeout (in milliseconds) after which the watchdog should declare that
444     * our handler thread is wedged.  The usual default for such things is one
445     * minute but we sometimes do very lengthy I/O operations on this thread,
446     * such as installing multi-gigabyte applications, so ours needs to be longer.
447     */
448    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
449
450    /**
451     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
452     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
453     * settings entry if available, otherwise we use the hardcoded default.  If it's been
454     * more than this long since the last fstrim, we force one during the boot sequence.
455     *
456     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
457     * one gets run at the next available charging+idle time.  This final mandatory
458     * no-fstrim check kicks in only of the other scheduling criteria is never met.
459     */
460    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
461
462    /**
463     * Whether verification is enabled by default.
464     */
465    private static final boolean DEFAULT_VERIFY_ENABLE = true;
466
467    /**
468     * The default maximum time to wait for the verification agent to return in
469     * milliseconds.
470     */
471    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
472
473    /**
474     * The default response for package verification timeout.
475     *
476     * This can be either PackageManager.VERIFICATION_ALLOW or
477     * PackageManager.VERIFICATION_REJECT.
478     */
479    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
480
481    static final String PLATFORM_PACKAGE_NAME = "android";
482
483    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
484
485    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
486            DEFAULT_CONTAINER_PACKAGE,
487            "com.android.defcontainer.DefaultContainerService");
488
489    private static final String KILL_APP_REASON_GIDS_CHANGED =
490            "permission grant or revoke changed gids";
491
492    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
493            "permissions revoked";
494
495    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
496
497    private static final String PACKAGE_SCHEME = "package";
498
499    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
500
501    /** Permission grant: not grant the permission. */
502    private static final int GRANT_DENIED = 1;
503
504    /** Permission grant: grant the permission as an install permission. */
505    private static final int GRANT_INSTALL = 2;
506
507    /** Permission grant: grant the permission as a runtime one. */
508    private static final int GRANT_RUNTIME = 3;
509
510    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
511    private static final int GRANT_UPGRADE = 4;
512
513    /** Canonical intent used to identify what counts as a "web browser" app */
514    private static final Intent sBrowserIntent;
515    static {
516        sBrowserIntent = new Intent();
517        sBrowserIntent.setAction(Intent.ACTION_VIEW);
518        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
519        sBrowserIntent.setData(Uri.parse("http:"));
520    }
521
522    /**
523     * The set of all protected actions [i.e. those actions for which a high priority
524     * intent filter is disallowed].
525     */
526    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
527    static {
528        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
530        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
531        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
532    }
533
534    // Compilation reasons.
535    public static final int REASON_FIRST_BOOT = 0;
536    public static final int REASON_BOOT = 1;
537    public static final int REASON_INSTALL = 2;
538    public static final int REASON_BACKGROUND_DEXOPT = 3;
539    public static final int REASON_AB_OTA = 4;
540    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
541    public static final int REASON_SHARED_APK = 6;
542    public static final int REASON_FORCED_DEXOPT = 7;
543
544    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
545
546    /** All dangerous permission names in the same order as the events in MetricsEvent */
547    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
548            Manifest.permission.READ_CALENDAR,
549            Manifest.permission.WRITE_CALENDAR,
550            Manifest.permission.CAMERA,
551            Manifest.permission.READ_CONTACTS,
552            Manifest.permission.WRITE_CONTACTS,
553            Manifest.permission.GET_ACCOUNTS,
554            Manifest.permission.ACCESS_FINE_LOCATION,
555            Manifest.permission.ACCESS_COARSE_LOCATION,
556            Manifest.permission.RECORD_AUDIO,
557            Manifest.permission.READ_PHONE_STATE,
558            Manifest.permission.CALL_PHONE,
559            Manifest.permission.READ_CALL_LOG,
560            Manifest.permission.WRITE_CALL_LOG,
561            Manifest.permission.ADD_VOICEMAIL,
562            Manifest.permission.USE_SIP,
563            Manifest.permission.PROCESS_OUTGOING_CALLS,
564            Manifest.permission.READ_CELL_BROADCASTS,
565            Manifest.permission.BODY_SENSORS,
566            Manifest.permission.SEND_SMS,
567            Manifest.permission.RECEIVE_SMS,
568            Manifest.permission.READ_SMS,
569            Manifest.permission.RECEIVE_WAP_PUSH,
570            Manifest.permission.RECEIVE_MMS,
571            Manifest.permission.READ_EXTERNAL_STORAGE,
572            Manifest.permission.WRITE_EXTERNAL_STORAGE,
573            Manifest.permission.READ_PHONE_NUMBER,
574            Manifest.permission.ANSWER_PHONE_CALLS);
575
576
577    /**
578     * Version number for the package parser cache. Increment this whenever the format or
579     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
580     */
581    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
582
583    /**
584     * Whether the package parser cache is enabled.
585     */
586    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
587
588    final ServiceThread mHandlerThread;
589
590    final PackageHandler mHandler;
591
592    private final ProcessLoggingHandler mProcessLoggingHandler;
593
594    /**
595     * Messages for {@link #mHandler} that need to wait for system ready before
596     * being dispatched.
597     */
598    private ArrayList<Message> mPostSystemReadyMessages;
599
600    final int mSdkVersion = Build.VERSION.SDK_INT;
601
602    final Context mContext;
603    final boolean mFactoryTest;
604    final boolean mOnlyCore;
605    final DisplayMetrics mMetrics;
606    final int mDefParseFlags;
607    final String[] mSeparateProcesses;
608    final boolean mIsUpgrade;
609    final boolean mIsPreNUpgrade;
610    final boolean mIsPreNMR1Upgrade;
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    // List of APK paths to load for each user and package. This data is never
656    // persisted by the package manager. Instead, the overlay manager will
657    // ensure the data is up-to-date in runtime.
658    @GuardedBy("mPackages")
659    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
660        new SparseArray<ArrayMap<String, ArrayList<String>>>();
661
662    /**
663     * Tracks new system packages [received in an OTA] that we expect to
664     * find updated user-installed versions. Keys are package name, values
665     * are package location.
666     */
667    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
668    /**
669     * Tracks high priority intent filters for protected actions. During boot, certain
670     * filter actions are protected and should never be allowed to have a high priority
671     * intent filter for them. However, there is one, and only one exception -- the
672     * setup wizard. It must be able to define a high priority intent filter for these
673     * actions to ensure there are no escapes from the wizard. We need to delay processing
674     * of these during boot as we need to look at all of the system packages in order
675     * to know which component is the setup wizard.
676     */
677    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
678    /**
679     * Whether or not processing protected filters should be deferred.
680     */
681    private boolean mDeferProtectedFilters = true;
682
683    /**
684     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
685     */
686    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
687    /**
688     * Whether or not system app permissions should be promoted from install to runtime.
689     */
690    boolean mPromoteSystemApps;
691
692    @GuardedBy("mPackages")
693    final Settings mSettings;
694
695    /**
696     * Set of package names that are currently "frozen", which means active
697     * surgery is being done on the code/data for that package. The platform
698     * will refuse to launch frozen packages to avoid race conditions.
699     *
700     * @see PackageFreezer
701     */
702    @GuardedBy("mPackages")
703    final ArraySet<String> mFrozenPackages = new ArraySet<>();
704
705    final ProtectedPackages mProtectedPackages;
706
707    boolean mFirstBoot;
708
709    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
710
711    // System configuration read by SystemConfig.
712    final int[] mGlobalGids;
713    final SparseArray<ArraySet<String>> mSystemPermissions;
714    @GuardedBy("mAvailableFeatures")
715    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
716
717    // If mac_permissions.xml was found for seinfo labeling.
718    boolean mFoundPolicyFile;
719
720    private final InstantAppRegistry mInstantAppRegistry;
721
722    @GuardedBy("mPackages")
723    int mChangedPackagesSequenceNumber;
724    /**
725     * List of changed [installed, removed or updated] packages.
726     * mapping from user id -> sequence number -> package name
727     */
728    @GuardedBy("mPackages")
729    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
730    /**
731     * The sequence number of the last change to a package.
732     * mapping from user id -> package name -> sequence number
733     */
734    @GuardedBy("mPackages")
735    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
736
737    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
738        @Override public boolean hasFeature(String feature) {
739            return PackageManagerService.this.hasSystemFeature(feature, 0);
740        }
741    };
742
743    public static final class SharedLibraryEntry {
744        public final String path;
745        public final String apk;
746        public final SharedLibraryInfo info;
747
748        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
749                String declaringPackageName, int declaringPackageVersionCode) {
750            path = _path;
751            apk = _apk;
752            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
753                    declaringPackageName, declaringPackageVersionCode), null);
754        }
755    }
756
757    // Currently known shared libraries.
758    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
759    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
760            new ArrayMap<>();
761
762    // All available activities, for your resolving pleasure.
763    final ActivityIntentResolver mActivities =
764            new ActivityIntentResolver();
765
766    // All available receivers, for your resolving pleasure.
767    final ActivityIntentResolver mReceivers =
768            new ActivityIntentResolver();
769
770    // All available services, for your resolving pleasure.
771    final ServiceIntentResolver mServices = new ServiceIntentResolver();
772
773    // All available providers, for your resolving pleasure.
774    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
775
776    // Mapping from provider base names (first directory in content URI codePath)
777    // to the provider information.
778    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
779            new ArrayMap<String, PackageParser.Provider>();
780
781    // Mapping from instrumentation class names to info about them.
782    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
783            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
784
785    // Mapping from permission names to info about them.
786    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
787            new ArrayMap<String, PackageParser.PermissionGroup>();
788
789    // Packages whose data we have transfered into another package, thus
790    // should no longer exist.
791    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
792
793    // Broadcast actions that are only available to the system.
794    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
795
796    /** List of packages waiting for verification. */
797    final SparseArray<PackageVerificationState> mPendingVerification
798            = new SparseArray<PackageVerificationState>();
799
800    /** Set of packages associated with each app op permission. */
801    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
802
803    final PackageInstallerService mInstallerService;
804
805    private final PackageDexOptimizer mPackageDexOptimizer;
806    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
807    // is used by other apps).
808    private final DexManager mDexManager;
809
810    private AtomicInteger mNextMoveId = new AtomicInteger();
811    private final MoveCallbacks mMoveCallbacks;
812
813    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
814
815    // Cache of users who need badging.
816    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
817
818    /** Token for keys in mPendingVerification. */
819    private int mPendingVerificationToken = 0;
820
821    volatile boolean mSystemReady;
822    volatile boolean mSafeMode;
823    volatile boolean mHasSystemUidErrors;
824
825    ApplicationInfo mAndroidApplication;
826    final ActivityInfo mResolveActivity = new ActivityInfo();
827    final ResolveInfo mResolveInfo = new ResolveInfo();
828    ComponentName mResolveComponentName;
829    PackageParser.Package mPlatformPackage;
830    ComponentName mCustomResolverComponentName;
831
832    boolean mResolverReplaced = false;
833
834    private final @Nullable ComponentName mIntentFilterVerifierComponent;
835    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
836
837    private int mIntentFilterVerificationToken = 0;
838
839    /** The service connection to the ephemeral resolver */
840    final EphemeralResolverConnection mInstantAppResolverConnection;
841
842    /** Component used to install ephemeral applications */
843    ComponentName mInstantAppInstallerComponent;
844    final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo();
845    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
846
847    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
848            = new SparseArray<IntentFilterVerificationState>();
849
850    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
851
852    // List of packages names to keep cached, even if they are uninstalled for all users
853    private List<String> mKeepUninstalledPackages;
854
855    private UserManagerInternal mUserManagerInternal;
856
857    private DeviceIdleController.LocalService mDeviceIdleController;
858
859    private File mCacheDir;
860
861    private ArraySet<String> mPrivappPermissionsViolations;
862
863    private Future<?> mPrepareAppDataFuture;
864
865    private static class IFVerificationParams {
866        PackageParser.Package pkg;
867        boolean replacing;
868        int userId;
869        int verifierUid;
870
871        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
872                int _userId, int _verifierUid) {
873            pkg = _pkg;
874            replacing = _replacing;
875            userId = _userId;
876            replacing = _replacing;
877            verifierUid = _verifierUid;
878        }
879    }
880
881    private interface IntentFilterVerifier<T extends IntentFilter> {
882        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
883                                               T filter, String packageName);
884        void startVerifications(int userId);
885        void receiveVerificationResponse(int verificationId);
886    }
887
888    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
889        private Context mContext;
890        private ComponentName mIntentFilterVerifierComponent;
891        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
892
893        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
894            mContext = context;
895            mIntentFilterVerifierComponent = verifierComponent;
896        }
897
898        private String getDefaultScheme() {
899            return IntentFilter.SCHEME_HTTPS;
900        }
901
902        @Override
903        public void startVerifications(int userId) {
904            // Launch verifications requests
905            int count = mCurrentIntentFilterVerifications.size();
906            for (int n=0; n<count; n++) {
907                int verificationId = mCurrentIntentFilterVerifications.get(n);
908                final IntentFilterVerificationState ivs =
909                        mIntentFilterVerificationStates.get(verificationId);
910
911                String packageName = ivs.getPackageName();
912
913                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
914                final int filterCount = filters.size();
915                ArraySet<String> domainsSet = new ArraySet<>();
916                for (int m=0; m<filterCount; m++) {
917                    PackageParser.ActivityIntentInfo filter = filters.get(m);
918                    domainsSet.addAll(filter.getHostsList());
919                }
920                synchronized (mPackages) {
921                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
922                            packageName, domainsSet) != null) {
923                        scheduleWriteSettingsLocked();
924                    }
925                }
926                sendVerificationRequest(userId, verificationId, ivs);
927            }
928            mCurrentIntentFilterVerifications.clear();
929        }
930
931        private void sendVerificationRequest(int userId, int verificationId,
932                IntentFilterVerificationState ivs) {
933
934            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
935            verificationIntent.putExtra(
936                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
937                    verificationId);
938            verificationIntent.putExtra(
939                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
940                    getDefaultScheme());
941            verificationIntent.putExtra(
942                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
943                    ivs.getHostsString());
944            verificationIntent.putExtra(
945                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
946                    ivs.getPackageName());
947            verificationIntent.setComponent(mIntentFilterVerifierComponent);
948            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
949
950            UserHandle user = new UserHandle(userId);
951            mContext.sendBroadcastAsUser(verificationIntent, user);
952            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
953                    "Sending IntentFilter verification broadcast");
954        }
955
956        public void receiveVerificationResponse(int verificationId) {
957            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
958
959            final boolean verified = ivs.isVerified();
960
961            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
962            final int count = filters.size();
963            if (DEBUG_DOMAIN_VERIFICATION) {
964                Slog.i(TAG, "Received verification response " + verificationId
965                        + " for " + count + " filters, verified=" + verified);
966            }
967            for (int n=0; n<count; n++) {
968                PackageParser.ActivityIntentInfo filter = filters.get(n);
969                filter.setVerified(verified);
970
971                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
972                        + " verified with result:" + verified + " and hosts:"
973                        + ivs.getHostsString());
974            }
975
976            mIntentFilterVerificationStates.remove(verificationId);
977
978            final String packageName = ivs.getPackageName();
979            IntentFilterVerificationInfo ivi = null;
980
981            synchronized (mPackages) {
982                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
983            }
984            if (ivi == null) {
985                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
986                        + verificationId + " packageName:" + packageName);
987                return;
988            }
989            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
990                    "Updating IntentFilterVerificationInfo for package " + packageName
991                            +" verificationId:" + verificationId);
992
993            synchronized (mPackages) {
994                if (verified) {
995                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
996                } else {
997                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
998                }
999                scheduleWriteSettingsLocked();
1000
1001                final int userId = ivs.getUserId();
1002                if (userId != UserHandle.USER_ALL) {
1003                    final int userStatus =
1004                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1005
1006                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1007                    boolean needUpdate = false;
1008
1009                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1010                    // already been set by the User thru the Disambiguation dialog
1011                    switch (userStatus) {
1012                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1013                            if (verified) {
1014                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1015                            } else {
1016                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1017                            }
1018                            needUpdate = true;
1019                            break;
1020
1021                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1022                            if (verified) {
1023                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1024                                needUpdate = true;
1025                            }
1026                            break;
1027
1028                        default:
1029                            // Nothing to do
1030                    }
1031
1032                    if (needUpdate) {
1033                        mSettings.updateIntentFilterVerificationStatusLPw(
1034                                packageName, updatedStatus, userId);
1035                        scheduleWritePackageRestrictionsLocked(userId);
1036                    }
1037                }
1038            }
1039        }
1040
1041        @Override
1042        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1043                    ActivityIntentInfo filter, String packageName) {
1044            if (!hasValidDomains(filter)) {
1045                return false;
1046            }
1047            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1048            if (ivs == null) {
1049                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1050                        packageName);
1051            }
1052            if (DEBUG_DOMAIN_VERIFICATION) {
1053                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1054            }
1055            ivs.addFilter(filter);
1056            return true;
1057        }
1058
1059        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1060                int userId, int verificationId, String packageName) {
1061            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1062                    verifierUid, userId, packageName);
1063            ivs.setPendingState();
1064            synchronized (mPackages) {
1065                mIntentFilterVerificationStates.append(verificationId, ivs);
1066                mCurrentIntentFilterVerifications.add(verificationId);
1067            }
1068            return ivs;
1069        }
1070    }
1071
1072    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1073        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1074                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1075                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1076    }
1077
1078    // Set of pending broadcasts for aggregating enable/disable of components.
1079    static class PendingPackageBroadcasts {
1080        // for each user id, a map of <package name -> components within that package>
1081        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1082
1083        public PendingPackageBroadcasts() {
1084            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1085        }
1086
1087        public ArrayList<String> get(int userId, String packageName) {
1088            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1089            return packages.get(packageName);
1090        }
1091
1092        public void put(int userId, String packageName, ArrayList<String> components) {
1093            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1094            packages.put(packageName, components);
1095        }
1096
1097        public void remove(int userId, String packageName) {
1098            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1099            if (packages != null) {
1100                packages.remove(packageName);
1101            }
1102        }
1103
1104        public void remove(int userId) {
1105            mUidMap.remove(userId);
1106        }
1107
1108        public int userIdCount() {
1109            return mUidMap.size();
1110        }
1111
1112        public int userIdAt(int n) {
1113            return mUidMap.keyAt(n);
1114        }
1115
1116        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1117            return mUidMap.get(userId);
1118        }
1119
1120        public int size() {
1121            // total number of pending broadcast entries across all userIds
1122            int num = 0;
1123            for (int i = 0; i< mUidMap.size(); i++) {
1124                num += mUidMap.valueAt(i).size();
1125            }
1126            return num;
1127        }
1128
1129        public void clear() {
1130            mUidMap.clear();
1131        }
1132
1133        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1134            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1135            if (map == null) {
1136                map = new ArrayMap<String, ArrayList<String>>();
1137                mUidMap.put(userId, map);
1138            }
1139            return map;
1140        }
1141    }
1142    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1143
1144    // Service Connection to remote media container service to copy
1145    // package uri's from external media onto secure containers
1146    // or internal storage.
1147    private IMediaContainerService mContainerService = null;
1148
1149    static final int SEND_PENDING_BROADCAST = 1;
1150    static final int MCS_BOUND = 3;
1151    static final int END_COPY = 4;
1152    static final int INIT_COPY = 5;
1153    static final int MCS_UNBIND = 6;
1154    static final int START_CLEANING_PACKAGE = 7;
1155    static final int FIND_INSTALL_LOC = 8;
1156    static final int POST_INSTALL = 9;
1157    static final int MCS_RECONNECT = 10;
1158    static final int MCS_GIVE_UP = 11;
1159    static final int UPDATED_MEDIA_STATUS = 12;
1160    static final int WRITE_SETTINGS = 13;
1161    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1162    static final int PACKAGE_VERIFIED = 15;
1163    static final int CHECK_PENDING_VERIFICATION = 16;
1164    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1165    static final int INTENT_FILTER_VERIFIED = 18;
1166    static final int WRITE_PACKAGE_LIST = 19;
1167    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1168
1169    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1170
1171    // Delay time in millisecs
1172    static final int BROADCAST_DELAY = 10 * 1000;
1173
1174    static UserManagerService sUserManager;
1175
1176    // Stores a list of users whose package restrictions file needs to be updated
1177    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1178
1179    final private DefaultContainerConnection mDefContainerConn =
1180            new DefaultContainerConnection();
1181    class DefaultContainerConnection implements ServiceConnection {
1182        public void onServiceConnected(ComponentName name, IBinder service) {
1183            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1184            final IMediaContainerService imcs = IMediaContainerService.Stub
1185                    .asInterface(Binder.allowBlocking(service));
1186            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1187        }
1188
1189        public void onServiceDisconnected(ComponentName name) {
1190            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1191        }
1192    }
1193
1194    // Recordkeeping of restore-after-install operations that are currently in flight
1195    // between the Package Manager and the Backup Manager
1196    static class PostInstallData {
1197        public InstallArgs args;
1198        public PackageInstalledInfo res;
1199
1200        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1201            args = _a;
1202            res = _r;
1203        }
1204    }
1205
1206    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1207    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1208
1209    // XML tags for backup/restore of various bits of state
1210    private static final String TAG_PREFERRED_BACKUP = "pa";
1211    private static final String TAG_DEFAULT_APPS = "da";
1212    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1213
1214    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1215    private static final String TAG_ALL_GRANTS = "rt-grants";
1216    private static final String TAG_GRANT = "grant";
1217    private static final String ATTR_PACKAGE_NAME = "pkg";
1218
1219    private static final String TAG_PERMISSION = "perm";
1220    private static final String ATTR_PERMISSION_NAME = "name";
1221    private static final String ATTR_IS_GRANTED = "g";
1222    private static final String ATTR_USER_SET = "set";
1223    private static final String ATTR_USER_FIXED = "fixed";
1224    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1225
1226    // System/policy permission grants are not backed up
1227    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1228            FLAG_PERMISSION_POLICY_FIXED
1229            | FLAG_PERMISSION_SYSTEM_FIXED
1230            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1231
1232    // And we back up these user-adjusted states
1233    private static final int USER_RUNTIME_GRANT_MASK =
1234            FLAG_PERMISSION_USER_SET
1235            | FLAG_PERMISSION_USER_FIXED
1236            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1237
1238    final @Nullable String mRequiredVerifierPackage;
1239    final @NonNull String mRequiredInstallerPackage;
1240    final @NonNull String mRequiredUninstallerPackage;
1241    final @Nullable String mSetupWizardPackage;
1242    final @Nullable String mStorageManagerPackage;
1243    final @NonNull String mServicesSystemSharedLibraryPackageName;
1244    final @NonNull String mSharedSystemSharedLibraryPackageName;
1245
1246    final boolean mPermissionReviewRequired;
1247
1248    private final PackageUsage mPackageUsage = new PackageUsage();
1249    private final CompilerStats mCompilerStats = new CompilerStats();
1250
1251    class PackageHandler extends Handler {
1252        private boolean mBound = false;
1253        final ArrayList<HandlerParams> mPendingInstalls =
1254            new ArrayList<HandlerParams>();
1255
1256        private boolean connectToService() {
1257            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1258                    " DefaultContainerService");
1259            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1260            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1261            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1262                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1263                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1264                mBound = true;
1265                return true;
1266            }
1267            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1268            return false;
1269        }
1270
1271        private void disconnectService() {
1272            mContainerService = null;
1273            mBound = false;
1274            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1275            mContext.unbindService(mDefContainerConn);
1276            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1277        }
1278
1279        PackageHandler(Looper looper) {
1280            super(looper);
1281        }
1282
1283        public void handleMessage(Message msg) {
1284            try {
1285                doHandleMessage(msg);
1286            } finally {
1287                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1288            }
1289        }
1290
1291        void doHandleMessage(Message msg) {
1292            switch (msg.what) {
1293                case INIT_COPY: {
1294                    HandlerParams params = (HandlerParams) msg.obj;
1295                    int idx = mPendingInstalls.size();
1296                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1297                    // If a bind was already initiated we dont really
1298                    // need to do anything. The pending install
1299                    // will be processed later on.
1300                    if (!mBound) {
1301                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1302                                System.identityHashCode(mHandler));
1303                        // If this is the only one pending we might
1304                        // have to bind to the service again.
1305                        if (!connectToService()) {
1306                            Slog.e(TAG, "Failed to bind to media container service");
1307                            params.serviceError();
1308                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1309                                    System.identityHashCode(mHandler));
1310                            if (params.traceMethod != null) {
1311                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1312                                        params.traceCookie);
1313                            }
1314                            return;
1315                        } else {
1316                            // Once we bind to the service, the first
1317                            // pending request will be processed.
1318                            mPendingInstalls.add(idx, params);
1319                        }
1320                    } else {
1321                        mPendingInstalls.add(idx, params);
1322                        // Already bound to the service. Just make
1323                        // sure we trigger off processing the first request.
1324                        if (idx == 0) {
1325                            mHandler.sendEmptyMessage(MCS_BOUND);
1326                        }
1327                    }
1328                    break;
1329                }
1330                case MCS_BOUND: {
1331                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1332                    if (msg.obj != null) {
1333                        mContainerService = (IMediaContainerService) msg.obj;
1334                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1335                                System.identityHashCode(mHandler));
1336                    }
1337                    if (mContainerService == null) {
1338                        if (!mBound) {
1339                            // Something seriously wrong since we are not bound and we are not
1340                            // waiting for connection. Bail out.
1341                            Slog.e(TAG, "Cannot bind to media container service");
1342                            for (HandlerParams params : mPendingInstalls) {
1343                                // Indicate service bind error
1344                                params.serviceError();
1345                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1346                                        System.identityHashCode(params));
1347                                if (params.traceMethod != null) {
1348                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1349                                            params.traceMethod, params.traceCookie);
1350                                }
1351                                return;
1352                            }
1353                            mPendingInstalls.clear();
1354                        } else {
1355                            Slog.w(TAG, "Waiting to connect to media container service");
1356                        }
1357                    } else if (mPendingInstalls.size() > 0) {
1358                        HandlerParams params = mPendingInstalls.get(0);
1359                        if (params != null) {
1360                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1361                                    System.identityHashCode(params));
1362                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1363                            if (params.startCopy()) {
1364                                // We are done...  look for more work or to
1365                                // go idle.
1366                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1367                                        "Checking for more work or unbind...");
1368                                // Delete pending install
1369                                if (mPendingInstalls.size() > 0) {
1370                                    mPendingInstalls.remove(0);
1371                                }
1372                                if (mPendingInstalls.size() == 0) {
1373                                    if (mBound) {
1374                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1375                                                "Posting delayed MCS_UNBIND");
1376                                        removeMessages(MCS_UNBIND);
1377                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1378                                        // Unbind after a little delay, to avoid
1379                                        // continual thrashing.
1380                                        sendMessageDelayed(ubmsg, 10000);
1381                                    }
1382                                } else {
1383                                    // There are more pending requests in queue.
1384                                    // Just post MCS_BOUND message to trigger processing
1385                                    // of next pending install.
1386                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1387                                            "Posting MCS_BOUND for next work");
1388                                    mHandler.sendEmptyMessage(MCS_BOUND);
1389                                }
1390                            }
1391                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1392                        }
1393                    } else {
1394                        // Should never happen ideally.
1395                        Slog.w(TAG, "Empty queue");
1396                    }
1397                    break;
1398                }
1399                case MCS_RECONNECT: {
1400                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1401                    if (mPendingInstalls.size() > 0) {
1402                        if (mBound) {
1403                            disconnectService();
1404                        }
1405                        if (!connectToService()) {
1406                            Slog.e(TAG, "Failed to bind to media container service");
1407                            for (HandlerParams params : mPendingInstalls) {
1408                                // Indicate service bind error
1409                                params.serviceError();
1410                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1411                                        System.identityHashCode(params));
1412                            }
1413                            mPendingInstalls.clear();
1414                        }
1415                    }
1416                    break;
1417                }
1418                case MCS_UNBIND: {
1419                    // If there is no actual work left, then time to unbind.
1420                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1421
1422                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1423                        if (mBound) {
1424                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1425
1426                            disconnectService();
1427                        }
1428                    } else if (mPendingInstalls.size() > 0) {
1429                        // There are more pending requests in queue.
1430                        // Just post MCS_BOUND message to trigger processing
1431                        // of next pending install.
1432                        mHandler.sendEmptyMessage(MCS_BOUND);
1433                    }
1434
1435                    break;
1436                }
1437                case MCS_GIVE_UP: {
1438                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1439                    HandlerParams params = mPendingInstalls.remove(0);
1440                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1441                            System.identityHashCode(params));
1442                    break;
1443                }
1444                case SEND_PENDING_BROADCAST: {
1445                    String packages[];
1446                    ArrayList<String> components[];
1447                    int size = 0;
1448                    int uids[];
1449                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1450                    synchronized (mPackages) {
1451                        if (mPendingBroadcasts == null) {
1452                            return;
1453                        }
1454                        size = mPendingBroadcasts.size();
1455                        if (size <= 0) {
1456                            // Nothing to be done. Just return
1457                            return;
1458                        }
1459                        packages = new String[size];
1460                        components = new ArrayList[size];
1461                        uids = new int[size];
1462                        int i = 0;  // filling out the above arrays
1463
1464                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1465                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1466                            Iterator<Map.Entry<String, ArrayList<String>>> it
1467                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1468                                            .entrySet().iterator();
1469                            while (it.hasNext() && i < size) {
1470                                Map.Entry<String, ArrayList<String>> ent = it.next();
1471                                packages[i] = ent.getKey();
1472                                components[i] = ent.getValue();
1473                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1474                                uids[i] = (ps != null)
1475                                        ? UserHandle.getUid(packageUserId, ps.appId)
1476                                        : -1;
1477                                i++;
1478                            }
1479                        }
1480                        size = i;
1481                        mPendingBroadcasts.clear();
1482                    }
1483                    // Send broadcasts
1484                    for (int i = 0; i < size; i++) {
1485                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1486                    }
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1488                    break;
1489                }
1490                case START_CLEANING_PACKAGE: {
1491                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1492                    final String packageName = (String)msg.obj;
1493                    final int userId = msg.arg1;
1494                    final boolean andCode = msg.arg2 != 0;
1495                    synchronized (mPackages) {
1496                        if (userId == UserHandle.USER_ALL) {
1497                            int[] users = sUserManager.getUserIds();
1498                            for (int user : users) {
1499                                mSettings.addPackageToCleanLPw(
1500                                        new PackageCleanItem(user, packageName, andCode));
1501                            }
1502                        } else {
1503                            mSettings.addPackageToCleanLPw(
1504                                    new PackageCleanItem(userId, packageName, andCode));
1505                        }
1506                    }
1507                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1508                    startCleaningPackages();
1509                } break;
1510                case POST_INSTALL: {
1511                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1512
1513                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1514                    final boolean didRestore = (msg.arg2 != 0);
1515                    mRunningInstalls.delete(msg.arg1);
1516
1517                    if (data != null) {
1518                        InstallArgs args = data.args;
1519                        PackageInstalledInfo parentRes = data.res;
1520
1521                        final boolean grantPermissions = (args.installFlags
1522                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1523                        final boolean killApp = (args.installFlags
1524                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1525                        final String[] grantedPermissions = args.installGrantPermissions;
1526
1527                        // Handle the parent package
1528                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1529                                grantedPermissions, didRestore, args.installerPackageName,
1530                                args.observer);
1531
1532                        // Handle the child packages
1533                        final int childCount = (parentRes.addedChildPackages != null)
1534                                ? parentRes.addedChildPackages.size() : 0;
1535                        for (int i = 0; i < childCount; i++) {
1536                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1537                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1538                                    grantedPermissions, false, args.installerPackageName,
1539                                    args.observer);
1540                        }
1541
1542                        // Log tracing if needed
1543                        if (args.traceMethod != null) {
1544                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1545                                    args.traceCookie);
1546                        }
1547                    } else {
1548                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1549                    }
1550
1551                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1552                } break;
1553                case UPDATED_MEDIA_STATUS: {
1554                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1555                    boolean reportStatus = msg.arg1 == 1;
1556                    boolean doGc = msg.arg2 == 1;
1557                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1558                    if (doGc) {
1559                        // Force a gc to clear up stale containers.
1560                        Runtime.getRuntime().gc();
1561                    }
1562                    if (msg.obj != null) {
1563                        @SuppressWarnings("unchecked")
1564                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1565                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1566                        // Unload containers
1567                        unloadAllContainers(args);
1568                    }
1569                    if (reportStatus) {
1570                        try {
1571                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1572                                    "Invoking StorageManagerService call back");
1573                            PackageHelper.getStorageManager().finishMediaUpdate();
1574                        } catch (RemoteException e) {
1575                            Log.e(TAG, "StorageManagerService not running?");
1576                        }
1577                    }
1578                } break;
1579                case WRITE_SETTINGS: {
1580                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1581                    synchronized (mPackages) {
1582                        removeMessages(WRITE_SETTINGS);
1583                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1584                        mSettings.writeLPr();
1585                        mDirtyUsers.clear();
1586                    }
1587                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1588                } break;
1589                case WRITE_PACKAGE_RESTRICTIONS: {
1590                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1591                    synchronized (mPackages) {
1592                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1593                        for (int userId : mDirtyUsers) {
1594                            mSettings.writePackageRestrictionsLPr(userId);
1595                        }
1596                        mDirtyUsers.clear();
1597                    }
1598                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1599                } break;
1600                case WRITE_PACKAGE_LIST: {
1601                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1602                    synchronized (mPackages) {
1603                        removeMessages(WRITE_PACKAGE_LIST);
1604                        mSettings.writePackageListLPr(msg.arg1);
1605                    }
1606                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1607                } break;
1608                case CHECK_PENDING_VERIFICATION: {
1609                    final int verificationId = msg.arg1;
1610                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1611
1612                    if ((state != null) && !state.timeoutExtended()) {
1613                        final InstallArgs args = state.getInstallArgs();
1614                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1615
1616                        Slog.i(TAG, "Verification timed out for " + originUri);
1617                        mPendingVerification.remove(verificationId);
1618
1619                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1620
1621                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1622                            Slog.i(TAG, "Continuing with installation of " + originUri);
1623                            state.setVerifierResponse(Binder.getCallingUid(),
1624                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1625                            broadcastPackageVerified(verificationId, originUri,
1626                                    PackageManager.VERIFICATION_ALLOW,
1627                                    state.getInstallArgs().getUser());
1628                            try {
1629                                ret = args.copyApk(mContainerService, true);
1630                            } catch (RemoteException e) {
1631                                Slog.e(TAG, "Could not contact the ContainerService");
1632                            }
1633                        } else {
1634                            broadcastPackageVerified(verificationId, originUri,
1635                                    PackageManager.VERIFICATION_REJECT,
1636                                    state.getInstallArgs().getUser());
1637                        }
1638
1639                        Trace.asyncTraceEnd(
1640                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1641
1642                        processPendingInstall(args, ret);
1643                        mHandler.sendEmptyMessage(MCS_UNBIND);
1644                    }
1645                    break;
1646                }
1647                case PACKAGE_VERIFIED: {
1648                    final int verificationId = msg.arg1;
1649
1650                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1651                    if (state == null) {
1652                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1653                        break;
1654                    }
1655
1656                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1657
1658                    state.setVerifierResponse(response.callerUid, response.code);
1659
1660                    if (state.isVerificationComplete()) {
1661                        mPendingVerification.remove(verificationId);
1662
1663                        final InstallArgs args = state.getInstallArgs();
1664                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1665
1666                        int ret;
1667                        if (state.isInstallAllowed()) {
1668                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1669                            broadcastPackageVerified(verificationId, originUri,
1670                                    response.code, state.getInstallArgs().getUser());
1671                            try {
1672                                ret = args.copyApk(mContainerService, true);
1673                            } catch (RemoteException e) {
1674                                Slog.e(TAG, "Could not contact the ContainerService");
1675                            }
1676                        } else {
1677                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1678                        }
1679
1680                        Trace.asyncTraceEnd(
1681                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1682
1683                        processPendingInstall(args, ret);
1684                        mHandler.sendEmptyMessage(MCS_UNBIND);
1685                    }
1686
1687                    break;
1688                }
1689                case START_INTENT_FILTER_VERIFICATIONS: {
1690                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1691                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1692                            params.replacing, params.pkg);
1693                    break;
1694                }
1695                case INTENT_FILTER_VERIFIED: {
1696                    final int verificationId = msg.arg1;
1697
1698                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1699                            verificationId);
1700                    if (state == null) {
1701                        Slog.w(TAG, "Invalid IntentFilter verification token "
1702                                + verificationId + " received");
1703                        break;
1704                    }
1705
1706                    final int userId = state.getUserId();
1707
1708                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1709                            "Processing IntentFilter verification with token:"
1710                            + verificationId + " and userId:" + userId);
1711
1712                    final IntentFilterVerificationResponse response =
1713                            (IntentFilterVerificationResponse) msg.obj;
1714
1715                    state.setVerifierResponse(response.callerUid, response.code);
1716
1717                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1718                            "IntentFilter verification with token:" + verificationId
1719                            + " and userId:" + userId
1720                            + " is settings verifier response with response code:"
1721                            + response.code);
1722
1723                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1724                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1725                                + response.getFailedDomainsString());
1726                    }
1727
1728                    if (state.isVerificationComplete()) {
1729                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1730                    } else {
1731                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1732                                "IntentFilter verification with token:" + verificationId
1733                                + " was not said to be complete");
1734                    }
1735
1736                    break;
1737                }
1738                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1739                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1740                            mInstantAppResolverConnection,
1741                            (InstantAppRequest) msg.obj,
1742                            mInstantAppInstallerActivity,
1743                            mHandler);
1744                }
1745            }
1746        }
1747    }
1748
1749    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1750            boolean killApp, String[] grantedPermissions,
1751            boolean launchedForRestore, String installerPackage,
1752            IPackageInstallObserver2 installObserver) {
1753        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1754            // Send the removed broadcasts
1755            if (res.removedInfo != null) {
1756                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1757            }
1758
1759            // Now that we successfully installed the package, grant runtime
1760            // permissions if requested before broadcasting the install. Also
1761            // for legacy apps in permission review mode we clear the permission
1762            // review flag which is used to emulate runtime permissions for
1763            // legacy apps.
1764            if (grantPermissions) {
1765                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1766            }
1767
1768            final boolean update = res.removedInfo != null
1769                    && res.removedInfo.removedPackage != null;
1770
1771            // If this is the first time we have child packages for a disabled privileged
1772            // app that had no children, we grant requested runtime permissions to the new
1773            // children if the parent on the system image had them already granted.
1774            if (res.pkg.parentPackage != null) {
1775                synchronized (mPackages) {
1776                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1777                }
1778            }
1779
1780            synchronized (mPackages) {
1781                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1782            }
1783
1784            final String packageName = res.pkg.applicationInfo.packageName;
1785
1786            // Determine the set of users who are adding this package for
1787            // the first time vs. those who are seeing an update.
1788            int[] firstUsers = EMPTY_INT_ARRAY;
1789            int[] updateUsers = EMPTY_INT_ARRAY;
1790            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1791            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1792            for (int newUser : res.newUsers) {
1793                if (ps.getInstantApp(newUser)) {
1794                    continue;
1795                }
1796                if (allNewUsers) {
1797                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1798                    continue;
1799                }
1800                boolean isNew = true;
1801                for (int origUser : res.origUsers) {
1802                    if (origUser == newUser) {
1803                        isNew = false;
1804                        break;
1805                    }
1806                }
1807                if (isNew) {
1808                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1809                } else {
1810                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1811                }
1812            }
1813
1814            // Send installed broadcasts if the package is not a static shared lib.
1815            if (res.pkg.staticSharedLibName == null) {
1816                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1817
1818                // Send added for users that see the package for the first time
1819                // sendPackageAddedForNewUsers also deals with system apps
1820                int appId = UserHandle.getAppId(res.uid);
1821                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1822                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1823
1824                // Send added for users that don't see the package for the first time
1825                Bundle extras = new Bundle(1);
1826                extras.putInt(Intent.EXTRA_UID, res.uid);
1827                if (update) {
1828                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1829                }
1830                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1831                        extras, 0 /*flags*/, null /*targetPackage*/,
1832                        null /*finishedReceiver*/, updateUsers);
1833
1834                // Send replaced for users that don't see the package for the first time
1835                if (update) {
1836                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1837                            packageName, extras, 0 /*flags*/,
1838                            null /*targetPackage*/, null /*finishedReceiver*/,
1839                            updateUsers);
1840                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1841                            null /*package*/, null /*extras*/, 0 /*flags*/,
1842                            packageName /*targetPackage*/,
1843                            null /*finishedReceiver*/, updateUsers);
1844                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1845                    // First-install and we did a restore, so we're responsible for the
1846                    // first-launch broadcast.
1847                    if (DEBUG_BACKUP) {
1848                        Slog.i(TAG, "Post-restore of " + packageName
1849                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1850                    }
1851                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1852                }
1853
1854                // Send broadcast package appeared if forward locked/external for all users
1855                // treat asec-hosted packages like removable media on upgrade
1856                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1857                    if (DEBUG_INSTALL) {
1858                        Slog.i(TAG, "upgrading pkg " + res.pkg
1859                                + " is ASEC-hosted -> AVAILABLE");
1860                    }
1861                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1862                    ArrayList<String> pkgList = new ArrayList<>(1);
1863                    pkgList.add(packageName);
1864                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1865                }
1866            }
1867
1868            // Work that needs to happen on first install within each user
1869            if (firstUsers != null && firstUsers.length > 0) {
1870                synchronized (mPackages) {
1871                    for (int userId : firstUsers) {
1872                        // If this app is a browser and it's newly-installed for some
1873                        // users, clear any default-browser state in those users. The
1874                        // app's nature doesn't depend on the user, so we can just check
1875                        // its browser nature in any user and generalize.
1876                        if (packageIsBrowser(packageName, userId)) {
1877                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1878                        }
1879
1880                        // We may also need to apply pending (restored) runtime
1881                        // permission grants within these users.
1882                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1883                    }
1884                }
1885            }
1886
1887            // Log current value of "unknown sources" setting
1888            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1889                    getUnknownSourcesSettings());
1890
1891            // Force a gc to clear up things
1892            Runtime.getRuntime().gc();
1893
1894            // Remove the replaced package's older resources safely now
1895            // We delete after a gc for applications  on sdcard.
1896            if (res.removedInfo != null && res.removedInfo.args != null) {
1897                synchronized (mInstallLock) {
1898                    res.removedInfo.args.doPostDeleteLI(true);
1899                }
1900            }
1901
1902            // Notify DexManager that the package was installed for new users.
1903            // The updated users should already be indexed and the package code paths
1904            // should not change.
1905            // Don't notify the manager for ephemeral apps as they are not expected to
1906            // survive long enough to benefit of background optimizations.
1907            for (int userId : firstUsers) {
1908                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1909                mDexManager.notifyPackageInstalled(info, userId);
1910            }
1911        }
1912
1913        // If someone is watching installs - notify them
1914        if (installObserver != null) {
1915            try {
1916                Bundle extras = extrasForInstallResult(res);
1917                installObserver.onPackageInstalled(res.name, res.returnCode,
1918                        res.returnMsg, extras);
1919            } catch (RemoteException e) {
1920                Slog.i(TAG, "Observer no longer exists.");
1921            }
1922        }
1923    }
1924
1925    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1926            PackageParser.Package pkg) {
1927        if (pkg.parentPackage == null) {
1928            return;
1929        }
1930        if (pkg.requestedPermissions == null) {
1931            return;
1932        }
1933        final PackageSetting disabledSysParentPs = mSettings
1934                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1935        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1936                || !disabledSysParentPs.isPrivileged()
1937                || (disabledSysParentPs.childPackageNames != null
1938                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1939            return;
1940        }
1941        final int[] allUserIds = sUserManager.getUserIds();
1942        final int permCount = pkg.requestedPermissions.size();
1943        for (int i = 0; i < permCount; i++) {
1944            String permission = pkg.requestedPermissions.get(i);
1945            BasePermission bp = mSettings.mPermissions.get(permission);
1946            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1947                continue;
1948            }
1949            for (int userId : allUserIds) {
1950                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1951                        permission, userId)) {
1952                    grantRuntimePermission(pkg.packageName, permission, userId);
1953                }
1954            }
1955        }
1956    }
1957
1958    private StorageEventListener mStorageListener = new StorageEventListener() {
1959        @Override
1960        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1961            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1962                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1963                    final String volumeUuid = vol.getFsUuid();
1964
1965                    // Clean up any users or apps that were removed or recreated
1966                    // while this volume was missing
1967                    sUserManager.reconcileUsers(volumeUuid);
1968                    reconcileApps(volumeUuid);
1969
1970                    // Clean up any install sessions that expired or were
1971                    // cancelled while this volume was missing
1972                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1973
1974                    loadPrivatePackages(vol);
1975
1976                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1977                    unloadPrivatePackages(vol);
1978                }
1979            }
1980
1981            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1982                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1983                    updateExternalMediaStatus(true, false);
1984                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1985                    updateExternalMediaStatus(false, false);
1986                }
1987            }
1988        }
1989
1990        @Override
1991        public void onVolumeForgotten(String fsUuid) {
1992            if (TextUtils.isEmpty(fsUuid)) {
1993                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1994                return;
1995            }
1996
1997            // Remove any apps installed on the forgotten volume
1998            synchronized (mPackages) {
1999                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2000                for (PackageSetting ps : packages) {
2001                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2002                    deletePackageVersioned(new VersionedPackage(ps.name,
2003                            PackageManager.VERSION_CODE_HIGHEST),
2004                            new LegacyPackageDeleteObserver(null).getBinder(),
2005                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2006                    // Try very hard to release any references to this package
2007                    // so we don't risk the system server being killed due to
2008                    // open FDs
2009                    AttributeCache.instance().removePackage(ps.name);
2010                }
2011
2012                mSettings.onVolumeForgotten(fsUuid);
2013                mSettings.writeLPr();
2014            }
2015        }
2016    };
2017
2018    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2019            String[] grantedPermissions) {
2020        for (int userId : userIds) {
2021            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2022        }
2023    }
2024
2025    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2026            String[] grantedPermissions) {
2027        SettingBase sb = (SettingBase) pkg.mExtras;
2028        if (sb == null) {
2029            return;
2030        }
2031
2032        PermissionsState permissionsState = sb.getPermissionsState();
2033
2034        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2035                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2036
2037        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2038                >= Build.VERSION_CODES.M;
2039
2040        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2041
2042        for (String permission : pkg.requestedPermissions) {
2043            final BasePermission bp;
2044            synchronized (mPackages) {
2045                bp = mSettings.mPermissions.get(permission);
2046            }
2047            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2048                    && (!instantApp || bp.isInstant())
2049                    && (grantedPermissions == null
2050                           || ArrayUtils.contains(grantedPermissions, permission))) {
2051                final int flags = permissionsState.getPermissionFlags(permission, userId);
2052                if (supportsRuntimePermissions) {
2053                    // Installer cannot change immutable permissions.
2054                    if ((flags & immutableFlags) == 0) {
2055                        grantRuntimePermission(pkg.packageName, permission, userId);
2056                    }
2057                } else if (mPermissionReviewRequired) {
2058                    // In permission review mode we clear the review flag when we
2059                    // are asked to install the app with all permissions granted.
2060                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2061                        updatePermissionFlags(permission, pkg.packageName,
2062                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2063                    }
2064                }
2065            }
2066        }
2067    }
2068
2069    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2070        Bundle extras = null;
2071        switch (res.returnCode) {
2072            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2073                extras = new Bundle();
2074                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2075                        res.origPermission);
2076                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2077                        res.origPackage);
2078                break;
2079            }
2080            case PackageManager.INSTALL_SUCCEEDED: {
2081                extras = new Bundle();
2082                extras.putBoolean(Intent.EXTRA_REPLACING,
2083                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2084                break;
2085            }
2086        }
2087        return extras;
2088    }
2089
2090    void scheduleWriteSettingsLocked() {
2091        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2092            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2093        }
2094    }
2095
2096    void scheduleWritePackageListLocked(int userId) {
2097        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2098            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2099            msg.arg1 = userId;
2100            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2101        }
2102    }
2103
2104    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2105        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2106        scheduleWritePackageRestrictionsLocked(userId);
2107    }
2108
2109    void scheduleWritePackageRestrictionsLocked(int userId) {
2110        final int[] userIds = (userId == UserHandle.USER_ALL)
2111                ? sUserManager.getUserIds() : new int[]{userId};
2112        for (int nextUserId : userIds) {
2113            if (!sUserManager.exists(nextUserId)) return;
2114            mDirtyUsers.add(nextUserId);
2115            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2116                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2117            }
2118        }
2119    }
2120
2121    public static PackageManagerService main(Context context, Installer installer,
2122            boolean factoryTest, boolean onlyCore) {
2123        // Self-check for initial settings.
2124        PackageManagerServiceCompilerMapping.checkProperties();
2125
2126        PackageManagerService m = new PackageManagerService(context, installer,
2127                factoryTest, onlyCore);
2128        m.enableSystemUserPackages();
2129        ServiceManager.addService("package", m);
2130        return m;
2131    }
2132
2133    private void enableSystemUserPackages() {
2134        if (!UserManager.isSplitSystemUser()) {
2135            return;
2136        }
2137        // For system user, enable apps based on the following conditions:
2138        // - app is whitelisted or belong to one of these groups:
2139        //   -- system app which has no launcher icons
2140        //   -- system app which has INTERACT_ACROSS_USERS permission
2141        //   -- system IME app
2142        // - app is not in the blacklist
2143        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2144        Set<String> enableApps = new ArraySet<>();
2145        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2146                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2147                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2148        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2149        enableApps.addAll(wlApps);
2150        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2151                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2152        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2153        enableApps.removeAll(blApps);
2154        Log.i(TAG, "Applications installed for system user: " + enableApps);
2155        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2156                UserHandle.SYSTEM);
2157        final int allAppsSize = allAps.size();
2158        synchronized (mPackages) {
2159            for (int i = 0; i < allAppsSize; i++) {
2160                String pName = allAps.get(i);
2161                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2162                // Should not happen, but we shouldn't be failing if it does
2163                if (pkgSetting == null) {
2164                    continue;
2165                }
2166                boolean install = enableApps.contains(pName);
2167                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2168                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2169                            + " for system user");
2170                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2171                }
2172            }
2173            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2174        }
2175    }
2176
2177    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2178        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2179                Context.DISPLAY_SERVICE);
2180        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2181    }
2182
2183    /**
2184     * Requests that files preopted on a secondary system partition be copied to the data partition
2185     * if possible.  Note that the actual copying of the files is accomplished by init for security
2186     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2187     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2188     */
2189    private static void requestCopyPreoptedFiles() {
2190        final int WAIT_TIME_MS = 100;
2191        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2192        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2193            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2194            // We will wait for up to 100 seconds.
2195            final long timeStart = SystemClock.uptimeMillis();
2196            final long timeEnd = timeStart + 100 * 1000;
2197            long timeNow = timeStart;
2198            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2199                try {
2200                    Thread.sleep(WAIT_TIME_MS);
2201                } catch (InterruptedException e) {
2202                    // Do nothing
2203                }
2204                timeNow = SystemClock.uptimeMillis();
2205                if (timeNow > timeEnd) {
2206                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2207                    Slog.wtf(TAG, "cppreopt did not finish!");
2208                    break;
2209                }
2210            }
2211
2212            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2213        }
2214    }
2215
2216    public PackageManagerService(Context context, Installer installer,
2217            boolean factoryTest, boolean onlyCore) {
2218        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2219        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2220        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2221                SystemClock.uptimeMillis());
2222
2223        if (mSdkVersion <= 0) {
2224            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2225        }
2226
2227        mContext = context;
2228
2229        mPermissionReviewRequired = context.getResources().getBoolean(
2230                R.bool.config_permissionReviewRequired);
2231
2232        mFactoryTest = factoryTest;
2233        mOnlyCore = onlyCore;
2234        mMetrics = new DisplayMetrics();
2235        mSettings = new Settings(mPackages);
2236        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2237                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2238        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2239                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2240        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2241                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2242        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2243                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2244        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2245                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2246        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2247                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2248
2249        String separateProcesses = SystemProperties.get("debug.separate_processes");
2250        if (separateProcesses != null && separateProcesses.length() > 0) {
2251            if ("*".equals(separateProcesses)) {
2252                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2253                mSeparateProcesses = null;
2254                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2255            } else {
2256                mDefParseFlags = 0;
2257                mSeparateProcesses = separateProcesses.split(",");
2258                Slog.w(TAG, "Running with debug.separate_processes: "
2259                        + separateProcesses);
2260            }
2261        } else {
2262            mDefParseFlags = 0;
2263            mSeparateProcesses = null;
2264        }
2265
2266        mInstaller = installer;
2267        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2268                "*dexopt*");
2269        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2270        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2271
2272        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2273                FgThread.get().getLooper());
2274
2275        getDefaultDisplayMetrics(context, mMetrics);
2276
2277        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2278        SystemConfig systemConfig = SystemConfig.getInstance();
2279        mGlobalGids = systemConfig.getGlobalGids();
2280        mSystemPermissions = systemConfig.getSystemPermissions();
2281        mAvailableFeatures = systemConfig.getAvailableFeatures();
2282        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2283
2284        mProtectedPackages = new ProtectedPackages(mContext);
2285
2286        synchronized (mInstallLock) {
2287        // writer
2288        synchronized (mPackages) {
2289            mHandlerThread = new ServiceThread(TAG,
2290                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2291            mHandlerThread.start();
2292            mHandler = new PackageHandler(mHandlerThread.getLooper());
2293            mProcessLoggingHandler = new ProcessLoggingHandler();
2294            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2295
2296            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2297            mInstantAppRegistry = new InstantAppRegistry(this);
2298
2299            File dataDir = Environment.getDataDirectory();
2300            mAppInstallDir = new File(dataDir, "app");
2301            mAppLib32InstallDir = new File(dataDir, "app-lib");
2302            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2303            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2304            sUserManager = new UserManagerService(context, this,
2305                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2306
2307            // Propagate permission configuration in to package manager.
2308            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2309                    = systemConfig.getPermissions();
2310            for (int i=0; i<permConfig.size(); i++) {
2311                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2312                BasePermission bp = mSettings.mPermissions.get(perm.name);
2313                if (bp == null) {
2314                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2315                    mSettings.mPermissions.put(perm.name, bp);
2316                }
2317                if (perm.gids != null) {
2318                    bp.setGids(perm.gids, perm.perUser);
2319                }
2320            }
2321
2322            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2323            final int builtInLibCount = libConfig.size();
2324            for (int i = 0; i < builtInLibCount; i++) {
2325                String name = libConfig.keyAt(i);
2326                String path = libConfig.valueAt(i);
2327                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2328                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2329            }
2330
2331            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2332
2333            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2334            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2335            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2336
2337            // Clean up orphaned packages for which the code path doesn't exist
2338            // and they are an update to a system app - caused by bug/32321269
2339            final int packageSettingCount = mSettings.mPackages.size();
2340            for (int i = packageSettingCount - 1; i >= 0; i--) {
2341                PackageSetting ps = mSettings.mPackages.valueAt(i);
2342                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2343                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2344                    mSettings.mPackages.removeAt(i);
2345                    mSettings.enableSystemPackageLPw(ps.name);
2346                }
2347            }
2348
2349            if (mFirstBoot) {
2350                requestCopyPreoptedFiles();
2351            }
2352
2353            String customResolverActivity = Resources.getSystem().getString(
2354                    R.string.config_customResolverActivity);
2355            if (TextUtils.isEmpty(customResolverActivity)) {
2356                customResolverActivity = null;
2357            } else {
2358                mCustomResolverComponentName = ComponentName.unflattenFromString(
2359                        customResolverActivity);
2360            }
2361
2362            long startTime = SystemClock.uptimeMillis();
2363
2364            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2365                    startTime);
2366
2367            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2368            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2369
2370            if (bootClassPath == null) {
2371                Slog.w(TAG, "No BOOTCLASSPATH found!");
2372            }
2373
2374            if (systemServerClassPath == null) {
2375                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2376            }
2377
2378            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2379            final String[] dexCodeInstructionSets =
2380                    getDexCodeInstructionSets(
2381                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2382
2383            /**
2384             * Ensure all external libraries have had dexopt run on them.
2385             */
2386            if (mSharedLibraries.size() > 0) {
2387                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2388                // NOTE: For now, we're compiling these system "shared libraries"
2389                // (and framework jars) into all available architectures. It's possible
2390                // to compile them only when we come across an app that uses them (there's
2391                // already logic for that in scanPackageLI) but that adds some complexity.
2392                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2393                    final int libCount = mSharedLibraries.size();
2394                    for (int i = 0; i < libCount; i++) {
2395                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2396                        final int versionCount = versionedLib.size();
2397                        for (int j = 0; j < versionCount; j++) {
2398                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2399                            final String libPath = libEntry.path != null
2400                                    ? libEntry.path : libEntry.apk;
2401                            if (libPath == null) {
2402                                continue;
2403                            }
2404                            try {
2405                                // Shared libraries do not have profiles so we perform a full
2406                                // AOT compilation (if needed).
2407                                int dexoptNeeded = DexFile.getDexOptNeeded(
2408                                        libPath, dexCodeInstructionSet,
2409                                        getCompilerFilterForReason(REASON_SHARED_APK),
2410                                        false /* newProfile */);
2411                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2412                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2413                                            dexCodeInstructionSet, dexoptNeeded, null,
2414                                            DEXOPT_PUBLIC,
2415                                            getCompilerFilterForReason(REASON_SHARED_APK),
2416                                            StorageManager.UUID_PRIVATE_INTERNAL,
2417                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2418                                }
2419                            } catch (FileNotFoundException e) {
2420                                Slog.w(TAG, "Library not found: " + libPath);
2421                            } catch (IOException | InstallerException e) {
2422                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2423                                        + e.getMessage());
2424                            }
2425                        }
2426                    }
2427                }
2428                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2429            }
2430
2431            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2432
2433            final VersionInfo ver = mSettings.getInternalVersion();
2434            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2435
2436            // when upgrading from pre-M, promote system app permissions from install to runtime
2437            mPromoteSystemApps =
2438                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2439
2440            // When upgrading from pre-N, we need to handle package extraction like first boot,
2441            // as there is no profiling data available.
2442            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2443
2444            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2445
2446            // save off the names of pre-existing system packages prior to scanning; we don't
2447            // want to automatically grant runtime permissions for new system apps
2448            if (mPromoteSystemApps) {
2449                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2450                while (pkgSettingIter.hasNext()) {
2451                    PackageSetting ps = pkgSettingIter.next();
2452                    if (isSystemApp(ps)) {
2453                        mExistingSystemPackages.add(ps.name);
2454                    }
2455                }
2456            }
2457
2458            mCacheDir = preparePackageParserCache(mIsUpgrade);
2459
2460            // Set flag to monitor and not change apk file paths when
2461            // scanning install directories.
2462            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2463
2464            if (mIsUpgrade || mFirstBoot) {
2465                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2466            }
2467
2468            // Collect vendor overlay packages. (Do this before scanning any apps.)
2469            // For security and version matching reason, only consider
2470            // overlay packages if they reside in the right directory.
2471            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2472                    | PackageParser.PARSE_IS_SYSTEM
2473                    | PackageParser.PARSE_IS_SYSTEM_DIR
2474                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2475
2476            // Find base frameworks (resource packages without code).
2477            scanDirTracedLI(frameworkDir, mDefParseFlags
2478                    | PackageParser.PARSE_IS_SYSTEM
2479                    | PackageParser.PARSE_IS_SYSTEM_DIR
2480                    | PackageParser.PARSE_IS_PRIVILEGED,
2481                    scanFlags | SCAN_NO_DEX, 0);
2482
2483            // Collected privileged system packages.
2484            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2485            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2486                    | PackageParser.PARSE_IS_SYSTEM
2487                    | PackageParser.PARSE_IS_SYSTEM_DIR
2488                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2489
2490            // Collect ordinary system packages.
2491            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2492            scanDirTracedLI(systemAppDir, mDefParseFlags
2493                    | PackageParser.PARSE_IS_SYSTEM
2494                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2495
2496            // Collect all vendor packages.
2497            File vendorAppDir = new File("/vendor/app");
2498            try {
2499                vendorAppDir = vendorAppDir.getCanonicalFile();
2500            } catch (IOException e) {
2501                // failed to look up canonical path, continue with original one
2502            }
2503            scanDirTracedLI(vendorAppDir, mDefParseFlags
2504                    | PackageParser.PARSE_IS_SYSTEM
2505                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2506
2507            // Collect all OEM packages.
2508            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2509            scanDirTracedLI(oemAppDir, mDefParseFlags
2510                    | PackageParser.PARSE_IS_SYSTEM
2511                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2512
2513            // Prune any system packages that no longer exist.
2514            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2515            if (!mOnlyCore) {
2516                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2517                while (psit.hasNext()) {
2518                    PackageSetting ps = psit.next();
2519
2520                    /*
2521                     * If this is not a system app, it can't be a
2522                     * disable system app.
2523                     */
2524                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2525                        continue;
2526                    }
2527
2528                    /*
2529                     * If the package is scanned, it's not erased.
2530                     */
2531                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2532                    if (scannedPkg != null) {
2533                        /*
2534                         * If the system app is both scanned and in the
2535                         * disabled packages list, then it must have been
2536                         * added via OTA. Remove it from the currently
2537                         * scanned package so the previously user-installed
2538                         * application can be scanned.
2539                         */
2540                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2541                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2542                                    + ps.name + "; removing system app.  Last known codePath="
2543                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2544                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2545                                    + scannedPkg.mVersionCode);
2546                            removePackageLI(scannedPkg, true);
2547                            mExpectingBetter.put(ps.name, ps.codePath);
2548                        }
2549
2550                        continue;
2551                    }
2552
2553                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2554                        psit.remove();
2555                        logCriticalInfo(Log.WARN, "System package " + ps.name
2556                                + " no longer exists; it's data will be wiped");
2557                        // Actual deletion of code and data will be handled by later
2558                        // reconciliation step
2559                    } else {
2560                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2561                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2562                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2563                        }
2564                    }
2565                }
2566            }
2567
2568            //look for any incomplete package installations
2569            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2570            for (int i = 0; i < deletePkgsList.size(); i++) {
2571                // Actual deletion of code and data will be handled by later
2572                // reconciliation step
2573                final String packageName = deletePkgsList.get(i).name;
2574                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2575                synchronized (mPackages) {
2576                    mSettings.removePackageLPw(packageName);
2577                }
2578            }
2579
2580            //delete tmp files
2581            deleteTempPackageFiles();
2582
2583            // Remove any shared userIDs that have no associated packages
2584            mSettings.pruneSharedUsersLPw();
2585
2586            if (!mOnlyCore) {
2587                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2588                        SystemClock.uptimeMillis());
2589                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2590
2591                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2592                        | PackageParser.PARSE_FORWARD_LOCK,
2593                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2594
2595                /**
2596                 * Remove disable package settings for any updated system
2597                 * apps that were removed via an OTA. If they're not a
2598                 * previously-updated app, remove them completely.
2599                 * Otherwise, just revoke their system-level permissions.
2600                 */
2601                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2602                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2603                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2604
2605                    String msg;
2606                    if (deletedPkg == null) {
2607                        msg = "Updated system package " + deletedAppName
2608                                + " no longer exists; it's data will be wiped";
2609                        // Actual deletion of code and data will be handled by later
2610                        // reconciliation step
2611                    } else {
2612                        msg = "Updated system app + " + deletedAppName
2613                                + " no longer present; removing system privileges for "
2614                                + deletedAppName;
2615
2616                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2617
2618                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2619                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2620                    }
2621                    logCriticalInfo(Log.WARN, msg);
2622                }
2623
2624                /**
2625                 * Make sure all system apps that we expected to appear on
2626                 * the userdata partition actually showed up. If they never
2627                 * appeared, crawl back and revive the system version.
2628                 */
2629                for (int i = 0; i < mExpectingBetter.size(); i++) {
2630                    final String packageName = mExpectingBetter.keyAt(i);
2631                    if (!mPackages.containsKey(packageName)) {
2632                        final File scanFile = mExpectingBetter.valueAt(i);
2633
2634                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2635                                + " but never showed up; reverting to system");
2636
2637                        int reparseFlags = mDefParseFlags;
2638                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2639                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2640                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2641                                    | PackageParser.PARSE_IS_PRIVILEGED;
2642                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2643                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2644                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2645                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2646                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2647                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2648                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2649                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2650                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2651                        } else {
2652                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2653                            continue;
2654                        }
2655
2656                        mSettings.enableSystemPackageLPw(packageName);
2657
2658                        try {
2659                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2660                        } catch (PackageManagerException e) {
2661                            Slog.e(TAG, "Failed to parse original system package: "
2662                                    + e.getMessage());
2663                        }
2664                    }
2665                }
2666            }
2667            mExpectingBetter.clear();
2668
2669            // Resolve the storage manager.
2670            mStorageManagerPackage = getStorageManagerPackageName();
2671
2672            // Resolve protected action filters. Only the setup wizard is allowed to
2673            // have a high priority filter for these actions.
2674            mSetupWizardPackage = getSetupWizardPackageName();
2675            if (mProtectedFilters.size() > 0) {
2676                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2677                    Slog.i(TAG, "No setup wizard;"
2678                        + " All protected intents capped to priority 0");
2679                }
2680                for (ActivityIntentInfo filter : mProtectedFilters) {
2681                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2682                        if (DEBUG_FILTERS) {
2683                            Slog.i(TAG, "Found setup wizard;"
2684                                + " allow priority " + filter.getPriority() + ";"
2685                                + " package: " + filter.activity.info.packageName
2686                                + " activity: " + filter.activity.className
2687                                + " priority: " + filter.getPriority());
2688                        }
2689                        // skip setup wizard; allow it to keep the high priority filter
2690                        continue;
2691                    }
2692                    Slog.w(TAG, "Protected action; cap priority to 0;"
2693                            + " package: " + filter.activity.info.packageName
2694                            + " activity: " + filter.activity.className
2695                            + " origPrio: " + filter.getPriority());
2696                    filter.setPriority(0);
2697                }
2698            }
2699            mDeferProtectedFilters = false;
2700            mProtectedFilters.clear();
2701
2702            // Now that we know all of the shared libraries, update all clients to have
2703            // the correct library paths.
2704            updateAllSharedLibrariesLPw(null);
2705
2706            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2707                // NOTE: We ignore potential failures here during a system scan (like
2708                // the rest of the commands above) because there's precious little we
2709                // can do about it. A settings error is reported, though.
2710                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2711            }
2712
2713            // Now that we know all the packages we are keeping,
2714            // read and update their last usage times.
2715            mPackageUsage.read(mPackages);
2716            mCompilerStats.read();
2717
2718            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2719                    SystemClock.uptimeMillis());
2720            Slog.i(TAG, "Time to scan packages: "
2721                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2722                    + " seconds");
2723
2724            // If the platform SDK has changed since the last time we booted,
2725            // we need to re-grant app permission to catch any new ones that
2726            // appear.  This is really a hack, and means that apps can in some
2727            // cases get permissions that the user didn't initially explicitly
2728            // allow...  it would be nice to have some better way to handle
2729            // this situation.
2730            int updateFlags = UPDATE_PERMISSIONS_ALL;
2731            if (ver.sdkVersion != mSdkVersion) {
2732                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2733                        + mSdkVersion + "; regranting permissions for internal storage");
2734                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2735            }
2736            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2737            ver.sdkVersion = mSdkVersion;
2738
2739            // If this is the first boot or an update from pre-M, and it is a normal
2740            // boot, then we need to initialize the default preferred apps across
2741            // all defined users.
2742            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2743                for (UserInfo user : sUserManager.getUsers(true)) {
2744                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2745                    applyFactoryDefaultBrowserLPw(user.id);
2746                    primeDomainVerificationsLPw(user.id);
2747                }
2748            }
2749
2750            // Prepare storage for system user really early during boot,
2751            // since core system apps like SettingsProvider and SystemUI
2752            // can't wait for user to start
2753            final int storageFlags;
2754            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2755                storageFlags = StorageManager.FLAG_STORAGE_DE;
2756            } else {
2757                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2758            }
2759            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2760                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2761                    true /* onlyCoreApps */);
2762            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2763                if (deferPackages == null || deferPackages.isEmpty()) {
2764                    return;
2765                }
2766                int count = 0;
2767                for (String pkgName : deferPackages) {
2768                    PackageParser.Package pkg = null;
2769                    synchronized (mPackages) {
2770                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2771                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2772                            pkg = ps.pkg;
2773                        }
2774                    }
2775                    if (pkg != null) {
2776                        synchronized (mInstallLock) {
2777                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2778                                    true /* maybeMigrateAppData */);
2779                        }
2780                        count++;
2781                    }
2782                }
2783                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2784            }, "prepareAppData");
2785
2786            // If this is first boot after an OTA, and a normal boot, then
2787            // we need to clear code cache directories.
2788            // Note that we do *not* clear the application profiles. These remain valid
2789            // across OTAs and are used to drive profile verification (post OTA) and
2790            // profile compilation (without waiting to collect a fresh set of profiles).
2791            if (mIsUpgrade && !onlyCore) {
2792                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2793                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2794                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2795                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2796                        // No apps are running this early, so no need to freeze
2797                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2798                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2799                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2800                    }
2801                }
2802                ver.fingerprint = Build.FINGERPRINT;
2803            }
2804
2805            checkDefaultBrowser();
2806
2807            // clear only after permissions and other defaults have been updated
2808            mExistingSystemPackages.clear();
2809            mPromoteSystemApps = false;
2810
2811            // All the changes are done during package scanning.
2812            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2813
2814            // can downgrade to reader
2815            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2816            mSettings.writeLPr();
2817            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2818
2819            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2820                    SystemClock.uptimeMillis());
2821
2822            if (!mOnlyCore) {
2823                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2824                mRequiredInstallerPackage = getRequiredInstallerLPr();
2825                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2826                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2827                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2828                        mIntentFilterVerifierComponent);
2829                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2830                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2831                        SharedLibraryInfo.VERSION_UNDEFINED);
2832                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2833                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2834                        SharedLibraryInfo.VERSION_UNDEFINED);
2835            } else {
2836                mRequiredVerifierPackage = null;
2837                mRequiredInstallerPackage = null;
2838                mRequiredUninstallerPackage = null;
2839                mIntentFilterVerifierComponent = null;
2840                mIntentFilterVerifier = null;
2841                mServicesSystemSharedLibraryPackageName = null;
2842                mSharedSystemSharedLibraryPackageName = null;
2843            }
2844
2845            mInstallerService = new PackageInstallerService(context, this);
2846
2847            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2848            if (ephemeralResolverComponent != null) {
2849                if (DEBUG_EPHEMERAL) {
2850                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2851                }
2852                mInstantAppResolverConnection =
2853                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2854            } else {
2855                mInstantAppResolverConnection = null;
2856            }
2857            mInstantAppInstallerComponent = getEphemeralInstallerLPr();
2858            if (mInstantAppInstallerComponent != null) {
2859                if (DEBUG_EPHEMERAL) {
2860                    Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent);
2861                }
2862                setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent);
2863            }
2864
2865            // Read and update the usage of dex files.
2866            // Do this at the end of PM init so that all the packages have their
2867            // data directory reconciled.
2868            // At this point we know the code paths of the packages, so we can validate
2869            // the disk file and build the internal cache.
2870            // The usage file is expected to be small so loading and verifying it
2871            // should take a fairly small time compare to the other activities (e.g. package
2872            // scanning).
2873            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2874            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2875            for (int userId : currentUserIds) {
2876                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2877            }
2878            mDexManager.load(userPackages);
2879        } // synchronized (mPackages)
2880        } // synchronized (mInstallLock)
2881
2882        // Now after opening every single application zip, make sure they
2883        // are all flushed.  Not really needed, but keeps things nice and
2884        // tidy.
2885        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2886        Runtime.getRuntime().gc();
2887        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2888
2889        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2890        FallbackCategoryProvider.loadFallbacks();
2891        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2892
2893        // The initial scanning above does many calls into installd while
2894        // holding the mPackages lock, but we're mostly interested in yelling
2895        // once we have a booted system.
2896        mInstaller.setWarnIfHeld(mPackages);
2897
2898        // Expose private service for system components to use.
2899        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2900        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2901    }
2902
2903    private static File preparePackageParserCache(boolean isUpgrade) {
2904        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2905            return null;
2906        }
2907
2908        // Disable package parsing on eng builds to allow for faster incremental development.
2909        if ("eng".equals(Build.TYPE)) {
2910            return null;
2911        }
2912
2913        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2914            Slog.i(TAG, "Disabling package parser cache due to system property.");
2915            return null;
2916        }
2917
2918        // The base directory for the package parser cache lives under /data/system/.
2919        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2920                "package_cache");
2921        if (cacheBaseDir == null) {
2922            return null;
2923        }
2924
2925        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2926        // This also serves to "GC" unused entries when the package cache version changes (which
2927        // can only happen during upgrades).
2928        if (isUpgrade) {
2929            FileUtils.deleteContents(cacheBaseDir);
2930        }
2931
2932
2933        // Return the versioned package cache directory. This is something like
2934        // "/data/system/package_cache/1"
2935        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2936
2937        // The following is a workaround to aid development on non-numbered userdebug
2938        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2939        // the system partition is newer.
2940        //
2941        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2942        // that starts with "eng." to signify that this is an engineering build and not
2943        // destined for release.
2944        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2945            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2946
2947            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2948            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2949            // in general and should not be used for production changes. In this specific case,
2950            // we know that they will work.
2951            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2952            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2953                FileUtils.deleteContents(cacheBaseDir);
2954                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2955            }
2956        }
2957
2958        return cacheDir;
2959    }
2960
2961    @Override
2962    public boolean isFirstBoot() {
2963        return mFirstBoot;
2964    }
2965
2966    @Override
2967    public boolean isOnlyCoreApps() {
2968        return mOnlyCore;
2969    }
2970
2971    @Override
2972    public boolean isUpgrade() {
2973        return mIsUpgrade;
2974    }
2975
2976    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2977        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2978
2979        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2980                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2981                UserHandle.USER_SYSTEM);
2982        if (matches.size() == 1) {
2983            return matches.get(0).getComponentInfo().packageName;
2984        } else if (matches.size() == 0) {
2985            Log.e(TAG, "There should probably be a verifier, but, none were found");
2986            return null;
2987        }
2988        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2989    }
2990
2991    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2992        synchronized (mPackages) {
2993            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2994            if (libraryEntry == null) {
2995                throw new IllegalStateException("Missing required shared library:" + name);
2996            }
2997            return libraryEntry.apk;
2998        }
2999    }
3000
3001    private @NonNull String getRequiredInstallerLPr() {
3002        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3003        intent.addCategory(Intent.CATEGORY_DEFAULT);
3004        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3005
3006        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3007                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3008                UserHandle.USER_SYSTEM);
3009        if (matches.size() == 1) {
3010            ResolveInfo resolveInfo = matches.get(0);
3011            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3012                throw new RuntimeException("The installer must be a privileged app");
3013            }
3014            return matches.get(0).getComponentInfo().packageName;
3015        } else {
3016            throw new RuntimeException("There must be exactly one installer; found " + matches);
3017        }
3018    }
3019
3020    private @NonNull String getRequiredUninstallerLPr() {
3021        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3022        intent.addCategory(Intent.CATEGORY_DEFAULT);
3023        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3024
3025        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3026                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3027                UserHandle.USER_SYSTEM);
3028        if (resolveInfo == null ||
3029                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3030            throw new RuntimeException("There must be exactly one uninstaller; found "
3031                    + resolveInfo);
3032        }
3033        return resolveInfo.getComponentInfo().packageName;
3034    }
3035
3036    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3037        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3038
3039        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3040                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3041                UserHandle.USER_SYSTEM);
3042        ResolveInfo best = null;
3043        final int N = matches.size();
3044        for (int i = 0; i < N; i++) {
3045            final ResolveInfo cur = matches.get(i);
3046            final String packageName = cur.getComponentInfo().packageName;
3047            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3048                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3049                continue;
3050            }
3051
3052            if (best == null || cur.priority > best.priority) {
3053                best = cur;
3054            }
3055        }
3056
3057        if (best != null) {
3058            return best.getComponentInfo().getComponentName();
3059        } else {
3060            throw new RuntimeException("There must be at least one intent filter verifier");
3061        }
3062    }
3063
3064    private @Nullable ComponentName getEphemeralResolverLPr() {
3065        final String[] packageArray =
3066                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3067        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3068            if (DEBUG_EPHEMERAL) {
3069                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3070            }
3071            return null;
3072        }
3073
3074        final int resolveFlags =
3075                MATCH_DIRECT_BOOT_AWARE
3076                | MATCH_DIRECT_BOOT_UNAWARE
3077                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3078        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3079        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3080                resolveFlags, UserHandle.USER_SYSTEM);
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 ComponentName(packageName, info.serviceInfo.name);
3112        }
3113        if (DEBUG_EPHEMERAL) {
3114            Slog.v(TAG, "Ephemeral resolver NOT found");
3115        }
3116        return null;
3117    }
3118
3119    private @Nullable ComponentName getEphemeralInstallerLPr() {
3120        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_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        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3129                resolveFlags, UserHandle.USER_SYSTEM);
3130        Iterator<ResolveInfo> iter = matches.iterator();
3131        while (iter.hasNext()) {
3132            final ResolveInfo rInfo = iter.next();
3133            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3134            if (ps != null) {
3135                final PermissionsState permissionsState = ps.getPermissionsState();
3136                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3137                    continue;
3138                }
3139            }
3140            iter.remove();
3141        }
3142        if (matches.size() == 0) {
3143            return null;
3144        } else if (matches.size() == 1) {
3145            return matches.get(0).getComponentInfo().getComponentName();
3146        } else {
3147            throw new RuntimeException(
3148                    "There must be at most one ephemeral installer; found " + matches);
3149        }
3150    }
3151
3152    private void primeDomainVerificationsLPw(int userId) {
3153        if (DEBUG_DOMAIN_VERIFICATION) {
3154            Slog.d(TAG, "Priming domain verifications in user " + userId);
3155        }
3156
3157        SystemConfig systemConfig = SystemConfig.getInstance();
3158        ArraySet<String> packages = systemConfig.getLinkedApps();
3159
3160        for (String packageName : packages) {
3161            PackageParser.Package pkg = mPackages.get(packageName);
3162            if (pkg != null) {
3163                if (!pkg.isSystemApp()) {
3164                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3165                    continue;
3166                }
3167
3168                ArraySet<String> domains = null;
3169                for (PackageParser.Activity a : pkg.activities) {
3170                    for (ActivityIntentInfo filter : a.intents) {
3171                        if (hasValidDomains(filter)) {
3172                            if (domains == null) {
3173                                domains = new ArraySet<String>();
3174                            }
3175                            domains.addAll(filter.getHostsList());
3176                        }
3177                    }
3178                }
3179
3180                if (domains != null && domains.size() > 0) {
3181                    if (DEBUG_DOMAIN_VERIFICATION) {
3182                        Slog.v(TAG, "      + " + packageName);
3183                    }
3184                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3185                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3186                    // and then 'always' in the per-user state actually used for intent resolution.
3187                    final IntentFilterVerificationInfo ivi;
3188                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3189                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3190                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3191                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3192                } else {
3193                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3194                            + "' does not handle web links");
3195                }
3196            } else {
3197                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3198            }
3199        }
3200
3201        scheduleWritePackageRestrictionsLocked(userId);
3202        scheduleWriteSettingsLocked();
3203    }
3204
3205    private void applyFactoryDefaultBrowserLPw(int userId) {
3206        // The default browser app's package name is stored in a string resource,
3207        // with a product-specific overlay used for vendor customization.
3208        String browserPkg = mContext.getResources().getString(
3209                com.android.internal.R.string.default_browser);
3210        if (!TextUtils.isEmpty(browserPkg)) {
3211            // non-empty string => required to be a known package
3212            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3213            if (ps == null) {
3214                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3215                browserPkg = null;
3216            } else {
3217                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3218            }
3219        }
3220
3221        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3222        // default.  If there's more than one, just leave everything alone.
3223        if (browserPkg == null) {
3224            calculateDefaultBrowserLPw(userId);
3225        }
3226    }
3227
3228    private void calculateDefaultBrowserLPw(int userId) {
3229        List<String> allBrowsers = resolveAllBrowserApps(userId);
3230        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3231        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3232    }
3233
3234    private List<String> resolveAllBrowserApps(int userId) {
3235        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3236        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3237                PackageManager.MATCH_ALL, userId);
3238
3239        final int count = list.size();
3240        List<String> result = new ArrayList<String>(count);
3241        for (int i=0; i<count; i++) {
3242            ResolveInfo info = list.get(i);
3243            if (info.activityInfo == null
3244                    || !info.handleAllWebDataURI
3245                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3246                    || result.contains(info.activityInfo.packageName)) {
3247                continue;
3248            }
3249            result.add(info.activityInfo.packageName);
3250        }
3251
3252        return result;
3253    }
3254
3255    private boolean packageIsBrowser(String packageName, int userId) {
3256        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3257                PackageManager.MATCH_ALL, userId);
3258        final int N = list.size();
3259        for (int i = 0; i < N; i++) {
3260            ResolveInfo info = list.get(i);
3261            if (packageName.equals(info.activityInfo.packageName)) {
3262                return true;
3263            }
3264        }
3265        return false;
3266    }
3267
3268    private void checkDefaultBrowser() {
3269        final int myUserId = UserHandle.myUserId();
3270        final String packageName = getDefaultBrowserPackageName(myUserId);
3271        if (packageName != null) {
3272            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3273            if (info == null) {
3274                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3275                synchronized (mPackages) {
3276                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3277                }
3278            }
3279        }
3280    }
3281
3282    @Override
3283    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3284            throws RemoteException {
3285        try {
3286            return super.onTransact(code, data, reply, flags);
3287        } catch (RuntimeException e) {
3288            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3289                Slog.wtf(TAG, "Package Manager Crash", e);
3290            }
3291            throw e;
3292        }
3293    }
3294
3295    static int[] appendInts(int[] cur, int[] add) {
3296        if (add == null) return cur;
3297        if (cur == null) return add;
3298        final int N = add.length;
3299        for (int i=0; i<N; i++) {
3300            cur = appendInt(cur, add[i]);
3301        }
3302        return cur;
3303    }
3304
3305    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3306        if (!sUserManager.exists(userId)) return null;
3307        if (ps == null) {
3308            return null;
3309        }
3310        final PackageParser.Package p = ps.pkg;
3311        if (p == null) {
3312            return null;
3313        }
3314        // Filter out ephemeral app metadata:
3315        //   * The system/shell/root can see metadata for any app
3316        //   * An installed app can see metadata for 1) other installed apps
3317        //     and 2) ephemeral apps that have explicitly interacted with it
3318        //   * Ephemeral apps can only see their own data and exposed installed apps
3319        //   * Holding a signature permission allows seeing instant apps
3320        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3321        if (callingAppId != Process.SYSTEM_UID
3322                && callingAppId != Process.SHELL_UID
3323                && callingAppId != Process.ROOT_UID
3324                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3325                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3326            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3327            if (instantAppPackageName != null) {
3328                // ephemeral apps can only get information on themselves or
3329                // installed apps that are exposed.
3330                if (!instantAppPackageName.equals(p.packageName)
3331                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3332                    return null;
3333                }
3334            } else {
3335                if (ps.getInstantApp(userId)) {
3336                    // only get access to the ephemeral app if we've been granted access
3337                    if (!mInstantAppRegistry.isInstantAccessGranted(
3338                            userId, callingAppId, ps.appId)) {
3339                        return null;
3340                    }
3341                }
3342            }
3343        }
3344
3345        final PermissionsState permissionsState = ps.getPermissionsState();
3346
3347        // Compute GIDs only if requested
3348        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3349                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3350        // Compute granted permissions only if package has requested permissions
3351        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3352                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3353        final PackageUserState state = ps.readUserState(userId);
3354
3355        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3356                && ps.isSystem()) {
3357            flags |= MATCH_ANY_USER;
3358        }
3359
3360        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3361                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3362
3363        if (packageInfo == null) {
3364            return null;
3365        }
3366
3367        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3368
3369        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3370                resolveExternalPackageNameLPr(p);
3371
3372        return packageInfo;
3373    }
3374
3375    @Override
3376    public void checkPackageStartable(String packageName, int userId) {
3377        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3378
3379        synchronized (mPackages) {
3380            final PackageSetting ps = mSettings.mPackages.get(packageName);
3381            if (ps == null) {
3382                throw new SecurityException("Package " + packageName + " was not found!");
3383            }
3384
3385            if (!ps.getInstalled(userId)) {
3386                throw new SecurityException(
3387                        "Package " + packageName + " was not installed for user " + userId + "!");
3388            }
3389
3390            if (mSafeMode && !ps.isSystem()) {
3391                throw new SecurityException("Package " + packageName + " not a system app!");
3392            }
3393
3394            if (mFrozenPackages.contains(packageName)) {
3395                throw new SecurityException("Package " + packageName + " is currently frozen!");
3396            }
3397
3398            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3399                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3400                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3401            }
3402        }
3403    }
3404
3405    @Override
3406    public boolean isPackageAvailable(String packageName, int userId) {
3407        if (!sUserManager.exists(userId)) return false;
3408        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3409                false /* requireFullPermission */, false /* checkShell */, "is package available");
3410        synchronized (mPackages) {
3411            PackageParser.Package p = mPackages.get(packageName);
3412            if (p != null) {
3413                final PackageSetting ps = (PackageSetting) p.mExtras;
3414                if (ps != null) {
3415                    final PackageUserState state = ps.readUserState(userId);
3416                    if (state != null) {
3417                        return PackageParser.isAvailable(state);
3418                    }
3419                }
3420            }
3421        }
3422        return false;
3423    }
3424
3425    @Override
3426    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3427        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3428                flags, userId);
3429    }
3430
3431    @Override
3432    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3433            int flags, int userId) {
3434        return getPackageInfoInternal(versionedPackage.getPackageName(),
3435                // TODO: We will change version code to long, so in the new API it is long
3436                (int) versionedPackage.getVersionCode(), flags, userId);
3437    }
3438
3439    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3440            int flags, int userId) {
3441        if (!sUserManager.exists(userId)) return null;
3442        flags = updateFlagsForPackage(flags, userId, packageName);
3443        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3444                false /* requireFullPermission */, false /* checkShell */, "get package info");
3445
3446        // reader
3447        synchronized (mPackages) {
3448            // Normalize package name to handle renamed packages and static libs
3449            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3450
3451            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3452            if (matchFactoryOnly) {
3453                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3454                if (ps != null) {
3455                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3456                        return null;
3457                    }
3458                    return generatePackageInfo(ps, flags, userId);
3459                }
3460            }
3461
3462            PackageParser.Package p = mPackages.get(packageName);
3463            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3464                return null;
3465            }
3466            if (DEBUG_PACKAGE_INFO)
3467                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3468            if (p != null) {
3469                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3470                        Binder.getCallingUid(), userId)) {
3471                    return null;
3472                }
3473                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3474            }
3475            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3476                final PackageSetting ps = mSettings.mPackages.get(packageName);
3477                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3478                    return null;
3479                }
3480                return generatePackageInfo(ps, flags, userId);
3481            }
3482        }
3483        return null;
3484    }
3485
3486
3487    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3488        // System/shell/root get to see all static libs
3489        final int appId = UserHandle.getAppId(uid);
3490        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3491                || appId == Process.ROOT_UID) {
3492            return false;
3493        }
3494
3495        // No package means no static lib as it is always on internal storage
3496        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3497            return false;
3498        }
3499
3500        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3501                ps.pkg.staticSharedLibVersion);
3502        if (libEntry == null) {
3503            return false;
3504        }
3505
3506        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3507        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3508        if (uidPackageNames == null) {
3509            return true;
3510        }
3511
3512        for (String uidPackageName : uidPackageNames) {
3513            if (ps.name.equals(uidPackageName)) {
3514                return false;
3515            }
3516            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3517            if (uidPs != null) {
3518                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3519                        libEntry.info.getName());
3520                if (index < 0) {
3521                    continue;
3522                }
3523                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3524                    return false;
3525                }
3526            }
3527        }
3528        return true;
3529    }
3530
3531    @Override
3532    public String[] currentToCanonicalPackageNames(String[] names) {
3533        String[] out = new String[names.length];
3534        // reader
3535        synchronized (mPackages) {
3536            for (int i=names.length-1; i>=0; i--) {
3537                PackageSetting ps = mSettings.mPackages.get(names[i]);
3538                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3539            }
3540        }
3541        return out;
3542    }
3543
3544    @Override
3545    public String[] canonicalToCurrentPackageNames(String[] names) {
3546        String[] out = new String[names.length];
3547        // reader
3548        synchronized (mPackages) {
3549            for (int i=names.length-1; i>=0; i--) {
3550                String cur = mSettings.getRenamedPackageLPr(names[i]);
3551                out[i] = cur != null ? cur : names[i];
3552            }
3553        }
3554        return out;
3555    }
3556
3557    @Override
3558    public int getPackageUid(String packageName, int flags, int userId) {
3559        if (!sUserManager.exists(userId)) return -1;
3560        flags = updateFlagsForPackage(flags, userId, packageName);
3561        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3562                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3563
3564        // reader
3565        synchronized (mPackages) {
3566            final PackageParser.Package p = mPackages.get(packageName);
3567            if (p != null && p.isMatch(flags)) {
3568                return UserHandle.getUid(userId, p.applicationInfo.uid);
3569            }
3570            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3571                final PackageSetting ps = mSettings.mPackages.get(packageName);
3572                if (ps != null && ps.isMatch(flags)) {
3573                    return UserHandle.getUid(userId, ps.appId);
3574                }
3575            }
3576        }
3577
3578        return -1;
3579    }
3580
3581    @Override
3582    public int[] getPackageGids(String packageName, int flags, int userId) {
3583        if (!sUserManager.exists(userId)) return null;
3584        flags = updateFlagsForPackage(flags, userId, packageName);
3585        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3586                false /* requireFullPermission */, false /* checkShell */,
3587                "getPackageGids");
3588
3589        // reader
3590        synchronized (mPackages) {
3591            final PackageParser.Package p = mPackages.get(packageName);
3592            if (p != null && p.isMatch(flags)) {
3593                PackageSetting ps = (PackageSetting) p.mExtras;
3594                // TODO: Shouldn't this be checking for package installed state for userId and
3595                // return null?
3596                return ps.getPermissionsState().computeGids(userId);
3597            }
3598            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3599                final PackageSetting ps = mSettings.mPackages.get(packageName);
3600                if (ps != null && ps.isMatch(flags)) {
3601                    return ps.getPermissionsState().computeGids(userId);
3602                }
3603            }
3604        }
3605
3606        return null;
3607    }
3608
3609    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3610        if (bp.perm != null) {
3611            return PackageParser.generatePermissionInfo(bp.perm, flags);
3612        }
3613        PermissionInfo pi = new PermissionInfo();
3614        pi.name = bp.name;
3615        pi.packageName = bp.sourcePackage;
3616        pi.nonLocalizedLabel = bp.name;
3617        pi.protectionLevel = bp.protectionLevel;
3618        return pi;
3619    }
3620
3621    @Override
3622    public PermissionInfo getPermissionInfo(String name, int flags) {
3623        // reader
3624        synchronized (mPackages) {
3625            final BasePermission p = mSettings.mPermissions.get(name);
3626            if (p != null) {
3627                return generatePermissionInfo(p, flags);
3628            }
3629            return null;
3630        }
3631    }
3632
3633    @Override
3634    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3635            int flags) {
3636        // reader
3637        synchronized (mPackages) {
3638            if (group != null && !mPermissionGroups.containsKey(group)) {
3639                // This is thrown as NameNotFoundException
3640                return null;
3641            }
3642
3643            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3644            for (BasePermission p : mSettings.mPermissions.values()) {
3645                if (group == null) {
3646                    if (p.perm == null || p.perm.info.group == null) {
3647                        out.add(generatePermissionInfo(p, flags));
3648                    }
3649                } else {
3650                    if (p.perm != null && group.equals(p.perm.info.group)) {
3651                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3652                    }
3653                }
3654            }
3655            return new ParceledListSlice<>(out);
3656        }
3657    }
3658
3659    @Override
3660    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3661        // reader
3662        synchronized (mPackages) {
3663            return PackageParser.generatePermissionGroupInfo(
3664                    mPermissionGroups.get(name), flags);
3665        }
3666    }
3667
3668    @Override
3669    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3670        // reader
3671        synchronized (mPackages) {
3672            final int N = mPermissionGroups.size();
3673            ArrayList<PermissionGroupInfo> out
3674                    = new ArrayList<PermissionGroupInfo>(N);
3675            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3676                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3677            }
3678            return new ParceledListSlice<>(out);
3679        }
3680    }
3681
3682    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3683            int uid, int userId) {
3684        if (!sUserManager.exists(userId)) return null;
3685        PackageSetting ps = mSettings.mPackages.get(packageName);
3686        if (ps != null) {
3687            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3688                return null;
3689            }
3690            if (ps.pkg == null) {
3691                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3692                if (pInfo != null) {
3693                    return pInfo.applicationInfo;
3694                }
3695                return null;
3696            }
3697            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3698                    ps.readUserState(userId), userId);
3699            if (ai != null) {
3700                rebaseEnabledOverlays(ai, userId);
3701                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3702            }
3703            return ai;
3704        }
3705        return null;
3706    }
3707
3708    @Override
3709    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3710        if (!sUserManager.exists(userId)) return null;
3711        flags = updateFlagsForApplication(flags, userId, packageName);
3712        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3713                false /* requireFullPermission */, false /* checkShell */, "get application info");
3714
3715        // writer
3716        synchronized (mPackages) {
3717            // Normalize package name to handle renamed packages and static libs
3718            packageName = resolveInternalPackageNameLPr(packageName,
3719                    PackageManager.VERSION_CODE_HIGHEST);
3720
3721            PackageParser.Package p = mPackages.get(packageName);
3722            if (DEBUG_PACKAGE_INFO) Log.v(
3723                    TAG, "getApplicationInfo " + packageName
3724                    + ": " + p);
3725            if (p != null) {
3726                PackageSetting ps = mSettings.mPackages.get(packageName);
3727                if (ps == null) return null;
3728                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3729                    return null;
3730                }
3731                // Note: isEnabledLP() does not apply here - always return info
3732                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3733                        p, flags, ps.readUserState(userId), userId);
3734                if (ai != null) {
3735                    rebaseEnabledOverlays(ai, userId);
3736                    ai.packageName = resolveExternalPackageNameLPr(p);
3737                }
3738                return ai;
3739            }
3740            if ("android".equals(packageName)||"system".equals(packageName)) {
3741                return mAndroidApplication;
3742            }
3743            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3744                // Already generates the external package name
3745                return generateApplicationInfoFromSettingsLPw(packageName,
3746                        Binder.getCallingUid(), flags, userId);
3747            }
3748        }
3749        return null;
3750    }
3751
3752    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3753        List<String> paths = new ArrayList<>();
3754        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3755            mEnabledOverlayPaths.get(userId);
3756        if (userSpecificOverlays != null) {
3757            if (!"android".equals(ai.packageName)) {
3758                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3759                if (frameworkOverlays != null) {
3760                    paths.addAll(frameworkOverlays);
3761                }
3762            }
3763
3764            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3765            if (appOverlays != null) {
3766                paths.addAll(appOverlays);
3767            }
3768        }
3769        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3770    }
3771
3772    private String normalizePackageNameLPr(String packageName) {
3773        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3774        return normalizedPackageName != null ? normalizedPackageName : packageName;
3775    }
3776
3777    @Override
3778    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3779            final IPackageDataObserver observer) {
3780        mContext.enforceCallingOrSelfPermission(
3781                android.Manifest.permission.CLEAR_APP_CACHE, null);
3782        mHandler.post(() -> {
3783            boolean success = false;
3784            try {
3785                freeStorage(volumeUuid, freeStorageSize, 0);
3786                success = true;
3787            } catch (IOException e) {
3788                Slog.w(TAG, e);
3789            }
3790            if (observer != null) {
3791                try {
3792                    observer.onRemoveCompleted(null, success);
3793                } catch (RemoteException e) {
3794                    Slog.w(TAG, e);
3795                }
3796            }
3797        });
3798    }
3799
3800    @Override
3801    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3802            final IntentSender pi) {
3803        mContext.enforceCallingOrSelfPermission(
3804                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3805        mHandler.post(() -> {
3806            boolean success = false;
3807            try {
3808                freeStorage(volumeUuid, freeStorageSize, 0);
3809                success = true;
3810            } catch (IOException e) {
3811                Slog.w(TAG, e);
3812            }
3813            if (pi != null) {
3814                try {
3815                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3816                } catch (SendIntentException e) {
3817                    Slog.w(TAG, e);
3818                }
3819            }
3820        });
3821    }
3822
3823    /**
3824     * Blocking call to clear various types of cached data across the system
3825     * until the requested bytes are available.
3826     */
3827    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3828        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3829        final File file = storage.findPathForUuid(volumeUuid);
3830
3831        if (ENABLE_FREE_CACHE_V2) {
3832            final boolean aggressive = (storageFlags
3833                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3834
3835            // 1. Pre-flight to determine if we have any chance to succeed
3836            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3837
3838            // 3. Consider parsed APK data (aggressive only)
3839            if (aggressive) {
3840                FileUtils.deleteContents(mCacheDir);
3841            }
3842            if (file.getUsableSpace() >= bytes) return;
3843
3844            // 4. Consider cached app data (above quotas)
3845            try {
3846                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3847            } catch (InstallerException ignored) {
3848            }
3849            if (file.getUsableSpace() >= bytes) return;
3850
3851            // 5. Consider shared libraries with refcount=0 and age>2h
3852            // 6. Consider dexopt output (aggressive only)
3853            // 7. Consider ephemeral apps not used in last week
3854
3855            // 8. Consider cached app data (below quotas)
3856            try {
3857                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3858                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3859            } catch (InstallerException ignored) {
3860            }
3861            if (file.getUsableSpace() >= bytes) return;
3862
3863            // 9. Consider DropBox entries
3864            // 10. Consider ephemeral cookies
3865
3866        } else {
3867            try {
3868                mInstaller.freeCache(volumeUuid, bytes, 0);
3869            } catch (InstallerException ignored) {
3870            }
3871            if (file.getUsableSpace() >= bytes) return;
3872        }
3873
3874        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3875    }
3876
3877    /**
3878     * Update given flags based on encryption status of current user.
3879     */
3880    private int updateFlags(int flags, int userId) {
3881        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3882                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3883            // Caller expressed an explicit opinion about what encryption
3884            // aware/unaware components they want to see, so fall through and
3885            // give them what they want
3886        } else {
3887            // Caller expressed no opinion, so match based on user state
3888            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3889                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3890            } else {
3891                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3892            }
3893        }
3894        return flags;
3895    }
3896
3897    private UserManagerInternal getUserManagerInternal() {
3898        if (mUserManagerInternal == null) {
3899            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3900        }
3901        return mUserManagerInternal;
3902    }
3903
3904    private DeviceIdleController.LocalService getDeviceIdleController() {
3905        if (mDeviceIdleController == null) {
3906            mDeviceIdleController =
3907                    LocalServices.getService(DeviceIdleController.LocalService.class);
3908        }
3909        return mDeviceIdleController;
3910    }
3911
3912    /**
3913     * Update given flags when being used to request {@link PackageInfo}.
3914     */
3915    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3916        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3917        boolean triaged = true;
3918        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3919                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3920            // Caller is asking for component details, so they'd better be
3921            // asking for specific encryption matching behavior, or be triaged
3922            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3923                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3924                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3925                triaged = false;
3926            }
3927        }
3928        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3929                | PackageManager.MATCH_SYSTEM_ONLY
3930                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3931            triaged = false;
3932        }
3933        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3934            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3935                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3936                    + Debug.getCallers(5));
3937        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3938                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3939            // If the caller wants all packages and has a restricted profile associated with it,
3940            // then match all users. This is to make sure that launchers that need to access work
3941            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3942            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3943            flags |= PackageManager.MATCH_ANY_USER;
3944        }
3945        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3946            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3947                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3948        }
3949        return updateFlags(flags, userId);
3950    }
3951
3952    /**
3953     * Update given flags when being used to request {@link ApplicationInfo}.
3954     */
3955    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3956        return updateFlagsForPackage(flags, userId, cookie);
3957    }
3958
3959    /**
3960     * Update given flags when being used to request {@link ComponentInfo}.
3961     */
3962    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3963        if (cookie instanceof Intent) {
3964            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3965                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3966            }
3967        }
3968
3969        boolean triaged = true;
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        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3978            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3979                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3980        }
3981
3982        return updateFlags(flags, userId);
3983    }
3984
3985    /**
3986     * Update given intent when being used to request {@link ResolveInfo}.
3987     */
3988    private Intent updateIntentForResolve(Intent intent) {
3989        if (intent.getSelector() != null) {
3990            intent = intent.getSelector();
3991        }
3992        if (DEBUG_PREFERRED) {
3993            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3994        }
3995        return intent;
3996    }
3997
3998    /**
3999     * Update given flags when being used to request {@link ResolveInfo}.
4000     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4001     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4002     * flag set. However, this flag is only honoured in three circumstances:
4003     * <ul>
4004     * <li>when called from a system process</li>
4005     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4006     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4007     * action and a {@code android.intent.category.BROWSABLE} category</li>
4008     * </ul>
4009     */
4010    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4011        // Safe mode means we shouldn't match any third-party components
4012        if (mSafeMode) {
4013            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4014        }
4015        final int callingUid = Binder.getCallingUid();
4016        if (getInstantAppPackageName(callingUid) != null) {
4017            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4018            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4019            flags |= PackageManager.MATCH_INSTANT;
4020        } else {
4021            // Otherwise, prevent leaking ephemeral components
4022            final boolean isSpecialProcess =
4023                    callingUid == Process.SYSTEM_UID
4024                    || callingUid == Process.SHELL_UID
4025                    || callingUid == 0;
4026            final boolean allowMatchInstant =
4027                    (includeInstantApp
4028                            && Intent.ACTION_VIEW.equals(intent.getAction())
4029                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4030                            && hasWebURI(intent))
4031                    || isSpecialProcess
4032                    || mContext.checkCallingOrSelfPermission(
4033                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4034            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4035            if (!allowMatchInstant) {
4036                flags &= ~PackageManager.MATCH_INSTANT;
4037            }
4038        }
4039        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4040    }
4041
4042    @Override
4043    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4044        if (!sUserManager.exists(userId)) return null;
4045        flags = updateFlagsForComponent(flags, userId, component);
4046        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4047                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4048        synchronized (mPackages) {
4049            PackageParser.Activity a = mActivities.mActivities.get(component);
4050
4051            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4052            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4053                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4054                if (ps == null) return null;
4055                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4056                        userId);
4057            }
4058            if (mResolveComponentName.equals(component)) {
4059                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4060                        new PackageUserState(), userId);
4061            }
4062        }
4063        return null;
4064    }
4065
4066    @Override
4067    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4068            String resolvedType) {
4069        synchronized (mPackages) {
4070            if (component.equals(mResolveComponentName)) {
4071                // The resolver supports EVERYTHING!
4072                return true;
4073            }
4074            PackageParser.Activity a = mActivities.mActivities.get(component);
4075            if (a == null) {
4076                return false;
4077            }
4078            for (int i=0; i<a.intents.size(); i++) {
4079                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4080                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4081                    return true;
4082                }
4083            }
4084            return false;
4085        }
4086    }
4087
4088    @Override
4089    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4090        if (!sUserManager.exists(userId)) return null;
4091        flags = updateFlagsForComponent(flags, userId, component);
4092        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4093                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4094        synchronized (mPackages) {
4095            PackageParser.Activity a = mReceivers.mActivities.get(component);
4096            if (DEBUG_PACKAGE_INFO) Log.v(
4097                TAG, "getReceiverInfo " + component + ": " + a);
4098            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4099                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4100                if (ps == null) return null;
4101                ActivityInfo ri = PackageParser.generateActivityInfo(a, flags,
4102                        ps.readUserState(userId), userId);
4103                if (ri != null) {
4104                    rebaseEnabledOverlays(ri.applicationInfo, userId);
4105                }
4106                return ri;
4107            }
4108        }
4109        return null;
4110    }
4111
4112    @Override
4113    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4114        if (!sUserManager.exists(userId)) return null;
4115        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4116
4117        flags = updateFlagsForPackage(flags, userId, null);
4118
4119        final boolean canSeeStaticLibraries =
4120                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4121                        == PERMISSION_GRANTED
4122                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4123                        == PERMISSION_GRANTED
4124                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4125                        == PERMISSION_GRANTED
4126                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4127                        == PERMISSION_GRANTED;
4128
4129        synchronized (mPackages) {
4130            List<SharedLibraryInfo> result = null;
4131
4132            final int libCount = mSharedLibraries.size();
4133            for (int i = 0; i < libCount; i++) {
4134                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4135                if (versionedLib == null) {
4136                    continue;
4137                }
4138
4139                final int versionCount = versionedLib.size();
4140                for (int j = 0; j < versionCount; j++) {
4141                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4142                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4143                        break;
4144                    }
4145                    final long identity = Binder.clearCallingIdentity();
4146                    try {
4147                        // TODO: We will change version code to long, so in the new API it is long
4148                        PackageInfo packageInfo = getPackageInfoVersioned(
4149                                libInfo.getDeclaringPackage(), flags, userId);
4150                        if (packageInfo == null) {
4151                            continue;
4152                        }
4153                    } finally {
4154                        Binder.restoreCallingIdentity(identity);
4155                    }
4156
4157                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4158                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4159                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4160
4161                    if (result == null) {
4162                        result = new ArrayList<>();
4163                    }
4164                    result.add(resLibInfo);
4165                }
4166            }
4167
4168            return result != null ? new ParceledListSlice<>(result) : null;
4169        }
4170    }
4171
4172    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4173            SharedLibraryInfo libInfo, int flags, int userId) {
4174        List<VersionedPackage> versionedPackages = null;
4175        final int packageCount = mSettings.mPackages.size();
4176        for (int i = 0; i < packageCount; i++) {
4177            PackageSetting ps = mSettings.mPackages.valueAt(i);
4178
4179            if (ps == null) {
4180                continue;
4181            }
4182
4183            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4184                continue;
4185            }
4186
4187            final String libName = libInfo.getName();
4188            if (libInfo.isStatic()) {
4189                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4190                if (libIdx < 0) {
4191                    continue;
4192                }
4193                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4194                    continue;
4195                }
4196                if (versionedPackages == null) {
4197                    versionedPackages = new ArrayList<>();
4198                }
4199                // If the dependent is a static shared lib, use the public package name
4200                String dependentPackageName = ps.name;
4201                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4202                    dependentPackageName = ps.pkg.manifestPackageName;
4203                }
4204                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4205            } else if (ps.pkg != null) {
4206                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4207                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4208                    if (versionedPackages == null) {
4209                        versionedPackages = new ArrayList<>();
4210                    }
4211                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4212                }
4213            }
4214        }
4215
4216        return versionedPackages;
4217    }
4218
4219    @Override
4220    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4221        if (!sUserManager.exists(userId)) return null;
4222        flags = updateFlagsForComponent(flags, userId, component);
4223        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4224                false /* requireFullPermission */, false /* checkShell */, "get service info");
4225        synchronized (mPackages) {
4226            PackageParser.Service s = mServices.mServices.get(component);
4227            if (DEBUG_PACKAGE_INFO) Log.v(
4228                TAG, "getServiceInfo " + component + ": " + s);
4229            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4230                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4231                if (ps == null) return null;
4232                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4233                        ps.readUserState(userId), userId);
4234                if (si != null) {
4235                    rebaseEnabledOverlays(si.applicationInfo, userId);
4236                }
4237                return si;
4238            }
4239        }
4240        return null;
4241    }
4242
4243    @Override
4244    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4245        if (!sUserManager.exists(userId)) return null;
4246        flags = updateFlagsForComponent(flags, userId, component);
4247        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4248                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4249        synchronized (mPackages) {
4250            PackageParser.Provider p = mProviders.mProviders.get(component);
4251            if (DEBUG_PACKAGE_INFO) Log.v(
4252                TAG, "getProviderInfo " + component + ": " + p);
4253            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4254                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4255                if (ps == null) return null;
4256                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4257                        ps.readUserState(userId), userId);
4258                if (pi != null) {
4259                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4260                }
4261                return pi;
4262            }
4263        }
4264        return null;
4265    }
4266
4267    @Override
4268    public String[] getSystemSharedLibraryNames() {
4269        synchronized (mPackages) {
4270            Set<String> libs = null;
4271            final int libCount = mSharedLibraries.size();
4272            for (int i = 0; i < libCount; i++) {
4273                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4274                if (versionedLib == null) {
4275                    continue;
4276                }
4277                final int versionCount = versionedLib.size();
4278                for (int j = 0; j < versionCount; j++) {
4279                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4280                    if (!libEntry.info.isStatic()) {
4281                        if (libs == null) {
4282                            libs = new ArraySet<>();
4283                        }
4284                        libs.add(libEntry.info.getName());
4285                        break;
4286                    }
4287                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4288                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4289                            UserHandle.getUserId(Binder.getCallingUid()))) {
4290                        if (libs == null) {
4291                            libs = new ArraySet<>();
4292                        }
4293                        libs.add(libEntry.info.getName());
4294                        break;
4295                    }
4296                }
4297            }
4298
4299            if (libs != null) {
4300                String[] libsArray = new String[libs.size()];
4301                libs.toArray(libsArray);
4302                return libsArray;
4303            }
4304
4305            return null;
4306        }
4307    }
4308
4309    @Override
4310    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4311        synchronized (mPackages) {
4312            return mServicesSystemSharedLibraryPackageName;
4313        }
4314    }
4315
4316    @Override
4317    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4318        synchronized (mPackages) {
4319            return mSharedSystemSharedLibraryPackageName;
4320        }
4321    }
4322
4323    private void updateSequenceNumberLP(String packageName, int[] userList) {
4324        for (int i = userList.length - 1; i >= 0; --i) {
4325            final int userId = userList[i];
4326            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4327            if (changedPackages == null) {
4328                changedPackages = new SparseArray<>();
4329                mChangedPackages.put(userId, changedPackages);
4330            }
4331            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4332            if (sequenceNumbers == null) {
4333                sequenceNumbers = new HashMap<>();
4334                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4335            }
4336            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4337            if (sequenceNumber != null) {
4338                changedPackages.remove(sequenceNumber);
4339            }
4340            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4341            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4342        }
4343        mChangedPackagesSequenceNumber++;
4344    }
4345
4346    @Override
4347    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4348        synchronized (mPackages) {
4349            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4350                return null;
4351            }
4352            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4353            if (changedPackages == null) {
4354                return null;
4355            }
4356            final List<String> packageNames =
4357                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4358            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4359                final String packageName = changedPackages.get(i);
4360                if (packageName != null) {
4361                    packageNames.add(packageName);
4362                }
4363            }
4364            return packageNames.isEmpty()
4365                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4366        }
4367    }
4368
4369    @Override
4370    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4371        ArrayList<FeatureInfo> res;
4372        synchronized (mAvailableFeatures) {
4373            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4374            res.addAll(mAvailableFeatures.values());
4375        }
4376        final FeatureInfo fi = new FeatureInfo();
4377        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4378                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4379        res.add(fi);
4380
4381        return new ParceledListSlice<>(res);
4382    }
4383
4384    @Override
4385    public boolean hasSystemFeature(String name, int version) {
4386        synchronized (mAvailableFeatures) {
4387            final FeatureInfo feat = mAvailableFeatures.get(name);
4388            if (feat == null) {
4389                return false;
4390            } else {
4391                return feat.version >= version;
4392            }
4393        }
4394    }
4395
4396    @Override
4397    public int checkPermission(String permName, String pkgName, int userId) {
4398        if (!sUserManager.exists(userId)) {
4399            return PackageManager.PERMISSION_DENIED;
4400        }
4401
4402        synchronized (mPackages) {
4403            final PackageParser.Package p = mPackages.get(pkgName);
4404            if (p != null && p.mExtras != null) {
4405                final PackageSetting ps = (PackageSetting) p.mExtras;
4406                final PermissionsState permissionsState = ps.getPermissionsState();
4407                if (permissionsState.hasPermission(permName, userId)) {
4408                    return PackageManager.PERMISSION_GRANTED;
4409                }
4410                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4411                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4412                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4413                    return PackageManager.PERMISSION_GRANTED;
4414                }
4415            }
4416        }
4417
4418        return PackageManager.PERMISSION_DENIED;
4419    }
4420
4421    @Override
4422    public int checkUidPermission(String permName, int uid) {
4423        final int userId = UserHandle.getUserId(uid);
4424
4425        if (!sUserManager.exists(userId)) {
4426            return PackageManager.PERMISSION_DENIED;
4427        }
4428
4429        synchronized (mPackages) {
4430            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4431            if (obj != null) {
4432                final SettingBase ps = (SettingBase) obj;
4433                final PermissionsState permissionsState = ps.getPermissionsState();
4434                if (permissionsState.hasPermission(permName, userId)) {
4435                    return PackageManager.PERMISSION_GRANTED;
4436                }
4437                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4438                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4439                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4440                    return PackageManager.PERMISSION_GRANTED;
4441                }
4442            } else {
4443                ArraySet<String> perms = mSystemPermissions.get(uid);
4444                if (perms != null) {
4445                    if (perms.contains(permName)) {
4446                        return PackageManager.PERMISSION_GRANTED;
4447                    }
4448                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4449                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4450                        return PackageManager.PERMISSION_GRANTED;
4451                    }
4452                }
4453            }
4454        }
4455
4456        return PackageManager.PERMISSION_DENIED;
4457    }
4458
4459    @Override
4460    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4461        if (UserHandle.getCallingUserId() != userId) {
4462            mContext.enforceCallingPermission(
4463                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4464                    "isPermissionRevokedByPolicy for user " + userId);
4465        }
4466
4467        if (checkPermission(permission, packageName, userId)
4468                == PackageManager.PERMISSION_GRANTED) {
4469            return false;
4470        }
4471
4472        final long identity = Binder.clearCallingIdentity();
4473        try {
4474            final int flags = getPermissionFlags(permission, packageName, userId);
4475            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4476        } finally {
4477            Binder.restoreCallingIdentity(identity);
4478        }
4479    }
4480
4481    @Override
4482    public String getPermissionControllerPackageName() {
4483        synchronized (mPackages) {
4484            return mRequiredInstallerPackage;
4485        }
4486    }
4487
4488    /**
4489     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4490     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4491     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4492     * @param message the message to log on security exception
4493     */
4494    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4495            boolean checkShell, String message) {
4496        if (userId < 0) {
4497            throw new IllegalArgumentException("Invalid userId " + userId);
4498        }
4499        if (checkShell) {
4500            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4501        }
4502        if (userId == UserHandle.getUserId(callingUid)) return;
4503        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4504            if (requireFullPermission) {
4505                mContext.enforceCallingOrSelfPermission(
4506                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4507            } else {
4508                try {
4509                    mContext.enforceCallingOrSelfPermission(
4510                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4511                } catch (SecurityException se) {
4512                    mContext.enforceCallingOrSelfPermission(
4513                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4514                }
4515            }
4516        }
4517    }
4518
4519    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4520        if (callingUid == Process.SHELL_UID) {
4521            if (userHandle >= 0
4522                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4523                throw new SecurityException("Shell does not have permission to access user "
4524                        + userHandle);
4525            } else if (userHandle < 0) {
4526                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4527                        + Debug.getCallers(3));
4528            }
4529        }
4530    }
4531
4532    private BasePermission findPermissionTreeLP(String permName) {
4533        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4534            if (permName.startsWith(bp.name) &&
4535                    permName.length() > bp.name.length() &&
4536                    permName.charAt(bp.name.length()) == '.') {
4537                return bp;
4538            }
4539        }
4540        return null;
4541    }
4542
4543    private BasePermission checkPermissionTreeLP(String permName) {
4544        if (permName != null) {
4545            BasePermission bp = findPermissionTreeLP(permName);
4546            if (bp != null) {
4547                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4548                    return bp;
4549                }
4550                throw new SecurityException("Calling uid "
4551                        + Binder.getCallingUid()
4552                        + " is not allowed to add to permission tree "
4553                        + bp.name + " owned by uid " + bp.uid);
4554            }
4555        }
4556        throw new SecurityException("No permission tree found for " + permName);
4557    }
4558
4559    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4560        if (s1 == null) {
4561            return s2 == null;
4562        }
4563        if (s2 == null) {
4564            return false;
4565        }
4566        if (s1.getClass() != s2.getClass()) {
4567            return false;
4568        }
4569        return s1.equals(s2);
4570    }
4571
4572    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4573        if (pi1.icon != pi2.icon) return false;
4574        if (pi1.logo != pi2.logo) return false;
4575        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4576        if (!compareStrings(pi1.name, pi2.name)) return false;
4577        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4578        // We'll take care of setting this one.
4579        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4580        // These are not currently stored in settings.
4581        //if (!compareStrings(pi1.group, pi2.group)) return false;
4582        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4583        //if (pi1.labelRes != pi2.labelRes) return false;
4584        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4585        return true;
4586    }
4587
4588    int permissionInfoFootprint(PermissionInfo info) {
4589        int size = info.name.length();
4590        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4591        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4592        return size;
4593    }
4594
4595    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4596        int size = 0;
4597        for (BasePermission perm : mSettings.mPermissions.values()) {
4598            if (perm.uid == tree.uid) {
4599                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4600            }
4601        }
4602        return size;
4603    }
4604
4605    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4606        // We calculate the max size of permissions defined by this uid and throw
4607        // if that plus the size of 'info' would exceed our stated maximum.
4608        if (tree.uid != Process.SYSTEM_UID) {
4609            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4610            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4611                throw new SecurityException("Permission tree size cap exceeded");
4612            }
4613        }
4614    }
4615
4616    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4617        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4618            throw new SecurityException("Label must be specified in permission");
4619        }
4620        BasePermission tree = checkPermissionTreeLP(info.name);
4621        BasePermission bp = mSettings.mPermissions.get(info.name);
4622        boolean added = bp == null;
4623        boolean changed = true;
4624        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4625        if (added) {
4626            enforcePermissionCapLocked(info, tree);
4627            bp = new BasePermission(info.name, tree.sourcePackage,
4628                    BasePermission.TYPE_DYNAMIC);
4629        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4630            throw new SecurityException(
4631                    "Not allowed to modify non-dynamic permission "
4632                    + info.name);
4633        } else {
4634            if (bp.protectionLevel == fixedLevel
4635                    && bp.perm.owner.equals(tree.perm.owner)
4636                    && bp.uid == tree.uid
4637                    && comparePermissionInfos(bp.perm.info, info)) {
4638                changed = false;
4639            }
4640        }
4641        bp.protectionLevel = fixedLevel;
4642        info = new PermissionInfo(info);
4643        info.protectionLevel = fixedLevel;
4644        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4645        bp.perm.info.packageName = tree.perm.info.packageName;
4646        bp.uid = tree.uid;
4647        if (added) {
4648            mSettings.mPermissions.put(info.name, bp);
4649        }
4650        if (changed) {
4651            if (!async) {
4652                mSettings.writeLPr();
4653            } else {
4654                scheduleWriteSettingsLocked();
4655            }
4656        }
4657        return added;
4658    }
4659
4660    @Override
4661    public boolean addPermission(PermissionInfo info) {
4662        synchronized (mPackages) {
4663            return addPermissionLocked(info, false);
4664        }
4665    }
4666
4667    @Override
4668    public boolean addPermissionAsync(PermissionInfo info) {
4669        synchronized (mPackages) {
4670            return addPermissionLocked(info, true);
4671        }
4672    }
4673
4674    @Override
4675    public void removePermission(String name) {
4676        synchronized (mPackages) {
4677            checkPermissionTreeLP(name);
4678            BasePermission bp = mSettings.mPermissions.get(name);
4679            if (bp != null) {
4680                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4681                    throw new SecurityException(
4682                            "Not allowed to modify non-dynamic permission "
4683                            + name);
4684                }
4685                mSettings.mPermissions.remove(name);
4686                mSettings.writeLPr();
4687            }
4688        }
4689    }
4690
4691    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4692            BasePermission bp) {
4693        int index = pkg.requestedPermissions.indexOf(bp.name);
4694        if (index == -1) {
4695            throw new SecurityException("Package " + pkg.packageName
4696                    + " has not requested permission " + bp.name);
4697        }
4698        if (!bp.isRuntime() && !bp.isDevelopment()) {
4699            throw new SecurityException("Permission " + bp.name
4700                    + " is not a changeable permission type");
4701        }
4702    }
4703
4704    @Override
4705    public void grantRuntimePermission(String packageName, String name, final int userId) {
4706        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4707    }
4708
4709    private void grantRuntimePermission(String packageName, String name, final int userId,
4710            boolean overridePolicy) {
4711        if (!sUserManager.exists(userId)) {
4712            Log.e(TAG, "No such user:" + userId);
4713            return;
4714        }
4715
4716        mContext.enforceCallingOrSelfPermission(
4717                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4718                "grantRuntimePermission");
4719
4720        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4721                true /* requireFullPermission */, true /* checkShell */,
4722                "grantRuntimePermission");
4723
4724        final int uid;
4725        final SettingBase sb;
4726
4727        synchronized (mPackages) {
4728            final PackageParser.Package pkg = mPackages.get(packageName);
4729            if (pkg == null) {
4730                throw new IllegalArgumentException("Unknown package: " + packageName);
4731            }
4732
4733            final BasePermission bp = mSettings.mPermissions.get(name);
4734            if (bp == null) {
4735                throw new IllegalArgumentException("Unknown permission: " + name);
4736            }
4737
4738            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4739
4740            // If a permission review is required for legacy apps we represent
4741            // their permissions as always granted runtime ones since we need
4742            // to keep the review required permission flag per user while an
4743            // install permission's state is shared across all users.
4744            if (mPermissionReviewRequired
4745                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4746                    && bp.isRuntime()) {
4747                return;
4748            }
4749
4750            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4751            sb = (SettingBase) pkg.mExtras;
4752            if (sb == null) {
4753                throw new IllegalArgumentException("Unknown package: " + packageName);
4754            }
4755
4756            final PermissionsState permissionsState = sb.getPermissionsState();
4757
4758            final int flags = permissionsState.getPermissionFlags(name, userId);
4759            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4760                throw new SecurityException("Cannot grant system fixed permission "
4761                        + name + " for package " + packageName);
4762            }
4763            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4764                throw new SecurityException("Cannot grant policy fixed permission "
4765                        + name + " for package " + packageName);
4766            }
4767
4768            if (bp.isDevelopment()) {
4769                // Development permissions must be handled specially, since they are not
4770                // normal runtime permissions.  For now they apply to all users.
4771                if (permissionsState.grantInstallPermission(bp) !=
4772                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4773                    scheduleWriteSettingsLocked();
4774                }
4775                return;
4776            }
4777
4778            final PackageSetting ps = mSettings.mPackages.get(packageName);
4779            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4780                throw new SecurityException("Cannot grant non-ephemeral permission"
4781                        + name + " for package " + packageName);
4782            }
4783
4784            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4785                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4786                return;
4787            }
4788
4789            final int result = permissionsState.grantRuntimePermission(bp, userId);
4790            switch (result) {
4791                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4792                    return;
4793                }
4794
4795                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4796                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4797                    mHandler.post(new Runnable() {
4798                        @Override
4799                        public void run() {
4800                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4801                        }
4802                    });
4803                }
4804                break;
4805            }
4806
4807            if (bp.isRuntime()) {
4808                logPermissionGranted(mContext, name, packageName);
4809            }
4810
4811            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4812
4813            // Not critical if that is lost - app has to request again.
4814            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4815        }
4816
4817        // Only need to do this if user is initialized. Otherwise it's a new user
4818        // and there are no processes running as the user yet and there's no need
4819        // to make an expensive call to remount processes for the changed permissions.
4820        if (READ_EXTERNAL_STORAGE.equals(name)
4821                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4822            final long token = Binder.clearCallingIdentity();
4823            try {
4824                if (sUserManager.isInitialized(userId)) {
4825                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4826                            StorageManagerInternal.class);
4827                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4828                }
4829            } finally {
4830                Binder.restoreCallingIdentity(token);
4831            }
4832        }
4833    }
4834
4835    @Override
4836    public void revokeRuntimePermission(String packageName, String name, int userId) {
4837        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4838    }
4839
4840    private void revokeRuntimePermission(String packageName, String name, int userId,
4841            boolean overridePolicy) {
4842        if (!sUserManager.exists(userId)) {
4843            Log.e(TAG, "No such user:" + userId);
4844            return;
4845        }
4846
4847        mContext.enforceCallingOrSelfPermission(
4848                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4849                "revokeRuntimePermission");
4850
4851        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4852                true /* requireFullPermission */, true /* checkShell */,
4853                "revokeRuntimePermission");
4854
4855        final int appId;
4856
4857        synchronized (mPackages) {
4858            final PackageParser.Package pkg = mPackages.get(packageName);
4859            if (pkg == null) {
4860                throw new IllegalArgumentException("Unknown package: " + packageName);
4861            }
4862
4863            final BasePermission bp = mSettings.mPermissions.get(name);
4864            if (bp == null) {
4865                throw new IllegalArgumentException("Unknown permission: " + name);
4866            }
4867
4868            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4869
4870            // If a permission review is required for legacy apps we represent
4871            // their permissions as always granted runtime ones since we need
4872            // to keep the review required permission flag per user while an
4873            // install permission's state is shared across all users.
4874            if (mPermissionReviewRequired
4875                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4876                    && bp.isRuntime()) {
4877                return;
4878            }
4879
4880            SettingBase sb = (SettingBase) pkg.mExtras;
4881            if (sb == null) {
4882                throw new IllegalArgumentException("Unknown package: " + packageName);
4883            }
4884
4885            final PermissionsState permissionsState = sb.getPermissionsState();
4886
4887            final int flags = permissionsState.getPermissionFlags(name, userId);
4888            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4889                throw new SecurityException("Cannot revoke system fixed permission "
4890                        + name + " for package " + packageName);
4891            }
4892            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4893                throw new SecurityException("Cannot revoke policy fixed permission "
4894                        + name + " for package " + packageName);
4895            }
4896
4897            if (bp.isDevelopment()) {
4898                // Development permissions must be handled specially, since they are not
4899                // normal runtime permissions.  For now they apply to all users.
4900                if (permissionsState.revokeInstallPermission(bp) !=
4901                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4902                    scheduleWriteSettingsLocked();
4903                }
4904                return;
4905            }
4906
4907            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4908                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4909                return;
4910            }
4911
4912            if (bp.isRuntime()) {
4913                logPermissionRevoked(mContext, name, packageName);
4914            }
4915
4916            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4917
4918            // Critical, after this call app should never have the permission.
4919            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4920
4921            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4922        }
4923
4924        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4925    }
4926
4927    /**
4928     * Get the first event id for the permission.
4929     *
4930     * <p>There are four events for each permission: <ul>
4931     *     <li>Request permission: first id + 0</li>
4932     *     <li>Grant permission: first id + 1</li>
4933     *     <li>Request for permission denied: first id + 2</li>
4934     *     <li>Revoke permission: first id + 3</li>
4935     * </ul></p>
4936     *
4937     * @param name name of the permission
4938     *
4939     * @return The first event id for the permission
4940     */
4941    private static int getBaseEventId(@NonNull String name) {
4942        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4943
4944        if (eventIdIndex == -1) {
4945            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4946                    || "user".equals(Build.TYPE)) {
4947                Log.i(TAG, "Unknown permission " + name);
4948
4949                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4950            } else {
4951                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4952                //
4953                // Also update
4954                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4955                // - metrics_constants.proto
4956                throw new IllegalStateException("Unknown permission " + name);
4957            }
4958        }
4959
4960        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4961    }
4962
4963    /**
4964     * Log that a permission was revoked.
4965     *
4966     * @param context Context of the caller
4967     * @param name name of the permission
4968     * @param packageName package permission if for
4969     */
4970    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4971            @NonNull String packageName) {
4972        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4973    }
4974
4975    /**
4976     * Log that a permission request was granted.
4977     *
4978     * @param context Context of the caller
4979     * @param name name of the permission
4980     * @param packageName package permission if for
4981     */
4982    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4983            @NonNull String packageName) {
4984        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4985    }
4986
4987    @Override
4988    public void resetRuntimePermissions() {
4989        mContext.enforceCallingOrSelfPermission(
4990                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4991                "revokeRuntimePermission");
4992
4993        int callingUid = Binder.getCallingUid();
4994        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4995            mContext.enforceCallingOrSelfPermission(
4996                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4997                    "resetRuntimePermissions");
4998        }
4999
5000        synchronized (mPackages) {
5001            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5002            for (int userId : UserManagerService.getInstance().getUserIds()) {
5003                final int packageCount = mPackages.size();
5004                for (int i = 0; i < packageCount; i++) {
5005                    PackageParser.Package pkg = mPackages.valueAt(i);
5006                    if (!(pkg.mExtras instanceof PackageSetting)) {
5007                        continue;
5008                    }
5009                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5010                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5011                }
5012            }
5013        }
5014    }
5015
5016    @Override
5017    public int getPermissionFlags(String name, String packageName, int userId) {
5018        if (!sUserManager.exists(userId)) {
5019            return 0;
5020        }
5021
5022        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5023
5024        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5025                true /* requireFullPermission */, false /* checkShell */,
5026                "getPermissionFlags");
5027
5028        synchronized (mPackages) {
5029            final PackageParser.Package pkg = mPackages.get(packageName);
5030            if (pkg == null) {
5031                return 0;
5032            }
5033
5034            final BasePermission bp = mSettings.mPermissions.get(name);
5035            if (bp == null) {
5036                return 0;
5037            }
5038
5039            SettingBase sb = (SettingBase) pkg.mExtras;
5040            if (sb == null) {
5041                return 0;
5042            }
5043
5044            PermissionsState permissionsState = sb.getPermissionsState();
5045            return permissionsState.getPermissionFlags(name, userId);
5046        }
5047    }
5048
5049    @Override
5050    public void updatePermissionFlags(String name, String packageName, int flagMask,
5051            int flagValues, int userId) {
5052        if (!sUserManager.exists(userId)) {
5053            return;
5054        }
5055
5056        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5057
5058        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5059                true /* requireFullPermission */, true /* checkShell */,
5060                "updatePermissionFlags");
5061
5062        // Only the system can change these flags and nothing else.
5063        if (getCallingUid() != Process.SYSTEM_UID) {
5064            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5065            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5066            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5067            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5068            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5069        }
5070
5071        synchronized (mPackages) {
5072            final PackageParser.Package pkg = mPackages.get(packageName);
5073            if (pkg == null) {
5074                throw new IllegalArgumentException("Unknown package: " + packageName);
5075            }
5076
5077            final BasePermission bp = mSettings.mPermissions.get(name);
5078            if (bp == null) {
5079                throw new IllegalArgumentException("Unknown permission: " + name);
5080            }
5081
5082            SettingBase sb = (SettingBase) pkg.mExtras;
5083            if (sb == null) {
5084                throw new IllegalArgumentException("Unknown package: " + packageName);
5085            }
5086
5087            PermissionsState permissionsState = sb.getPermissionsState();
5088
5089            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5090
5091            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5092                // Install and runtime permissions are stored in different places,
5093                // so figure out what permission changed and persist the change.
5094                if (permissionsState.getInstallPermissionState(name) != null) {
5095                    scheduleWriteSettingsLocked();
5096                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5097                        || hadState) {
5098                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5099                }
5100            }
5101        }
5102    }
5103
5104    /**
5105     * Update the permission flags for all packages and runtime permissions of a user in order
5106     * to allow device or profile owner to remove POLICY_FIXED.
5107     */
5108    @Override
5109    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5110        if (!sUserManager.exists(userId)) {
5111            return;
5112        }
5113
5114        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5115
5116        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5117                true /* requireFullPermission */, true /* checkShell */,
5118                "updatePermissionFlagsForAllApps");
5119
5120        // Only the system can change system fixed flags.
5121        if (getCallingUid() != Process.SYSTEM_UID) {
5122            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5123            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5124        }
5125
5126        synchronized (mPackages) {
5127            boolean changed = false;
5128            final int packageCount = mPackages.size();
5129            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5130                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5131                SettingBase sb = (SettingBase) pkg.mExtras;
5132                if (sb == null) {
5133                    continue;
5134                }
5135                PermissionsState permissionsState = sb.getPermissionsState();
5136                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5137                        userId, flagMask, flagValues);
5138            }
5139            if (changed) {
5140                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5141            }
5142        }
5143    }
5144
5145    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5146        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5147                != PackageManager.PERMISSION_GRANTED
5148            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5149                != PackageManager.PERMISSION_GRANTED) {
5150            throw new SecurityException(message + " requires "
5151                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5152                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5153        }
5154    }
5155
5156    @Override
5157    public boolean shouldShowRequestPermissionRationale(String permissionName,
5158            String packageName, int userId) {
5159        if (UserHandle.getCallingUserId() != userId) {
5160            mContext.enforceCallingPermission(
5161                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5162                    "canShowRequestPermissionRationale for user " + userId);
5163        }
5164
5165        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5166        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5167            return false;
5168        }
5169
5170        if (checkPermission(permissionName, packageName, userId)
5171                == PackageManager.PERMISSION_GRANTED) {
5172            return false;
5173        }
5174
5175        final int flags;
5176
5177        final long identity = Binder.clearCallingIdentity();
5178        try {
5179            flags = getPermissionFlags(permissionName,
5180                    packageName, userId);
5181        } finally {
5182            Binder.restoreCallingIdentity(identity);
5183        }
5184
5185        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5186                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5187                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5188
5189        if ((flags & fixedFlags) != 0) {
5190            return false;
5191        }
5192
5193        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5194    }
5195
5196    @Override
5197    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5198        mContext.enforceCallingOrSelfPermission(
5199                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5200                "addOnPermissionsChangeListener");
5201
5202        synchronized (mPackages) {
5203            mOnPermissionChangeListeners.addListenerLocked(listener);
5204        }
5205    }
5206
5207    @Override
5208    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5209        synchronized (mPackages) {
5210            mOnPermissionChangeListeners.removeListenerLocked(listener);
5211        }
5212    }
5213
5214    @Override
5215    public boolean isProtectedBroadcast(String actionName) {
5216        synchronized (mPackages) {
5217            if (mProtectedBroadcasts.contains(actionName)) {
5218                return true;
5219            } else if (actionName != null) {
5220                // TODO: remove these terrible hacks
5221                if (actionName.startsWith("android.net.netmon.lingerExpired")
5222                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5223                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5224                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5225                    return true;
5226                }
5227            }
5228        }
5229        return false;
5230    }
5231
5232    @Override
5233    public int checkSignatures(String pkg1, String pkg2) {
5234        synchronized (mPackages) {
5235            final PackageParser.Package p1 = mPackages.get(pkg1);
5236            final PackageParser.Package p2 = mPackages.get(pkg2);
5237            if (p1 == null || p1.mExtras == null
5238                    || p2 == null || p2.mExtras == null) {
5239                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5240            }
5241            return compareSignatures(p1.mSignatures, p2.mSignatures);
5242        }
5243    }
5244
5245    @Override
5246    public int checkUidSignatures(int uid1, int uid2) {
5247        // Map to base uids.
5248        uid1 = UserHandle.getAppId(uid1);
5249        uid2 = UserHandle.getAppId(uid2);
5250        // reader
5251        synchronized (mPackages) {
5252            Signature[] s1;
5253            Signature[] s2;
5254            Object obj = mSettings.getUserIdLPr(uid1);
5255            if (obj != null) {
5256                if (obj instanceof SharedUserSetting) {
5257                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5258                } else if (obj instanceof PackageSetting) {
5259                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5260                } else {
5261                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5262                }
5263            } else {
5264                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5265            }
5266            obj = mSettings.getUserIdLPr(uid2);
5267            if (obj != null) {
5268                if (obj instanceof SharedUserSetting) {
5269                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5270                } else if (obj instanceof PackageSetting) {
5271                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5272                } else {
5273                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5274                }
5275            } else {
5276                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5277            }
5278            return compareSignatures(s1, s2);
5279        }
5280    }
5281
5282    /**
5283     * This method should typically only be used when granting or revoking
5284     * permissions, since the app may immediately restart after this call.
5285     * <p>
5286     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5287     * guard your work against the app being relaunched.
5288     */
5289    private void killUid(int appId, int userId, String reason) {
5290        final long identity = Binder.clearCallingIdentity();
5291        try {
5292            IActivityManager am = ActivityManager.getService();
5293            if (am != null) {
5294                try {
5295                    am.killUid(appId, userId, reason);
5296                } catch (RemoteException e) {
5297                    /* ignore - same process */
5298                }
5299            }
5300        } finally {
5301            Binder.restoreCallingIdentity(identity);
5302        }
5303    }
5304
5305    /**
5306     * Compares two sets of signatures. Returns:
5307     * <br />
5308     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5309     * <br />
5310     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5311     * <br />
5312     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5313     * <br />
5314     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5315     * <br />
5316     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5317     */
5318    static int compareSignatures(Signature[] s1, Signature[] s2) {
5319        if (s1 == null) {
5320            return s2 == null
5321                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5322                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5323        }
5324
5325        if (s2 == null) {
5326            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5327        }
5328
5329        if (s1.length != s2.length) {
5330            return PackageManager.SIGNATURE_NO_MATCH;
5331        }
5332
5333        // Since both signature sets are of size 1, we can compare without HashSets.
5334        if (s1.length == 1) {
5335            return s1[0].equals(s2[0]) ?
5336                    PackageManager.SIGNATURE_MATCH :
5337                    PackageManager.SIGNATURE_NO_MATCH;
5338        }
5339
5340        ArraySet<Signature> set1 = new ArraySet<Signature>();
5341        for (Signature sig : s1) {
5342            set1.add(sig);
5343        }
5344        ArraySet<Signature> set2 = new ArraySet<Signature>();
5345        for (Signature sig : s2) {
5346            set2.add(sig);
5347        }
5348        // Make sure s2 contains all signatures in s1.
5349        if (set1.equals(set2)) {
5350            return PackageManager.SIGNATURE_MATCH;
5351        }
5352        return PackageManager.SIGNATURE_NO_MATCH;
5353    }
5354
5355    /**
5356     * If the database version for this type of package (internal storage or
5357     * external storage) is less than the version where package signatures
5358     * were updated, return true.
5359     */
5360    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5361        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5362        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5363    }
5364
5365    /**
5366     * Used for backward compatibility to make sure any packages with
5367     * certificate chains get upgraded to the new style. {@code existingSigs}
5368     * will be in the old format (since they were stored on disk from before the
5369     * system upgrade) and {@code scannedSigs} will be in the newer format.
5370     */
5371    private int compareSignaturesCompat(PackageSignatures existingSigs,
5372            PackageParser.Package scannedPkg) {
5373        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5374            return PackageManager.SIGNATURE_NO_MATCH;
5375        }
5376
5377        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5378        for (Signature sig : existingSigs.mSignatures) {
5379            existingSet.add(sig);
5380        }
5381        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5382        for (Signature sig : scannedPkg.mSignatures) {
5383            try {
5384                Signature[] chainSignatures = sig.getChainSignatures();
5385                for (Signature chainSig : chainSignatures) {
5386                    scannedCompatSet.add(chainSig);
5387                }
5388            } catch (CertificateEncodingException e) {
5389                scannedCompatSet.add(sig);
5390            }
5391        }
5392        /*
5393         * Make sure the expanded scanned set contains all signatures in the
5394         * existing one.
5395         */
5396        if (scannedCompatSet.equals(existingSet)) {
5397            // Migrate the old signatures to the new scheme.
5398            existingSigs.assignSignatures(scannedPkg.mSignatures);
5399            // The new KeySets will be re-added later in the scanning process.
5400            synchronized (mPackages) {
5401                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5402            }
5403            return PackageManager.SIGNATURE_MATCH;
5404        }
5405        return PackageManager.SIGNATURE_NO_MATCH;
5406    }
5407
5408    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5409        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5410        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5411    }
5412
5413    private int compareSignaturesRecover(PackageSignatures existingSigs,
5414            PackageParser.Package scannedPkg) {
5415        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5416            return PackageManager.SIGNATURE_NO_MATCH;
5417        }
5418
5419        String msg = null;
5420        try {
5421            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5422                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5423                        + scannedPkg.packageName);
5424                return PackageManager.SIGNATURE_MATCH;
5425            }
5426        } catch (CertificateException e) {
5427            msg = e.getMessage();
5428        }
5429
5430        logCriticalInfo(Log.INFO,
5431                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5432        return PackageManager.SIGNATURE_NO_MATCH;
5433    }
5434
5435    @Override
5436    public List<String> getAllPackages() {
5437        synchronized (mPackages) {
5438            return new ArrayList<String>(mPackages.keySet());
5439        }
5440    }
5441
5442    @Override
5443    public String[] getPackagesForUid(int uid) {
5444        final int userId = UserHandle.getUserId(uid);
5445        uid = UserHandle.getAppId(uid);
5446        // reader
5447        synchronized (mPackages) {
5448            Object obj = mSettings.getUserIdLPr(uid);
5449            if (obj instanceof SharedUserSetting) {
5450                final SharedUserSetting sus = (SharedUserSetting) obj;
5451                final int N = sus.packages.size();
5452                String[] res = new String[N];
5453                final Iterator<PackageSetting> it = sus.packages.iterator();
5454                int i = 0;
5455                while (it.hasNext()) {
5456                    PackageSetting ps = it.next();
5457                    if (ps.getInstalled(userId)) {
5458                        res[i++] = ps.name;
5459                    } else {
5460                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5461                    }
5462                }
5463                return res;
5464            } else if (obj instanceof PackageSetting) {
5465                final PackageSetting ps = (PackageSetting) obj;
5466                if (ps.getInstalled(userId)) {
5467                    return new String[]{ps.name};
5468                }
5469            }
5470        }
5471        return null;
5472    }
5473
5474    @Override
5475    public String getNameForUid(int uid) {
5476        // reader
5477        synchronized (mPackages) {
5478            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5479            if (obj instanceof SharedUserSetting) {
5480                final SharedUserSetting sus = (SharedUserSetting) obj;
5481                return sus.name + ":" + sus.userId;
5482            } else if (obj instanceof PackageSetting) {
5483                final PackageSetting ps = (PackageSetting) obj;
5484                return ps.name;
5485            }
5486        }
5487        return null;
5488    }
5489
5490    @Override
5491    public int getUidForSharedUser(String sharedUserName) {
5492        if(sharedUserName == null) {
5493            return -1;
5494        }
5495        // reader
5496        synchronized (mPackages) {
5497            SharedUserSetting suid;
5498            try {
5499                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5500                if (suid != null) {
5501                    return suid.userId;
5502                }
5503            } catch (PackageManagerException ignore) {
5504                // can't happen, but, still need to catch it
5505            }
5506            return -1;
5507        }
5508    }
5509
5510    @Override
5511    public int getFlagsForUid(int uid) {
5512        synchronized (mPackages) {
5513            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5514            if (obj instanceof SharedUserSetting) {
5515                final SharedUserSetting sus = (SharedUserSetting) obj;
5516                return sus.pkgFlags;
5517            } else if (obj instanceof PackageSetting) {
5518                final PackageSetting ps = (PackageSetting) obj;
5519                return ps.pkgFlags;
5520            }
5521        }
5522        return 0;
5523    }
5524
5525    @Override
5526    public int getPrivateFlagsForUid(int uid) {
5527        synchronized (mPackages) {
5528            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5529            if (obj instanceof SharedUserSetting) {
5530                final SharedUserSetting sus = (SharedUserSetting) obj;
5531                return sus.pkgPrivateFlags;
5532            } else if (obj instanceof PackageSetting) {
5533                final PackageSetting ps = (PackageSetting) obj;
5534                return ps.pkgPrivateFlags;
5535            }
5536        }
5537        return 0;
5538    }
5539
5540    @Override
5541    public boolean isUidPrivileged(int uid) {
5542        uid = UserHandle.getAppId(uid);
5543        // reader
5544        synchronized (mPackages) {
5545            Object obj = mSettings.getUserIdLPr(uid);
5546            if (obj instanceof SharedUserSetting) {
5547                final SharedUserSetting sus = (SharedUserSetting) obj;
5548                final Iterator<PackageSetting> it = sus.packages.iterator();
5549                while (it.hasNext()) {
5550                    if (it.next().isPrivileged()) {
5551                        return true;
5552                    }
5553                }
5554            } else if (obj instanceof PackageSetting) {
5555                final PackageSetting ps = (PackageSetting) obj;
5556                return ps.isPrivileged();
5557            }
5558        }
5559        return false;
5560    }
5561
5562    @Override
5563    public String[] getAppOpPermissionPackages(String permissionName) {
5564        synchronized (mPackages) {
5565            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5566            if (pkgs == null) {
5567                return null;
5568            }
5569            return pkgs.toArray(new String[pkgs.size()]);
5570        }
5571    }
5572
5573    @Override
5574    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5575            int flags, int userId) {
5576        return resolveIntentInternal(
5577                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5578    }
5579
5580    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5581            int flags, int userId, boolean includeInstantApp) {
5582        try {
5583            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5584
5585            if (!sUserManager.exists(userId)) return null;
5586            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5587            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5588                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5589
5590            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5591            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5592                    flags, userId, includeInstantApp);
5593            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5594
5595            final ResolveInfo bestChoice =
5596                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5597            return bestChoice;
5598        } finally {
5599            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5600        }
5601    }
5602
5603    @Override
5604    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5605        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5606            throw new SecurityException(
5607                    "findPersistentPreferredActivity can only be run by the system");
5608        }
5609        if (!sUserManager.exists(userId)) {
5610            return null;
5611        }
5612        intent = updateIntentForResolve(intent);
5613        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5614        final int flags = updateFlagsForResolve(0, userId, intent, false);
5615        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5616                userId);
5617        synchronized (mPackages) {
5618            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5619                    userId);
5620        }
5621    }
5622
5623    @Override
5624    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5625            IntentFilter filter, int match, ComponentName activity) {
5626        final int userId = UserHandle.getCallingUserId();
5627        if (DEBUG_PREFERRED) {
5628            Log.v(TAG, "setLastChosenActivity intent=" + intent
5629                + " resolvedType=" + resolvedType
5630                + " flags=" + flags
5631                + " filter=" + filter
5632                + " match=" + match
5633                + " activity=" + activity);
5634            filter.dump(new PrintStreamPrinter(System.out), "    ");
5635        }
5636        intent.setComponent(null);
5637        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5638                userId);
5639        // Find any earlier preferred or last chosen entries and nuke them
5640        findPreferredActivity(intent, resolvedType,
5641                flags, query, 0, false, true, false, userId);
5642        // Add the new activity as the last chosen for this filter
5643        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5644                "Setting last chosen");
5645    }
5646
5647    @Override
5648    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5649        final int userId = UserHandle.getCallingUserId();
5650        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5651        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5652                userId);
5653        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5654                false, false, false, userId);
5655    }
5656
5657    /**
5658     * Returns whether or not instant apps have been disabled remotely.
5659     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5660     * held. Otherwise we run the risk of deadlock.
5661     */
5662    private boolean isEphemeralDisabled() {
5663        // ephemeral apps have been disabled across the board
5664        if (DISABLE_EPHEMERAL_APPS) {
5665            return true;
5666        }
5667        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5668        if (!mSystemReady) {
5669            return true;
5670        }
5671        // we can't get a content resolver until the system is ready; these checks must happen last
5672        final ContentResolver resolver = mContext.getContentResolver();
5673        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5674            return true;
5675        }
5676        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5677    }
5678
5679    private boolean isEphemeralAllowed(
5680            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5681            boolean skipPackageCheck) {
5682        final int callingUser = UserHandle.getCallingUserId();
5683        if (callingUser != UserHandle.USER_SYSTEM) {
5684            return false;
5685        }
5686        if (mInstantAppResolverConnection == null) {
5687            return false;
5688        }
5689        if (mInstantAppInstallerComponent == null) {
5690            return false;
5691        }
5692        if (intent.getComponent() != null) {
5693            return false;
5694        }
5695        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5696            return false;
5697        }
5698        if (!skipPackageCheck && intent.getPackage() != null) {
5699            return false;
5700        }
5701        final boolean isWebUri = hasWebURI(intent);
5702        if (!isWebUri || intent.getData().getHost() == null) {
5703            return false;
5704        }
5705        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5706        // Or if there's already an ephemeral app installed that handles the action
5707        synchronized (mPackages) {
5708            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5709            for (int n = 0; n < count; n++) {
5710                ResolveInfo info = resolvedActivities.get(n);
5711                String packageName = info.activityInfo.packageName;
5712                PackageSetting ps = mSettings.mPackages.get(packageName);
5713                if (ps != null) {
5714                    // Try to get the status from User settings first
5715                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5716                    int status = (int) (packedStatus >> 32);
5717                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5718                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5719                        if (DEBUG_EPHEMERAL) {
5720                            Slog.v(TAG, "DENY ephemeral apps;"
5721                                + " pkg: " + packageName + ", status: " + status);
5722                        }
5723                        return false;
5724                    }
5725                    if (ps.getInstantApp(userId)) {
5726                        return false;
5727                    }
5728                }
5729            }
5730        }
5731        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5732        return true;
5733    }
5734
5735    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5736            Intent origIntent, String resolvedType, String callingPackage,
5737            int userId) {
5738        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5739                new InstantAppRequest(responseObj, origIntent, resolvedType,
5740                        callingPackage, userId));
5741        mHandler.sendMessage(msg);
5742    }
5743
5744    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5745            int flags, List<ResolveInfo> query, int userId) {
5746        if (query != null) {
5747            final int N = query.size();
5748            if (N == 1) {
5749                return query.get(0);
5750            } else if (N > 1) {
5751                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5752                // If there is more than one activity with the same priority,
5753                // then let the user decide between them.
5754                ResolveInfo r0 = query.get(0);
5755                ResolveInfo r1 = query.get(1);
5756                if (DEBUG_INTENT_MATCHING || debug) {
5757                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5758                            + r1.activityInfo.name + "=" + r1.priority);
5759                }
5760                // If the first activity has a higher priority, or a different
5761                // default, then it is always desirable to pick it.
5762                if (r0.priority != r1.priority
5763                        || r0.preferredOrder != r1.preferredOrder
5764                        || r0.isDefault != r1.isDefault) {
5765                    return query.get(0);
5766                }
5767                // If we have saved a preference for a preferred activity for
5768                // this Intent, use that.
5769                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5770                        flags, query, r0.priority, true, false, debug, userId);
5771                if (ri != null) {
5772                    return ri;
5773                }
5774                // If we have an ephemeral app, use it
5775                for (int i = 0; i < N; i++) {
5776                    ri = query.get(i);
5777                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5778                        return ri;
5779                    }
5780                }
5781                ri = new ResolveInfo(mResolveInfo);
5782                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5783                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5784                // If all of the options come from the same package, show the application's
5785                // label and icon instead of the generic resolver's.
5786                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5787                // and then throw away the ResolveInfo itself, meaning that the caller loses
5788                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5789                // a fallback for this case; we only set the target package's resources on
5790                // the ResolveInfo, not the ActivityInfo.
5791                final String intentPackage = intent.getPackage();
5792                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5793                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5794                    ri.resolvePackageName = intentPackage;
5795                    if (userNeedsBadging(userId)) {
5796                        ri.noResourceId = true;
5797                    } else {
5798                        ri.icon = appi.icon;
5799                    }
5800                    ri.iconResourceId = appi.icon;
5801                    ri.labelRes = appi.labelRes;
5802                }
5803                ri.activityInfo.applicationInfo = new ApplicationInfo(
5804                        ri.activityInfo.applicationInfo);
5805                if (userId != 0) {
5806                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5807                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5808                }
5809                // Make sure that the resolver is displayable in car mode
5810                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5811                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5812                return ri;
5813            }
5814        }
5815        return null;
5816    }
5817
5818    /**
5819     * Return true if the given list is not empty and all of its contents have
5820     * an activityInfo with the given package name.
5821     */
5822    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5823        if (ArrayUtils.isEmpty(list)) {
5824            return false;
5825        }
5826        for (int i = 0, N = list.size(); i < N; i++) {
5827            final ResolveInfo ri = list.get(i);
5828            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5829            if (ai == null || !packageName.equals(ai.packageName)) {
5830                return false;
5831            }
5832        }
5833        return true;
5834    }
5835
5836    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5837            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5838        final int N = query.size();
5839        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5840                .get(userId);
5841        // Get the list of persistent preferred activities that handle the intent
5842        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5843        List<PersistentPreferredActivity> pprefs = ppir != null
5844                ? ppir.queryIntent(intent, resolvedType,
5845                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5846                        userId)
5847                : null;
5848        if (pprefs != null && pprefs.size() > 0) {
5849            final int M = pprefs.size();
5850            for (int i=0; i<M; i++) {
5851                final PersistentPreferredActivity ppa = pprefs.get(i);
5852                if (DEBUG_PREFERRED || debug) {
5853                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5854                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5855                            + "\n  component=" + ppa.mComponent);
5856                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5857                }
5858                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5859                        flags | MATCH_DISABLED_COMPONENTS, userId);
5860                if (DEBUG_PREFERRED || debug) {
5861                    Slog.v(TAG, "Found persistent preferred activity:");
5862                    if (ai != null) {
5863                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5864                    } else {
5865                        Slog.v(TAG, "  null");
5866                    }
5867                }
5868                if (ai == null) {
5869                    // This previously registered persistent preferred activity
5870                    // component is no longer known. Ignore it and do NOT remove it.
5871                    continue;
5872                }
5873                for (int j=0; j<N; j++) {
5874                    final ResolveInfo ri = query.get(j);
5875                    if (!ri.activityInfo.applicationInfo.packageName
5876                            .equals(ai.applicationInfo.packageName)) {
5877                        continue;
5878                    }
5879                    if (!ri.activityInfo.name.equals(ai.name)) {
5880                        continue;
5881                    }
5882                    //  Found a persistent preference that can handle the intent.
5883                    if (DEBUG_PREFERRED || debug) {
5884                        Slog.v(TAG, "Returning persistent preferred activity: " +
5885                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5886                    }
5887                    return ri;
5888                }
5889            }
5890        }
5891        return null;
5892    }
5893
5894    // TODO: handle preferred activities missing while user has amnesia
5895    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5896            List<ResolveInfo> query, int priority, boolean always,
5897            boolean removeMatches, boolean debug, int userId) {
5898        if (!sUserManager.exists(userId)) return null;
5899        flags = updateFlagsForResolve(flags, userId, intent, false);
5900        intent = updateIntentForResolve(intent);
5901        // writer
5902        synchronized (mPackages) {
5903            // Try to find a matching persistent preferred activity.
5904            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5905                    debug, userId);
5906
5907            // If a persistent preferred activity matched, use it.
5908            if (pri != null) {
5909                return pri;
5910            }
5911
5912            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5913            // Get the list of preferred activities that handle the intent
5914            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5915            List<PreferredActivity> prefs = pir != null
5916                    ? pir.queryIntent(intent, resolvedType,
5917                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5918                            userId)
5919                    : null;
5920            if (prefs != null && prefs.size() > 0) {
5921                boolean changed = false;
5922                try {
5923                    // First figure out how good the original match set is.
5924                    // We will only allow preferred activities that came
5925                    // from the same match quality.
5926                    int match = 0;
5927
5928                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5929
5930                    final int N = query.size();
5931                    for (int j=0; j<N; j++) {
5932                        final ResolveInfo ri = query.get(j);
5933                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5934                                + ": 0x" + Integer.toHexString(match));
5935                        if (ri.match > match) {
5936                            match = ri.match;
5937                        }
5938                    }
5939
5940                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5941                            + Integer.toHexString(match));
5942
5943                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5944                    final int M = prefs.size();
5945                    for (int i=0; i<M; i++) {
5946                        final PreferredActivity pa = prefs.get(i);
5947                        if (DEBUG_PREFERRED || debug) {
5948                            Slog.v(TAG, "Checking PreferredActivity ds="
5949                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5950                                    + "\n  component=" + pa.mPref.mComponent);
5951                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5952                        }
5953                        if (pa.mPref.mMatch != match) {
5954                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5955                                    + Integer.toHexString(pa.mPref.mMatch));
5956                            continue;
5957                        }
5958                        // If it's not an "always" type preferred activity and that's what we're
5959                        // looking for, skip it.
5960                        if (always && !pa.mPref.mAlways) {
5961                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5962                            continue;
5963                        }
5964                        final ActivityInfo ai = getActivityInfo(
5965                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5966                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5967                                userId);
5968                        if (DEBUG_PREFERRED || debug) {
5969                            Slog.v(TAG, "Found preferred activity:");
5970                            if (ai != null) {
5971                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5972                            } else {
5973                                Slog.v(TAG, "  null");
5974                            }
5975                        }
5976                        if (ai == null) {
5977                            // This previously registered preferred activity
5978                            // component is no longer known.  Most likely an update
5979                            // to the app was installed and in the new version this
5980                            // component no longer exists.  Clean it up by removing
5981                            // it from the preferred activities list, and skip it.
5982                            Slog.w(TAG, "Removing dangling preferred activity: "
5983                                    + pa.mPref.mComponent);
5984                            pir.removeFilter(pa);
5985                            changed = true;
5986                            continue;
5987                        }
5988                        for (int j=0; j<N; j++) {
5989                            final ResolveInfo ri = query.get(j);
5990                            if (!ri.activityInfo.applicationInfo.packageName
5991                                    .equals(ai.applicationInfo.packageName)) {
5992                                continue;
5993                            }
5994                            if (!ri.activityInfo.name.equals(ai.name)) {
5995                                continue;
5996                            }
5997
5998                            if (removeMatches) {
5999                                pir.removeFilter(pa);
6000                                changed = true;
6001                                if (DEBUG_PREFERRED) {
6002                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6003                                }
6004                                break;
6005                            }
6006
6007                            // Okay we found a previously set preferred or last chosen app.
6008                            // If the result set is different from when this
6009                            // was created, we need to clear it and re-ask the
6010                            // user their preference, if we're looking for an "always" type entry.
6011                            if (always && !pa.mPref.sameSet(query)) {
6012                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6013                                        + intent + " type " + resolvedType);
6014                                if (DEBUG_PREFERRED) {
6015                                    Slog.v(TAG, "Removing preferred activity since set changed "
6016                                            + pa.mPref.mComponent);
6017                                }
6018                                pir.removeFilter(pa);
6019                                // Re-add the filter as a "last chosen" entry (!always)
6020                                PreferredActivity lastChosen = new PreferredActivity(
6021                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6022                                pir.addFilter(lastChosen);
6023                                changed = true;
6024                                return null;
6025                            }
6026
6027                            // Yay! Either the set matched or we're looking for the last chosen
6028                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6029                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6030                            return ri;
6031                        }
6032                    }
6033                } finally {
6034                    if (changed) {
6035                        if (DEBUG_PREFERRED) {
6036                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6037                        }
6038                        scheduleWritePackageRestrictionsLocked(userId);
6039                    }
6040                }
6041            }
6042        }
6043        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6044        return null;
6045    }
6046
6047    /*
6048     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6049     */
6050    @Override
6051    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6052            int targetUserId) {
6053        mContext.enforceCallingOrSelfPermission(
6054                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6055        List<CrossProfileIntentFilter> matches =
6056                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6057        if (matches != null) {
6058            int size = matches.size();
6059            for (int i = 0; i < size; i++) {
6060                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6061            }
6062        }
6063        if (hasWebURI(intent)) {
6064            // cross-profile app linking works only towards the parent.
6065            final UserInfo parent = getProfileParent(sourceUserId);
6066            synchronized(mPackages) {
6067                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6068                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6069                        intent, resolvedType, flags, sourceUserId, parent.id);
6070                return xpDomainInfo != null;
6071            }
6072        }
6073        return false;
6074    }
6075
6076    private UserInfo getProfileParent(int userId) {
6077        final long identity = Binder.clearCallingIdentity();
6078        try {
6079            return sUserManager.getProfileParent(userId);
6080        } finally {
6081            Binder.restoreCallingIdentity(identity);
6082        }
6083    }
6084
6085    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6086            String resolvedType, int userId) {
6087        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6088        if (resolver != null) {
6089            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6090        }
6091        return null;
6092    }
6093
6094    @Override
6095    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6096            String resolvedType, int flags, int userId) {
6097        try {
6098            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6099
6100            return new ParceledListSlice<>(
6101                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6102        } finally {
6103            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6104        }
6105    }
6106
6107    /**
6108     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6109     * instant, returns {@code null}.
6110     */
6111    private String getInstantAppPackageName(int callingUid) {
6112        final int appId = UserHandle.getAppId(callingUid);
6113        synchronized (mPackages) {
6114            final Object obj = mSettings.getUserIdLPr(appId);
6115            if (obj instanceof PackageSetting) {
6116                final PackageSetting ps = (PackageSetting) obj;
6117                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6118                return isInstantApp ? ps.pkg.packageName : null;
6119            }
6120        }
6121        return null;
6122    }
6123
6124    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6125            String resolvedType, int flags, int userId) {
6126        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6127    }
6128
6129    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6130            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6131        if (!sUserManager.exists(userId)) return Collections.emptyList();
6132        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6133        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6134        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6135                false /* requireFullPermission */, false /* checkShell */,
6136                "query intent activities");
6137        ComponentName comp = intent.getComponent();
6138        if (comp == null) {
6139            if (intent.getSelector() != null) {
6140                intent = intent.getSelector();
6141                comp = intent.getComponent();
6142            }
6143        }
6144
6145        if (comp != null) {
6146            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6147            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6148            if (ai != null) {
6149                // When specifying an explicit component, we prevent the activity from being
6150                // used when either 1) the calling package is normal and the activity is within
6151                // an ephemeral application or 2) the calling package is ephemeral and the
6152                // activity is not visible to ephemeral applications.
6153                final boolean matchInstantApp =
6154                        (flags & PackageManager.MATCH_INSTANT) != 0;
6155                final boolean matchVisibleToInstantAppOnly =
6156                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6157                final boolean isCallerInstantApp =
6158                        instantAppPkgName != null;
6159                final boolean isTargetSameInstantApp =
6160                        comp.getPackageName().equals(instantAppPkgName);
6161                final boolean isTargetInstantApp =
6162                        (ai.applicationInfo.privateFlags
6163                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6164                final boolean isTargetHiddenFromInstantApp =
6165                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6166                final boolean blockResolution =
6167                        !isTargetSameInstantApp
6168                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6169                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6170                                        && isTargetHiddenFromInstantApp));
6171                if (!blockResolution) {
6172                    final ResolveInfo ri = new ResolveInfo();
6173                    ri.activityInfo = ai;
6174                    list.add(ri);
6175                }
6176            }
6177            return applyPostResolutionFilter(list, instantAppPkgName);
6178        }
6179
6180        // reader
6181        boolean sortResult = false;
6182        boolean addEphemeral = false;
6183        List<ResolveInfo> result;
6184        final String pkgName = intent.getPackage();
6185        final boolean ephemeralDisabled = isEphemeralDisabled();
6186        synchronized (mPackages) {
6187            if (pkgName == null) {
6188                List<CrossProfileIntentFilter> matchingFilters =
6189                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6190                // Check for results that need to skip the current profile.
6191                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6192                        resolvedType, flags, userId);
6193                if (xpResolveInfo != null) {
6194                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6195                    xpResult.add(xpResolveInfo);
6196                    return applyPostResolutionFilter(
6197                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6198                }
6199
6200                // Check for results in the current profile.
6201                result = filterIfNotSystemUser(mActivities.queryIntent(
6202                        intent, resolvedType, flags, userId), userId);
6203                addEphemeral = !ephemeralDisabled
6204                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6205
6206                // Check for cross profile results.
6207                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6208                xpResolveInfo = queryCrossProfileIntents(
6209                        matchingFilters, intent, resolvedType, flags, userId,
6210                        hasNonNegativePriorityResult);
6211                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6212                    boolean isVisibleToUser = filterIfNotSystemUser(
6213                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6214                    if (isVisibleToUser) {
6215                        result.add(xpResolveInfo);
6216                        sortResult = true;
6217                    }
6218                }
6219                if (hasWebURI(intent)) {
6220                    CrossProfileDomainInfo xpDomainInfo = null;
6221                    final UserInfo parent = getProfileParent(userId);
6222                    if (parent != null) {
6223                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6224                                flags, userId, parent.id);
6225                    }
6226                    if (xpDomainInfo != null) {
6227                        if (xpResolveInfo != null) {
6228                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6229                            // in the result.
6230                            result.remove(xpResolveInfo);
6231                        }
6232                        if (result.size() == 0 && !addEphemeral) {
6233                            // No result in current profile, but found candidate in parent user.
6234                            // And we are not going to add emphemeral app, so we can return the
6235                            // result straight away.
6236                            result.add(xpDomainInfo.resolveInfo);
6237                            return applyPostResolutionFilter(result, instantAppPkgName);
6238                        }
6239                    } else if (result.size() <= 1 && !addEphemeral) {
6240                        // No result in parent user and <= 1 result in current profile, and we
6241                        // are not going to add emphemeral app, so we can return the result without
6242                        // further processing.
6243                        return applyPostResolutionFilter(result, instantAppPkgName);
6244                    }
6245                    // We have more than one candidate (combining results from current and parent
6246                    // profile), so we need filtering and sorting.
6247                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6248                            intent, flags, result, xpDomainInfo, userId);
6249                    sortResult = true;
6250                }
6251            } else {
6252                final PackageParser.Package pkg = mPackages.get(pkgName);
6253                if (pkg != null) {
6254                    result = applyPostResolutionFilter(filterIfNotSystemUser(
6255                            mActivities.queryIntentForPackage(
6256                                    intent, resolvedType, flags, pkg.activities, userId),
6257                            userId), instantAppPkgName);
6258                } else {
6259                    // the caller wants to resolve for a particular package; however, there
6260                    // were no installed results, so, try to find an ephemeral result
6261                    addEphemeral =  !ephemeralDisabled
6262                            && isEphemeralAllowed(
6263                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6264                    result = new ArrayList<ResolveInfo>();
6265                }
6266            }
6267        }
6268        if (addEphemeral) {
6269            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6270            final InstantAppRequest requestObject = new InstantAppRequest(
6271                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6272                    null /*callingPackage*/, userId);
6273            final AuxiliaryResolveInfo auxiliaryResponse =
6274                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6275                            mContext, mInstantAppResolverConnection, requestObject);
6276            if (auxiliaryResponse != null) {
6277                if (DEBUG_EPHEMERAL) {
6278                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6279                }
6280                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6281                ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity);
6282                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6283                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6284                // make sure this resolver is the default
6285                ephemeralInstaller.isDefault = true;
6286                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6287                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6288                // add a non-generic filter
6289                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6290                ephemeralInstaller.filter.addDataPath(
6291                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6292                ephemeralInstaller.instantAppAvailable = true;
6293                result.add(ephemeralInstaller);
6294            }
6295            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6296        }
6297        if (sortResult) {
6298            Collections.sort(result, mResolvePrioritySorter);
6299        }
6300        return applyPostResolutionFilter(result, instantAppPkgName);
6301    }
6302
6303    private static class CrossProfileDomainInfo {
6304        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6305        ResolveInfo resolveInfo;
6306        /* Best domain verification status of the activities found in the other profile */
6307        int bestDomainVerificationStatus;
6308    }
6309
6310    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6311            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6312        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6313                sourceUserId)) {
6314            return null;
6315        }
6316        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6317                resolvedType, flags, parentUserId);
6318
6319        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6320            return null;
6321        }
6322        CrossProfileDomainInfo result = null;
6323        int size = resultTargetUser.size();
6324        for (int i = 0; i < size; i++) {
6325            ResolveInfo riTargetUser = resultTargetUser.get(i);
6326            // Intent filter verification is only for filters that specify a host. So don't return
6327            // those that handle all web uris.
6328            if (riTargetUser.handleAllWebDataURI) {
6329                continue;
6330            }
6331            String packageName = riTargetUser.activityInfo.packageName;
6332            PackageSetting ps = mSettings.mPackages.get(packageName);
6333            if (ps == null) {
6334                continue;
6335            }
6336            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6337            int status = (int)(verificationState >> 32);
6338            if (result == null) {
6339                result = new CrossProfileDomainInfo();
6340                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6341                        sourceUserId, parentUserId);
6342                result.bestDomainVerificationStatus = status;
6343            } else {
6344                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6345                        result.bestDomainVerificationStatus);
6346            }
6347        }
6348        // Don't consider matches with status NEVER across profiles.
6349        if (result != null && result.bestDomainVerificationStatus
6350                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6351            return null;
6352        }
6353        return result;
6354    }
6355
6356    /**
6357     * Verification statuses are ordered from the worse to the best, except for
6358     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6359     */
6360    private int bestDomainVerificationStatus(int status1, int status2) {
6361        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6362            return status2;
6363        }
6364        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6365            return status1;
6366        }
6367        return (int) MathUtils.max(status1, status2);
6368    }
6369
6370    private boolean isUserEnabled(int userId) {
6371        long callingId = Binder.clearCallingIdentity();
6372        try {
6373            UserInfo userInfo = sUserManager.getUserInfo(userId);
6374            return userInfo != null && userInfo.isEnabled();
6375        } finally {
6376            Binder.restoreCallingIdentity(callingId);
6377        }
6378    }
6379
6380    /**
6381     * Filter out activities with systemUserOnly flag set, when current user is not System.
6382     *
6383     * @return filtered list
6384     */
6385    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6386        if (userId == UserHandle.USER_SYSTEM) {
6387            return resolveInfos;
6388        }
6389        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6390            ResolveInfo info = resolveInfos.get(i);
6391            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6392                resolveInfos.remove(i);
6393            }
6394        }
6395        return resolveInfos;
6396    }
6397
6398    /**
6399     * Filters out ephemeral activities.
6400     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6401     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6402     *
6403     * @param resolveInfos The pre-filtered list of resolved activities
6404     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6405     *          is performed.
6406     * @return A filtered list of resolved activities.
6407     */
6408    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6409            String ephemeralPkgName) {
6410        // TODO: When adding on-demand split support for non-instant apps, remove this check
6411        // and always apply post filtering
6412        if (ephemeralPkgName == null) {
6413            return resolveInfos;
6414        }
6415        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6416            final ResolveInfo info = resolveInfos.get(i);
6417            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6418            // allow activities that are defined in the provided package
6419            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6420                if (info.activityInfo.splitName != null
6421                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6422                                info.activityInfo.splitName)) {
6423                    // requested activity is defined in a split that hasn't been installed yet.
6424                    // add the installer to the resolve list
6425                    if (DEBUG_EPHEMERAL) {
6426                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6427                    }
6428                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6429                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6430                            info.activityInfo.packageName, info.activityInfo.splitName,
6431                            info.activityInfo.applicationInfo.versionCode);
6432                    // make sure this resolver is the default
6433                    installerInfo.isDefault = true;
6434                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6435                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6436                    // add a non-generic filter
6437                    installerInfo.filter = new IntentFilter();
6438                    // load resources from the correct package
6439                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6440                    resolveInfos.set(i, installerInfo);
6441                }
6442                continue;
6443            }
6444            // allow activities that have been explicitly exposed to ephemeral apps
6445            if (!isEphemeralApp
6446                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6447                continue;
6448            }
6449            resolveInfos.remove(i);
6450        }
6451        return resolveInfos;
6452    }
6453
6454    /**
6455     * @param resolveInfos list of resolve infos in descending priority order
6456     * @return if the list contains a resolve info with non-negative priority
6457     */
6458    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6459        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6460    }
6461
6462    private static boolean hasWebURI(Intent intent) {
6463        if (intent.getData() == null) {
6464            return false;
6465        }
6466        final String scheme = intent.getScheme();
6467        if (TextUtils.isEmpty(scheme)) {
6468            return false;
6469        }
6470        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6471    }
6472
6473    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6474            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6475            int userId) {
6476        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6477
6478        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6479            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6480                    candidates.size());
6481        }
6482
6483        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6484        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6485        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6486        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6487        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6488        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6489
6490        synchronized (mPackages) {
6491            final int count = candidates.size();
6492            // First, try to use linked apps. Partition the candidates into four lists:
6493            // one for the final results, one for the "do not use ever", one for "undefined status"
6494            // and finally one for "browser app type".
6495            for (int n=0; n<count; n++) {
6496                ResolveInfo info = candidates.get(n);
6497                String packageName = info.activityInfo.packageName;
6498                PackageSetting ps = mSettings.mPackages.get(packageName);
6499                if (ps != null) {
6500                    // Add to the special match all list (Browser use case)
6501                    if (info.handleAllWebDataURI) {
6502                        matchAllList.add(info);
6503                        continue;
6504                    }
6505                    // Try to get the status from User settings first
6506                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6507                    int status = (int)(packedStatus >> 32);
6508                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6509                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6510                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6511                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6512                                    + " : linkgen=" + linkGeneration);
6513                        }
6514                        // Use link-enabled generation as preferredOrder, i.e.
6515                        // prefer newly-enabled over earlier-enabled.
6516                        info.preferredOrder = linkGeneration;
6517                        alwaysList.add(info);
6518                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6519                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6520                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6521                        }
6522                        neverList.add(info);
6523                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6524                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6525                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6526                        }
6527                        alwaysAskList.add(info);
6528                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6529                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6530                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6531                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6532                        }
6533                        undefinedList.add(info);
6534                    }
6535                }
6536            }
6537
6538            // We'll want to include browser possibilities in a few cases
6539            boolean includeBrowser = false;
6540
6541            // First try to add the "always" resolution(s) for the current user, if any
6542            if (alwaysList.size() > 0) {
6543                result.addAll(alwaysList);
6544            } else {
6545                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6546                result.addAll(undefinedList);
6547                // Maybe add one for the other profile.
6548                if (xpDomainInfo != null && (
6549                        xpDomainInfo.bestDomainVerificationStatus
6550                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6551                    result.add(xpDomainInfo.resolveInfo);
6552                }
6553                includeBrowser = true;
6554            }
6555
6556            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6557            // If there were 'always' entries their preferred order has been set, so we also
6558            // back that off to make the alternatives equivalent
6559            if (alwaysAskList.size() > 0) {
6560                for (ResolveInfo i : result) {
6561                    i.preferredOrder = 0;
6562                }
6563                result.addAll(alwaysAskList);
6564                includeBrowser = true;
6565            }
6566
6567            if (includeBrowser) {
6568                // Also add browsers (all of them or only the default one)
6569                if (DEBUG_DOMAIN_VERIFICATION) {
6570                    Slog.v(TAG, "   ...including browsers in candidate set");
6571                }
6572                if ((matchFlags & MATCH_ALL) != 0) {
6573                    result.addAll(matchAllList);
6574                } else {
6575                    // Browser/generic handling case.  If there's a default browser, go straight
6576                    // to that (but only if there is no other higher-priority match).
6577                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6578                    int maxMatchPrio = 0;
6579                    ResolveInfo defaultBrowserMatch = null;
6580                    final int numCandidates = matchAllList.size();
6581                    for (int n = 0; n < numCandidates; n++) {
6582                        ResolveInfo info = matchAllList.get(n);
6583                        // track the highest overall match priority...
6584                        if (info.priority > maxMatchPrio) {
6585                            maxMatchPrio = info.priority;
6586                        }
6587                        // ...and the highest-priority default browser match
6588                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6589                            if (defaultBrowserMatch == null
6590                                    || (defaultBrowserMatch.priority < info.priority)) {
6591                                if (debug) {
6592                                    Slog.v(TAG, "Considering default browser match " + info);
6593                                }
6594                                defaultBrowserMatch = info;
6595                            }
6596                        }
6597                    }
6598                    if (defaultBrowserMatch != null
6599                            && defaultBrowserMatch.priority >= maxMatchPrio
6600                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6601                    {
6602                        if (debug) {
6603                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6604                        }
6605                        result.add(defaultBrowserMatch);
6606                    } else {
6607                        result.addAll(matchAllList);
6608                    }
6609                }
6610
6611                // If there is nothing selected, add all candidates and remove the ones that the user
6612                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6613                if (result.size() == 0) {
6614                    result.addAll(candidates);
6615                    result.removeAll(neverList);
6616                }
6617            }
6618        }
6619        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6620            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6621                    result.size());
6622            for (ResolveInfo info : result) {
6623                Slog.v(TAG, "  + " + info.activityInfo);
6624            }
6625        }
6626        return result;
6627    }
6628
6629    // Returns a packed value as a long:
6630    //
6631    // high 'int'-sized word: link status: undefined/ask/never/always.
6632    // low 'int'-sized word: relative priority among 'always' results.
6633    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6634        long result = ps.getDomainVerificationStatusForUser(userId);
6635        // if none available, get the master status
6636        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6637            if (ps.getIntentFilterVerificationInfo() != null) {
6638                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6639            }
6640        }
6641        return result;
6642    }
6643
6644    private ResolveInfo querySkipCurrentProfileIntents(
6645            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6646            int flags, int sourceUserId) {
6647        if (matchingFilters != null) {
6648            int size = matchingFilters.size();
6649            for (int i = 0; i < size; i ++) {
6650                CrossProfileIntentFilter filter = matchingFilters.get(i);
6651                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6652                    // Checking if there are activities in the target user that can handle the
6653                    // intent.
6654                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6655                            resolvedType, flags, sourceUserId);
6656                    if (resolveInfo != null) {
6657                        return resolveInfo;
6658                    }
6659                }
6660            }
6661        }
6662        return null;
6663    }
6664
6665    // Return matching ResolveInfo in target user if any.
6666    private ResolveInfo queryCrossProfileIntents(
6667            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6668            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6669        if (matchingFilters != null) {
6670            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6671            // match the same intent. For performance reasons, it is better not to
6672            // run queryIntent twice for the same userId
6673            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6674            int size = matchingFilters.size();
6675            for (int i = 0; i < size; i++) {
6676                CrossProfileIntentFilter filter = matchingFilters.get(i);
6677                int targetUserId = filter.getTargetUserId();
6678                boolean skipCurrentProfile =
6679                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6680                boolean skipCurrentProfileIfNoMatchFound =
6681                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6682                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6683                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6684                    // Checking if there are activities in the target user that can handle the
6685                    // intent.
6686                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6687                            resolvedType, flags, sourceUserId);
6688                    if (resolveInfo != null) return resolveInfo;
6689                    alreadyTriedUserIds.put(targetUserId, true);
6690                }
6691            }
6692        }
6693        return null;
6694    }
6695
6696    /**
6697     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6698     * will forward the intent to the filter's target user.
6699     * Otherwise, returns null.
6700     */
6701    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6702            String resolvedType, int flags, int sourceUserId) {
6703        int targetUserId = filter.getTargetUserId();
6704        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6705                resolvedType, flags, targetUserId);
6706        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6707            // If all the matches in the target profile are suspended, return null.
6708            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6709                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6710                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6711                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6712                            targetUserId);
6713                }
6714            }
6715        }
6716        return null;
6717    }
6718
6719    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6720            int sourceUserId, int targetUserId) {
6721        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6722        long ident = Binder.clearCallingIdentity();
6723        boolean targetIsProfile;
6724        try {
6725            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6726        } finally {
6727            Binder.restoreCallingIdentity(ident);
6728        }
6729        String className;
6730        if (targetIsProfile) {
6731            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6732        } else {
6733            className = FORWARD_INTENT_TO_PARENT;
6734        }
6735        ComponentName forwardingActivityComponentName = new ComponentName(
6736                mAndroidApplication.packageName, className);
6737        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6738                sourceUserId);
6739        if (!targetIsProfile) {
6740            forwardingActivityInfo.showUserIcon = targetUserId;
6741            forwardingResolveInfo.noResourceId = true;
6742        }
6743        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6744        forwardingResolveInfo.priority = 0;
6745        forwardingResolveInfo.preferredOrder = 0;
6746        forwardingResolveInfo.match = 0;
6747        forwardingResolveInfo.isDefault = true;
6748        forwardingResolveInfo.filter = filter;
6749        forwardingResolveInfo.targetUserId = targetUserId;
6750        return forwardingResolveInfo;
6751    }
6752
6753    @Override
6754    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6755            Intent[] specifics, String[] specificTypes, Intent intent,
6756            String resolvedType, int flags, int userId) {
6757        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6758                specificTypes, intent, resolvedType, flags, userId));
6759    }
6760
6761    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6762            Intent[] specifics, String[] specificTypes, Intent intent,
6763            String resolvedType, int flags, int userId) {
6764        if (!sUserManager.exists(userId)) return Collections.emptyList();
6765        flags = updateFlagsForResolve(flags, userId, intent, false);
6766        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6767                false /* requireFullPermission */, false /* checkShell */,
6768                "query intent activity options");
6769        final String resultsAction = intent.getAction();
6770
6771        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6772                | PackageManager.GET_RESOLVED_FILTER, userId);
6773
6774        if (DEBUG_INTENT_MATCHING) {
6775            Log.v(TAG, "Query " + intent + ": " + results);
6776        }
6777
6778        int specificsPos = 0;
6779        int N;
6780
6781        // todo: note that the algorithm used here is O(N^2).  This
6782        // isn't a problem in our current environment, but if we start running
6783        // into situations where we have more than 5 or 10 matches then this
6784        // should probably be changed to something smarter...
6785
6786        // First we go through and resolve each of the specific items
6787        // that were supplied, taking care of removing any corresponding
6788        // duplicate items in the generic resolve list.
6789        if (specifics != null) {
6790            for (int i=0; i<specifics.length; i++) {
6791                final Intent sintent = specifics[i];
6792                if (sintent == null) {
6793                    continue;
6794                }
6795
6796                if (DEBUG_INTENT_MATCHING) {
6797                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6798                }
6799
6800                String action = sintent.getAction();
6801                if (resultsAction != null && resultsAction.equals(action)) {
6802                    // If this action was explicitly requested, then don't
6803                    // remove things that have it.
6804                    action = null;
6805                }
6806
6807                ResolveInfo ri = null;
6808                ActivityInfo ai = null;
6809
6810                ComponentName comp = sintent.getComponent();
6811                if (comp == null) {
6812                    ri = resolveIntent(
6813                        sintent,
6814                        specificTypes != null ? specificTypes[i] : null,
6815                            flags, userId);
6816                    if (ri == null) {
6817                        continue;
6818                    }
6819                    if (ri == mResolveInfo) {
6820                        // ACK!  Must do something better with this.
6821                    }
6822                    ai = ri.activityInfo;
6823                    comp = new ComponentName(ai.applicationInfo.packageName,
6824                            ai.name);
6825                } else {
6826                    ai = getActivityInfo(comp, flags, userId);
6827                    if (ai == null) {
6828                        continue;
6829                    }
6830                }
6831
6832                // Look for any generic query activities that are duplicates
6833                // of this specific one, and remove them from the results.
6834                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6835                N = results.size();
6836                int j;
6837                for (j=specificsPos; j<N; j++) {
6838                    ResolveInfo sri = results.get(j);
6839                    if ((sri.activityInfo.name.equals(comp.getClassName())
6840                            && sri.activityInfo.applicationInfo.packageName.equals(
6841                                    comp.getPackageName()))
6842                        || (action != null && sri.filter.matchAction(action))) {
6843                        results.remove(j);
6844                        if (DEBUG_INTENT_MATCHING) Log.v(
6845                            TAG, "Removing duplicate item from " + j
6846                            + " due to specific " + specificsPos);
6847                        if (ri == null) {
6848                            ri = sri;
6849                        }
6850                        j--;
6851                        N--;
6852                    }
6853                }
6854
6855                // Add this specific item to its proper place.
6856                if (ri == null) {
6857                    ri = new ResolveInfo();
6858                    ri.activityInfo = ai;
6859                }
6860                results.add(specificsPos, ri);
6861                ri.specificIndex = i;
6862                specificsPos++;
6863            }
6864        }
6865
6866        // Now we go through the remaining generic results and remove any
6867        // duplicate actions that are found here.
6868        N = results.size();
6869        for (int i=specificsPos; i<N-1; i++) {
6870            final ResolveInfo rii = results.get(i);
6871            if (rii.filter == null) {
6872                continue;
6873            }
6874
6875            // Iterate over all of the actions of this result's intent
6876            // filter...  typically this should be just one.
6877            final Iterator<String> it = rii.filter.actionsIterator();
6878            if (it == null) {
6879                continue;
6880            }
6881            while (it.hasNext()) {
6882                final String action = it.next();
6883                if (resultsAction != null && resultsAction.equals(action)) {
6884                    // If this action was explicitly requested, then don't
6885                    // remove things that have it.
6886                    continue;
6887                }
6888                for (int j=i+1; j<N; j++) {
6889                    final ResolveInfo rij = results.get(j);
6890                    if (rij.filter != null && rij.filter.hasAction(action)) {
6891                        results.remove(j);
6892                        if (DEBUG_INTENT_MATCHING) Log.v(
6893                            TAG, "Removing duplicate item from " + j
6894                            + " due to action " + action + " at " + i);
6895                        j--;
6896                        N--;
6897                    }
6898                }
6899            }
6900
6901            // If the caller didn't request filter information, drop it now
6902            // so we don't have to marshall/unmarshall it.
6903            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6904                rii.filter = null;
6905            }
6906        }
6907
6908        // Filter out the caller activity if so requested.
6909        if (caller != null) {
6910            N = results.size();
6911            for (int i=0; i<N; i++) {
6912                ActivityInfo ainfo = results.get(i).activityInfo;
6913                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6914                        && caller.getClassName().equals(ainfo.name)) {
6915                    results.remove(i);
6916                    break;
6917                }
6918            }
6919        }
6920
6921        // If the caller didn't request filter information,
6922        // drop them now so we don't have to
6923        // marshall/unmarshall it.
6924        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6925            N = results.size();
6926            for (int i=0; i<N; i++) {
6927                results.get(i).filter = null;
6928            }
6929        }
6930
6931        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6932        return results;
6933    }
6934
6935    @Override
6936    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6937            String resolvedType, int flags, int userId) {
6938        return new ParceledListSlice<>(
6939                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6940    }
6941
6942    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6943            String resolvedType, int flags, int userId) {
6944        if (!sUserManager.exists(userId)) return Collections.emptyList();
6945        flags = updateFlagsForResolve(flags, userId, intent, false);
6946        ComponentName comp = intent.getComponent();
6947        if (comp == null) {
6948            if (intent.getSelector() != null) {
6949                intent = intent.getSelector();
6950                comp = intent.getComponent();
6951            }
6952        }
6953        if (comp != null) {
6954            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6955            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6956            if (ai != null) {
6957                ResolveInfo ri = new ResolveInfo();
6958                ri.activityInfo = ai;
6959                list.add(ri);
6960            }
6961            return list;
6962        }
6963
6964        // reader
6965        synchronized (mPackages) {
6966            String pkgName = intent.getPackage();
6967            if (pkgName == null) {
6968                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6969            }
6970            final PackageParser.Package pkg = mPackages.get(pkgName);
6971            if (pkg != null) {
6972                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6973                        userId);
6974            }
6975            return Collections.emptyList();
6976        }
6977    }
6978
6979    @Override
6980    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6981        if (!sUserManager.exists(userId)) return null;
6982        flags = updateFlagsForResolve(flags, userId, intent, false);
6983        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6984        if (query != null) {
6985            if (query.size() >= 1) {
6986                // If there is more than one service with the same priority,
6987                // just arbitrarily pick the first one.
6988                return query.get(0);
6989            }
6990        }
6991        return null;
6992    }
6993
6994    @Override
6995    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6996            String resolvedType, int flags, int userId) {
6997        return new ParceledListSlice<>(
6998                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6999    }
7000
7001    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7002            String resolvedType, int flags, int userId) {
7003        if (!sUserManager.exists(userId)) return Collections.emptyList();
7004        flags = updateFlagsForResolve(flags, userId, intent, false);
7005        ComponentName comp = intent.getComponent();
7006        if (comp == null) {
7007            if (intent.getSelector() != null) {
7008                intent = intent.getSelector();
7009                comp = intent.getComponent();
7010            }
7011        }
7012        if (comp != null) {
7013            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7014            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7015            if (si != null) {
7016                final ResolveInfo ri = new ResolveInfo();
7017                ri.serviceInfo = si;
7018                list.add(ri);
7019            }
7020            return list;
7021        }
7022
7023        // reader
7024        synchronized (mPackages) {
7025            String pkgName = intent.getPackage();
7026            if (pkgName == null) {
7027                return mServices.queryIntent(intent, resolvedType, flags, userId);
7028            }
7029            final PackageParser.Package pkg = mPackages.get(pkgName);
7030            if (pkg != null) {
7031                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7032                        userId);
7033            }
7034            return Collections.emptyList();
7035        }
7036    }
7037
7038    @Override
7039    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7040            String resolvedType, int flags, int userId) {
7041        return new ParceledListSlice<>(
7042                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7043    }
7044
7045    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7046            Intent intent, String resolvedType, int flags, int userId) {
7047        if (!sUserManager.exists(userId)) return Collections.emptyList();
7048        flags = updateFlagsForResolve(flags, userId, intent, false);
7049        ComponentName comp = intent.getComponent();
7050        if (comp == null) {
7051            if (intent.getSelector() != null) {
7052                intent = intent.getSelector();
7053                comp = intent.getComponent();
7054            }
7055        }
7056        if (comp != null) {
7057            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7058            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7059            if (pi != null) {
7060                final ResolveInfo ri = new ResolveInfo();
7061                ri.providerInfo = pi;
7062                list.add(ri);
7063            }
7064            return list;
7065        }
7066
7067        // reader
7068        synchronized (mPackages) {
7069            String pkgName = intent.getPackage();
7070            if (pkgName == null) {
7071                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7072            }
7073            final PackageParser.Package pkg = mPackages.get(pkgName);
7074            if (pkg != null) {
7075                return mProviders.queryIntentForPackage(
7076                        intent, resolvedType, flags, pkg.providers, userId);
7077            }
7078            return Collections.emptyList();
7079        }
7080    }
7081
7082    @Override
7083    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7084        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7085        flags = updateFlagsForPackage(flags, userId, null);
7086        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7087        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7088                true /* requireFullPermission */, false /* checkShell */,
7089                "get installed packages");
7090
7091        // writer
7092        synchronized (mPackages) {
7093            ArrayList<PackageInfo> list;
7094            if (listUninstalled) {
7095                list = new ArrayList<>(mSettings.mPackages.size());
7096                for (PackageSetting ps : mSettings.mPackages.values()) {
7097                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7098                        continue;
7099                    }
7100                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7101                    if (pi != null) {
7102                        list.add(pi);
7103                    }
7104                }
7105            } else {
7106                list = new ArrayList<>(mPackages.size());
7107                for (PackageParser.Package p : mPackages.values()) {
7108                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7109                            Binder.getCallingUid(), userId)) {
7110                        continue;
7111                    }
7112                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7113                            p.mExtras, flags, userId);
7114                    if (pi != null) {
7115                        list.add(pi);
7116                    }
7117                }
7118            }
7119
7120            return new ParceledListSlice<>(list);
7121        }
7122    }
7123
7124    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7125            String[] permissions, boolean[] tmp, int flags, int userId) {
7126        int numMatch = 0;
7127        final PermissionsState permissionsState = ps.getPermissionsState();
7128        for (int i=0; i<permissions.length; i++) {
7129            final String permission = permissions[i];
7130            if (permissionsState.hasPermission(permission, userId)) {
7131                tmp[i] = true;
7132                numMatch++;
7133            } else {
7134                tmp[i] = false;
7135            }
7136        }
7137        if (numMatch == 0) {
7138            return;
7139        }
7140        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7141
7142        // The above might return null in cases of uninstalled apps or install-state
7143        // skew across users/profiles.
7144        if (pi != null) {
7145            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7146                if (numMatch == permissions.length) {
7147                    pi.requestedPermissions = permissions;
7148                } else {
7149                    pi.requestedPermissions = new String[numMatch];
7150                    numMatch = 0;
7151                    for (int i=0; i<permissions.length; i++) {
7152                        if (tmp[i]) {
7153                            pi.requestedPermissions[numMatch] = permissions[i];
7154                            numMatch++;
7155                        }
7156                    }
7157                }
7158            }
7159            list.add(pi);
7160        }
7161    }
7162
7163    @Override
7164    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7165            String[] permissions, int flags, int userId) {
7166        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7167        flags = updateFlagsForPackage(flags, userId, permissions);
7168        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7169                true /* requireFullPermission */, false /* checkShell */,
7170                "get packages holding permissions");
7171        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7172
7173        // writer
7174        synchronized (mPackages) {
7175            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7176            boolean[] tmpBools = new boolean[permissions.length];
7177            if (listUninstalled) {
7178                for (PackageSetting ps : mSettings.mPackages.values()) {
7179                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7180                            userId);
7181                }
7182            } else {
7183                for (PackageParser.Package pkg : mPackages.values()) {
7184                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7185                    if (ps != null) {
7186                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7187                                userId);
7188                    }
7189                }
7190            }
7191
7192            return new ParceledListSlice<PackageInfo>(list);
7193        }
7194    }
7195
7196    @Override
7197    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7198        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7199        flags = updateFlagsForApplication(flags, userId, null);
7200        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7201
7202        // writer
7203        synchronized (mPackages) {
7204            ArrayList<ApplicationInfo> list;
7205            if (listUninstalled) {
7206                list = new ArrayList<>(mSettings.mPackages.size());
7207                for (PackageSetting ps : mSettings.mPackages.values()) {
7208                    ApplicationInfo ai;
7209                    int effectiveFlags = flags;
7210                    if (ps.isSystem()) {
7211                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7212                    }
7213                    if (ps.pkg != null) {
7214                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7215                            continue;
7216                        }
7217                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7218                                ps.readUserState(userId), userId);
7219                        if (ai != null) {
7220                            rebaseEnabledOverlays(ai, userId);
7221                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7222                        }
7223                    } else {
7224                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7225                        // and already converts to externally visible package name
7226                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7227                                Binder.getCallingUid(), effectiveFlags, userId);
7228                    }
7229                    if (ai != null) {
7230                        list.add(ai);
7231                    }
7232                }
7233            } else {
7234                list = new ArrayList<>(mPackages.size());
7235                for (PackageParser.Package p : mPackages.values()) {
7236                    if (p.mExtras != null) {
7237                        PackageSetting ps = (PackageSetting) p.mExtras;
7238                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7239                            continue;
7240                        }
7241                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7242                                ps.readUserState(userId), userId);
7243                        if (ai != null) {
7244                            rebaseEnabledOverlays(ai, userId);
7245                            ai.packageName = resolveExternalPackageNameLPr(p);
7246                            list.add(ai);
7247                        }
7248                    }
7249                }
7250            }
7251
7252            return new ParceledListSlice<>(list);
7253        }
7254    }
7255
7256    @Override
7257    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7258        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7259            return null;
7260        }
7261
7262        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7263                "getEphemeralApplications");
7264        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7265                true /* requireFullPermission */, false /* checkShell */,
7266                "getEphemeralApplications");
7267        synchronized (mPackages) {
7268            List<InstantAppInfo> instantApps = mInstantAppRegistry
7269                    .getInstantAppsLPr(userId);
7270            if (instantApps != null) {
7271                return new ParceledListSlice<>(instantApps);
7272            }
7273        }
7274        return null;
7275    }
7276
7277    @Override
7278    public boolean isInstantApp(String packageName, int userId) {
7279        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7280                true /* requireFullPermission */, false /* checkShell */,
7281                "isInstantApp");
7282        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7283            return false;
7284        }
7285
7286        synchronized (mPackages) {
7287            final PackageSetting ps = mSettings.mPackages.get(packageName);
7288            final boolean returnAllowed =
7289                    ps != null
7290                    && (isCallerSameApp(packageName)
7291                            || mContext.checkCallingOrSelfPermission(
7292                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7293                                            == PERMISSION_GRANTED
7294                            || mInstantAppRegistry.isInstantAccessGranted(
7295                                    userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId));
7296            if (returnAllowed) {
7297                return ps.getInstantApp(userId);
7298            }
7299        }
7300        return false;
7301    }
7302
7303    @Override
7304    public byte[] getInstantAppCookie(String packageName, int userId) {
7305        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7306            return null;
7307        }
7308
7309        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7310                true /* requireFullPermission */, false /* checkShell */,
7311                "getInstantAppCookie");
7312        if (!isCallerSameApp(packageName)) {
7313            return null;
7314        }
7315        synchronized (mPackages) {
7316            return mInstantAppRegistry.getInstantAppCookieLPw(
7317                    packageName, userId);
7318        }
7319    }
7320
7321    @Override
7322    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7323        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7324            return true;
7325        }
7326
7327        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7328                true /* requireFullPermission */, true /* checkShell */,
7329                "setInstantAppCookie");
7330        if (!isCallerSameApp(packageName)) {
7331            return false;
7332        }
7333        synchronized (mPackages) {
7334            return mInstantAppRegistry.setInstantAppCookieLPw(
7335                    packageName, cookie, userId);
7336        }
7337    }
7338
7339    @Override
7340    public Bitmap getInstantAppIcon(String packageName, int userId) {
7341        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7342            return null;
7343        }
7344
7345        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7346                "getInstantAppIcon");
7347
7348        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7349                true /* requireFullPermission */, false /* checkShell */,
7350                "getInstantAppIcon");
7351
7352        synchronized (mPackages) {
7353            return mInstantAppRegistry.getInstantAppIconLPw(
7354                    packageName, userId);
7355        }
7356    }
7357
7358    private boolean isCallerSameApp(String packageName) {
7359        PackageParser.Package pkg = mPackages.get(packageName);
7360        return pkg != null
7361                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7362    }
7363
7364    @Override
7365    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7366        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7367    }
7368
7369    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7370        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7371
7372        // reader
7373        synchronized (mPackages) {
7374            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7375            final int userId = UserHandle.getCallingUserId();
7376            while (i.hasNext()) {
7377                final PackageParser.Package p = i.next();
7378                if (p.applicationInfo == null) continue;
7379
7380                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7381                        && !p.applicationInfo.isDirectBootAware();
7382                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7383                        && p.applicationInfo.isDirectBootAware();
7384
7385                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7386                        && (!mSafeMode || isSystemApp(p))
7387                        && (matchesUnaware || matchesAware)) {
7388                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7389                    if (ps != null) {
7390                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7391                                ps.readUserState(userId), userId);
7392                        if (ai != null) {
7393                            rebaseEnabledOverlays(ai, userId);
7394                            finalList.add(ai);
7395                        }
7396                    }
7397                }
7398            }
7399        }
7400
7401        return finalList;
7402    }
7403
7404    @Override
7405    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7406        if (!sUserManager.exists(userId)) return null;
7407        flags = updateFlagsForComponent(flags, userId, name);
7408        // reader
7409        synchronized (mPackages) {
7410            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7411            PackageSetting ps = provider != null
7412                    ? mSettings.mPackages.get(provider.owner.packageName)
7413                    : null;
7414            return ps != null
7415                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7416                    ? PackageParser.generateProviderInfo(provider, flags,
7417                            ps.readUserState(userId), userId)
7418                    : null;
7419        }
7420    }
7421
7422    /**
7423     * @deprecated
7424     */
7425    @Deprecated
7426    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7427        // reader
7428        synchronized (mPackages) {
7429            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7430                    .entrySet().iterator();
7431            final int userId = UserHandle.getCallingUserId();
7432            while (i.hasNext()) {
7433                Map.Entry<String, PackageParser.Provider> entry = i.next();
7434                PackageParser.Provider p = entry.getValue();
7435                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7436
7437                if (ps != null && p.syncable
7438                        && (!mSafeMode || (p.info.applicationInfo.flags
7439                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7440                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7441                            ps.readUserState(userId), userId);
7442                    if (info != null) {
7443                        outNames.add(entry.getKey());
7444                        outInfo.add(info);
7445                    }
7446                }
7447            }
7448        }
7449    }
7450
7451    @Override
7452    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7453            int uid, int flags, String metaDataKey) {
7454        final int userId = processName != null ? UserHandle.getUserId(uid)
7455                : UserHandle.getCallingUserId();
7456        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7457        flags = updateFlagsForComponent(flags, userId, processName);
7458
7459        ArrayList<ProviderInfo> finalList = null;
7460        // reader
7461        synchronized (mPackages) {
7462            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7463            while (i.hasNext()) {
7464                final PackageParser.Provider p = i.next();
7465                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7466                if (ps != null && p.info.authority != null
7467                        && (processName == null
7468                                || (p.info.processName.equals(processName)
7469                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7470                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7471
7472                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7473                    // parameter.
7474                    if (metaDataKey != null
7475                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7476                        continue;
7477                    }
7478
7479                    if (finalList == null) {
7480                        finalList = new ArrayList<ProviderInfo>(3);
7481                    }
7482                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7483                            ps.readUserState(userId), userId);
7484                    if (info != null) {
7485                        finalList.add(info);
7486                    }
7487                }
7488            }
7489        }
7490
7491        if (finalList != null) {
7492            Collections.sort(finalList, mProviderInitOrderSorter);
7493            return new ParceledListSlice<ProviderInfo>(finalList);
7494        }
7495
7496        return ParceledListSlice.emptyList();
7497    }
7498
7499    @Override
7500    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7501        // reader
7502        synchronized (mPackages) {
7503            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7504            return PackageParser.generateInstrumentationInfo(i, flags);
7505        }
7506    }
7507
7508    @Override
7509    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7510            String targetPackage, int flags) {
7511        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7512    }
7513
7514    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7515            int flags) {
7516        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7517
7518        // reader
7519        synchronized (mPackages) {
7520            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7521            while (i.hasNext()) {
7522                final PackageParser.Instrumentation p = i.next();
7523                if (targetPackage == null
7524                        || targetPackage.equals(p.info.targetPackage)) {
7525                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7526                            flags);
7527                    if (ii != null) {
7528                        finalList.add(ii);
7529                    }
7530                }
7531            }
7532        }
7533
7534        return finalList;
7535    }
7536
7537    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7538        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7539        try {
7540            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7541        } finally {
7542            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7543        }
7544    }
7545
7546    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7547        final File[] files = dir.listFiles();
7548        if (ArrayUtils.isEmpty(files)) {
7549            Log.d(TAG, "No files in app dir " + dir);
7550            return;
7551        }
7552
7553        if (DEBUG_PACKAGE_SCANNING) {
7554            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7555                    + " flags=0x" + Integer.toHexString(parseFlags));
7556        }
7557        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7558                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7559
7560        // Submit files for parsing in parallel
7561        int fileCount = 0;
7562        for (File file : files) {
7563            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7564                    && !PackageInstallerService.isStageName(file.getName());
7565            if (!isPackage) {
7566                // Ignore entries which are not packages
7567                continue;
7568            }
7569            parallelPackageParser.submit(file, parseFlags);
7570            fileCount++;
7571        }
7572
7573        // Process results one by one
7574        for (; fileCount > 0; fileCount--) {
7575            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7576            Throwable throwable = parseResult.throwable;
7577            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7578
7579            if (throwable == null) {
7580                // Static shared libraries have synthetic package names
7581                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7582                    renameStaticSharedLibraryPackage(parseResult.pkg);
7583                }
7584                try {
7585                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7586                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7587                                currentTime, null);
7588                    }
7589                } catch (PackageManagerException e) {
7590                    errorCode = e.error;
7591                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7592                }
7593            } else if (throwable instanceof PackageParser.PackageParserException) {
7594                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7595                        throwable;
7596                errorCode = e.error;
7597                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7598            } else {
7599                throw new IllegalStateException("Unexpected exception occurred while parsing "
7600                        + parseResult.scanFile, throwable);
7601            }
7602
7603            // Delete invalid userdata apps
7604            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7605                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7606                logCriticalInfo(Log.WARN,
7607                        "Deleting invalid package at " + parseResult.scanFile);
7608                removeCodePathLI(parseResult.scanFile);
7609            }
7610        }
7611        parallelPackageParser.close();
7612    }
7613
7614    private static File getSettingsProblemFile() {
7615        File dataDir = Environment.getDataDirectory();
7616        File systemDir = new File(dataDir, "system");
7617        File fname = new File(systemDir, "uiderrors.txt");
7618        return fname;
7619    }
7620
7621    static void reportSettingsProblem(int priority, String msg) {
7622        logCriticalInfo(priority, msg);
7623    }
7624
7625    public static void logCriticalInfo(int priority, String msg) {
7626        Slog.println(priority, TAG, msg);
7627        EventLogTags.writePmCriticalInfo(msg);
7628        try {
7629            File fname = getSettingsProblemFile();
7630            FileOutputStream out = new FileOutputStream(fname, true);
7631            PrintWriter pw = new FastPrintWriter(out);
7632            SimpleDateFormat formatter = new SimpleDateFormat();
7633            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7634            pw.println(dateString + ": " + msg);
7635            pw.close();
7636            FileUtils.setPermissions(
7637                    fname.toString(),
7638                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7639                    -1, -1);
7640        } catch (java.io.IOException e) {
7641        }
7642    }
7643
7644    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7645        if (srcFile.isDirectory()) {
7646            final File baseFile = new File(pkg.baseCodePath);
7647            long maxModifiedTime = baseFile.lastModified();
7648            if (pkg.splitCodePaths != null) {
7649                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7650                    final File splitFile = new File(pkg.splitCodePaths[i]);
7651                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7652                }
7653            }
7654            return maxModifiedTime;
7655        }
7656        return srcFile.lastModified();
7657    }
7658
7659    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7660            final int policyFlags) throws PackageManagerException {
7661        // When upgrading from pre-N MR1, verify the package time stamp using the package
7662        // directory and not the APK file.
7663        final long lastModifiedTime = mIsPreNMR1Upgrade
7664                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7665        if (ps != null
7666                && ps.codePath.equals(srcFile)
7667                && ps.timeStamp == lastModifiedTime
7668                && !isCompatSignatureUpdateNeeded(pkg)
7669                && !isRecoverSignatureUpdateNeeded(pkg)) {
7670            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7671            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7672            ArraySet<PublicKey> signingKs;
7673            synchronized (mPackages) {
7674                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7675            }
7676            if (ps.signatures.mSignatures != null
7677                    && ps.signatures.mSignatures.length != 0
7678                    && signingKs != null) {
7679                // Optimization: reuse the existing cached certificates
7680                // if the package appears to be unchanged.
7681                pkg.mSignatures = ps.signatures.mSignatures;
7682                pkg.mSigningKeys = signingKs;
7683                return;
7684            }
7685
7686            Slog.w(TAG, "PackageSetting for " + ps.name
7687                    + " is missing signatures.  Collecting certs again to recover them.");
7688        } else {
7689            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7690        }
7691
7692        try {
7693            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7694            PackageParser.collectCertificates(pkg, policyFlags);
7695        } catch (PackageParserException e) {
7696            throw PackageManagerException.from(e);
7697        } finally {
7698            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7699        }
7700    }
7701
7702    /**
7703     *  Traces a package scan.
7704     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7705     */
7706    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7707            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7708        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7709        try {
7710            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7711        } finally {
7712            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7713        }
7714    }
7715
7716    /**
7717     *  Scans a package and returns the newly parsed package.
7718     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7719     */
7720    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7721            long currentTime, UserHandle user) throws PackageManagerException {
7722        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7723        PackageParser pp = new PackageParser();
7724        pp.setSeparateProcesses(mSeparateProcesses);
7725        pp.setOnlyCoreApps(mOnlyCore);
7726        pp.setDisplayMetrics(mMetrics);
7727        pp.setCallback(mPackageParserCallback);
7728
7729        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7730            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7731        }
7732
7733        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7734        final PackageParser.Package pkg;
7735        try {
7736            pkg = pp.parsePackage(scanFile, parseFlags);
7737        } catch (PackageParserException e) {
7738            throw PackageManagerException.from(e);
7739        } finally {
7740            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7741        }
7742
7743        // Static shared libraries have synthetic package names
7744        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7745            renameStaticSharedLibraryPackage(pkg);
7746        }
7747
7748        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7749    }
7750
7751    /**
7752     *  Scans a package and returns the newly parsed package.
7753     *  @throws PackageManagerException on a parse error.
7754     */
7755    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7756            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7757            throws PackageManagerException {
7758        // If the package has children and this is the first dive in the function
7759        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7760        // packages (parent and children) would be successfully scanned before the
7761        // actual scan since scanning mutates internal state and we want to atomically
7762        // install the package and its children.
7763        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7764            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7765                scanFlags |= SCAN_CHECK_ONLY;
7766            }
7767        } else {
7768            scanFlags &= ~SCAN_CHECK_ONLY;
7769        }
7770
7771        // Scan the parent
7772        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7773                scanFlags, currentTime, user);
7774
7775        // Scan the children
7776        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7777        for (int i = 0; i < childCount; i++) {
7778            PackageParser.Package childPackage = pkg.childPackages.get(i);
7779            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7780                    currentTime, user);
7781        }
7782
7783
7784        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7785            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7786        }
7787
7788        return scannedPkg;
7789    }
7790
7791    /**
7792     *  Scans a package and returns the newly parsed package.
7793     *  @throws PackageManagerException on a parse error.
7794     */
7795    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7796            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7797            throws PackageManagerException {
7798        PackageSetting ps = null;
7799        PackageSetting updatedPkg;
7800        // reader
7801        synchronized (mPackages) {
7802            // Look to see if we already know about this package.
7803            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7804            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7805                // This package has been renamed to its original name.  Let's
7806                // use that.
7807                ps = mSettings.getPackageLPr(oldName);
7808            }
7809            // If there was no original package, see one for the real package name.
7810            if (ps == null) {
7811                ps = mSettings.getPackageLPr(pkg.packageName);
7812            }
7813            // Check to see if this package could be hiding/updating a system
7814            // package.  Must look for it either under the original or real
7815            // package name depending on our state.
7816            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7817            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7818
7819            // If this is a package we don't know about on the system partition, we
7820            // may need to remove disabled child packages on the system partition
7821            // or may need to not add child packages if the parent apk is updated
7822            // on the data partition and no longer defines this child package.
7823            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7824                // If this is a parent package for an updated system app and this system
7825                // app got an OTA update which no longer defines some of the child packages
7826                // we have to prune them from the disabled system packages.
7827                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7828                if (disabledPs != null) {
7829                    final int scannedChildCount = (pkg.childPackages != null)
7830                            ? pkg.childPackages.size() : 0;
7831                    final int disabledChildCount = disabledPs.childPackageNames != null
7832                            ? disabledPs.childPackageNames.size() : 0;
7833                    for (int i = 0; i < disabledChildCount; i++) {
7834                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7835                        boolean disabledPackageAvailable = false;
7836                        for (int j = 0; j < scannedChildCount; j++) {
7837                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7838                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7839                                disabledPackageAvailable = true;
7840                                break;
7841                            }
7842                         }
7843                         if (!disabledPackageAvailable) {
7844                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7845                         }
7846                    }
7847                }
7848            }
7849        }
7850
7851        boolean updatedPkgBetter = false;
7852        // First check if this is a system package that may involve an update
7853        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7854            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7855            // it needs to drop FLAG_PRIVILEGED.
7856            if (locationIsPrivileged(scanFile)) {
7857                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7858            } else {
7859                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7860            }
7861
7862            if (ps != null && !ps.codePath.equals(scanFile)) {
7863                // The path has changed from what was last scanned...  check the
7864                // version of the new path against what we have stored to determine
7865                // what to do.
7866                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7867                if (pkg.mVersionCode <= ps.versionCode) {
7868                    // The system package has been updated and the code path does not match
7869                    // Ignore entry. Skip it.
7870                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7871                            + " ignored: updated version " + ps.versionCode
7872                            + " better than this " + pkg.mVersionCode);
7873                    if (!updatedPkg.codePath.equals(scanFile)) {
7874                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7875                                + ps.name + " changing from " + updatedPkg.codePathString
7876                                + " to " + scanFile);
7877                        updatedPkg.codePath = scanFile;
7878                        updatedPkg.codePathString = scanFile.toString();
7879                        updatedPkg.resourcePath = scanFile;
7880                        updatedPkg.resourcePathString = scanFile.toString();
7881                    }
7882                    updatedPkg.pkg = pkg;
7883                    updatedPkg.versionCode = pkg.mVersionCode;
7884
7885                    // Update the disabled system child packages to point to the package too.
7886                    final int childCount = updatedPkg.childPackageNames != null
7887                            ? updatedPkg.childPackageNames.size() : 0;
7888                    for (int i = 0; i < childCount; i++) {
7889                        String childPackageName = updatedPkg.childPackageNames.get(i);
7890                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7891                                childPackageName);
7892                        if (updatedChildPkg != null) {
7893                            updatedChildPkg.pkg = pkg;
7894                            updatedChildPkg.versionCode = pkg.mVersionCode;
7895                        }
7896                    }
7897
7898                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7899                            + scanFile + " ignored: updated version " + ps.versionCode
7900                            + " better than this " + pkg.mVersionCode);
7901                } else {
7902                    // The current app on the system partition is better than
7903                    // what we have updated to on the data partition; switch
7904                    // back to the system partition version.
7905                    // At this point, its safely assumed that package installation for
7906                    // apps in system partition will go through. If not there won't be a working
7907                    // version of the app
7908                    // writer
7909                    synchronized (mPackages) {
7910                        // Just remove the loaded entries from package lists.
7911                        mPackages.remove(ps.name);
7912                    }
7913
7914                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7915                            + " reverting from " + ps.codePathString
7916                            + ": new version " + pkg.mVersionCode
7917                            + " better than installed " + ps.versionCode);
7918
7919                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7920                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7921                    synchronized (mInstallLock) {
7922                        args.cleanUpResourcesLI();
7923                    }
7924                    synchronized (mPackages) {
7925                        mSettings.enableSystemPackageLPw(ps.name);
7926                    }
7927                    updatedPkgBetter = true;
7928                }
7929            }
7930        }
7931
7932        if (updatedPkg != null) {
7933            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7934            // initially
7935            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7936
7937            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7938            // flag set initially
7939            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7940                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7941            }
7942        }
7943
7944        // Verify certificates against what was last scanned
7945        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7946
7947        /*
7948         * A new system app appeared, but we already had a non-system one of the
7949         * same name installed earlier.
7950         */
7951        boolean shouldHideSystemApp = false;
7952        if (updatedPkg == null && ps != null
7953                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7954            /*
7955             * Check to make sure the signatures match first. If they don't,
7956             * wipe the installed application and its data.
7957             */
7958            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7959                    != PackageManager.SIGNATURE_MATCH) {
7960                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7961                        + " signatures don't match existing userdata copy; removing");
7962                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7963                        "scanPackageInternalLI")) {
7964                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7965                }
7966                ps = null;
7967            } else {
7968                /*
7969                 * If the newly-added system app is an older version than the
7970                 * already installed version, hide it. It will be scanned later
7971                 * and re-added like an update.
7972                 */
7973                if (pkg.mVersionCode <= ps.versionCode) {
7974                    shouldHideSystemApp = true;
7975                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7976                            + " but new version " + pkg.mVersionCode + " better than installed "
7977                            + ps.versionCode + "; hiding system");
7978                } else {
7979                    /*
7980                     * The newly found system app is a newer version that the
7981                     * one previously installed. Simply remove the
7982                     * already-installed application and replace it with our own
7983                     * while keeping the application data.
7984                     */
7985                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7986                            + " reverting from " + ps.codePathString + ": new version "
7987                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7988                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7989                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7990                    synchronized (mInstallLock) {
7991                        args.cleanUpResourcesLI();
7992                    }
7993                }
7994            }
7995        }
7996
7997        // The apk is forward locked (not public) if its code and resources
7998        // are kept in different files. (except for app in either system or
7999        // vendor path).
8000        // TODO grab this value from PackageSettings
8001        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8002            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8003                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8004            }
8005        }
8006
8007        // TODO: extend to support forward-locked splits
8008        String resourcePath = null;
8009        String baseResourcePath = null;
8010        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8011            if (ps != null && ps.resourcePathString != null) {
8012                resourcePath = ps.resourcePathString;
8013                baseResourcePath = ps.resourcePathString;
8014            } else {
8015                // Should not happen at all. Just log an error.
8016                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8017            }
8018        } else {
8019            resourcePath = pkg.codePath;
8020            baseResourcePath = pkg.baseCodePath;
8021        }
8022
8023        // Set application objects path explicitly.
8024        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8025        pkg.setApplicationInfoCodePath(pkg.codePath);
8026        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8027        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8028        pkg.setApplicationInfoResourcePath(resourcePath);
8029        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8030        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8031
8032        final int userId = ((user == null) ? 0 : user.getIdentifier());
8033        if (ps != null && ps.getInstantApp(userId)) {
8034            scanFlags |= SCAN_AS_INSTANT_APP;
8035        }
8036
8037        // Note that we invoke the following method only if we are about to unpack an application
8038        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8039                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8040
8041        /*
8042         * If the system app should be overridden by a previously installed
8043         * data, hide the system app now and let the /data/app scan pick it up
8044         * again.
8045         */
8046        if (shouldHideSystemApp) {
8047            synchronized (mPackages) {
8048                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8049            }
8050        }
8051
8052        return scannedPkg;
8053    }
8054
8055    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8056        // Derive the new package synthetic package name
8057        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8058                + pkg.staticSharedLibVersion);
8059    }
8060
8061    private static String fixProcessName(String defProcessName,
8062            String processName) {
8063        if (processName == null) {
8064            return defProcessName;
8065        }
8066        return processName;
8067    }
8068
8069    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8070            throws PackageManagerException {
8071        if (pkgSetting.signatures.mSignatures != null) {
8072            // Already existing package. Make sure signatures match
8073            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8074                    == PackageManager.SIGNATURE_MATCH;
8075            if (!match) {
8076                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8077                        == PackageManager.SIGNATURE_MATCH;
8078            }
8079            if (!match) {
8080                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8081                        == PackageManager.SIGNATURE_MATCH;
8082            }
8083            if (!match) {
8084                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8085                        + pkg.packageName + " signatures do not match the "
8086                        + "previously installed version; ignoring!");
8087            }
8088        }
8089
8090        // Check for shared user signatures
8091        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8092            // Already existing package. Make sure signatures match
8093            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8094                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8095            if (!match) {
8096                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8097                        == PackageManager.SIGNATURE_MATCH;
8098            }
8099            if (!match) {
8100                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8101                        == PackageManager.SIGNATURE_MATCH;
8102            }
8103            if (!match) {
8104                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8105                        "Package " + pkg.packageName
8106                        + " has no signatures that match those in shared user "
8107                        + pkgSetting.sharedUser.name + "; ignoring!");
8108            }
8109        }
8110    }
8111
8112    /**
8113     * Enforces that only the system UID or root's UID can call a method exposed
8114     * via Binder.
8115     *
8116     * @param message used as message if SecurityException is thrown
8117     * @throws SecurityException if the caller is not system or root
8118     */
8119    private static final void enforceSystemOrRoot(String message) {
8120        final int uid = Binder.getCallingUid();
8121        if (uid != Process.SYSTEM_UID && uid != 0) {
8122            throw new SecurityException(message);
8123        }
8124    }
8125
8126    @Override
8127    public void performFstrimIfNeeded() {
8128        enforceSystemOrRoot("Only the system can request fstrim");
8129
8130        // Before everything else, see whether we need to fstrim.
8131        try {
8132            IStorageManager sm = PackageHelper.getStorageManager();
8133            if (sm != null) {
8134                boolean doTrim = false;
8135                final long interval = android.provider.Settings.Global.getLong(
8136                        mContext.getContentResolver(),
8137                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8138                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8139                if (interval > 0) {
8140                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8141                    if (timeSinceLast > interval) {
8142                        doTrim = true;
8143                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8144                                + "; running immediately");
8145                    }
8146                }
8147                if (doTrim) {
8148                    final boolean dexOptDialogShown;
8149                    synchronized (mPackages) {
8150                        dexOptDialogShown = mDexOptDialogShown;
8151                    }
8152                    if (!isFirstBoot() && dexOptDialogShown) {
8153                        try {
8154                            ActivityManager.getService().showBootMessage(
8155                                    mContext.getResources().getString(
8156                                            R.string.android_upgrading_fstrim), true);
8157                        } catch (RemoteException e) {
8158                        }
8159                    }
8160                    sm.runMaintenance();
8161                }
8162            } else {
8163                Slog.e(TAG, "storageManager service unavailable!");
8164            }
8165        } catch (RemoteException e) {
8166            // Can't happen; StorageManagerService is local
8167        }
8168    }
8169
8170    @Override
8171    public void updatePackagesIfNeeded() {
8172        enforceSystemOrRoot("Only the system can request package update");
8173
8174        // We need to re-extract after an OTA.
8175        boolean causeUpgrade = isUpgrade();
8176
8177        // First boot or factory reset.
8178        // Note: we also handle devices that are upgrading to N right now as if it is their
8179        //       first boot, as they do not have profile data.
8180        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8181
8182        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8183        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8184
8185        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8186            return;
8187        }
8188
8189        List<PackageParser.Package> pkgs;
8190        synchronized (mPackages) {
8191            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8192        }
8193
8194        final long startTime = System.nanoTime();
8195        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8196                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8197
8198        final int elapsedTimeSeconds =
8199                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8200
8201        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8202        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8203        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8204        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8205        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8206    }
8207
8208    /**
8209     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8210     * containing statistics about the invocation. The array consists of three elements,
8211     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8212     * and {@code numberOfPackagesFailed}.
8213     */
8214    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8215            String compilerFilter) {
8216
8217        int numberOfPackagesVisited = 0;
8218        int numberOfPackagesOptimized = 0;
8219        int numberOfPackagesSkipped = 0;
8220        int numberOfPackagesFailed = 0;
8221        final int numberOfPackagesToDexopt = pkgs.size();
8222
8223        for (PackageParser.Package pkg : pkgs) {
8224            numberOfPackagesVisited++;
8225
8226            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8227                if (DEBUG_DEXOPT) {
8228                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8229                }
8230                numberOfPackagesSkipped++;
8231                continue;
8232            }
8233
8234            if (DEBUG_DEXOPT) {
8235                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8236                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8237            }
8238
8239            if (showDialog) {
8240                try {
8241                    ActivityManager.getService().showBootMessage(
8242                            mContext.getResources().getString(R.string.android_upgrading_apk,
8243                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8244                } catch (RemoteException e) {
8245                }
8246                synchronized (mPackages) {
8247                    mDexOptDialogShown = true;
8248                }
8249            }
8250
8251            // If the OTA updates a system app which was previously preopted to a non-preopted state
8252            // the app might end up being verified at runtime. That's because by default the apps
8253            // are verify-profile but for preopted apps there's no profile.
8254            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8255            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8256            // filter (by default interpret-only).
8257            // Note that at this stage unused apps are already filtered.
8258            if (isSystemApp(pkg) &&
8259                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8260                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8261                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8262            }
8263
8264            // checkProfiles is false to avoid merging profiles during boot which
8265            // might interfere with background compilation (b/28612421).
8266            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8267            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8268            // trade-off worth doing to save boot time work.
8269            int dexOptStatus = performDexOptTraced(pkg.packageName,
8270                    false /* checkProfiles */,
8271                    compilerFilter,
8272                    false /* force */);
8273            switch (dexOptStatus) {
8274                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8275                    numberOfPackagesOptimized++;
8276                    break;
8277                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8278                    numberOfPackagesSkipped++;
8279                    break;
8280                case PackageDexOptimizer.DEX_OPT_FAILED:
8281                    numberOfPackagesFailed++;
8282                    break;
8283                default:
8284                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8285                    break;
8286            }
8287        }
8288
8289        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8290                numberOfPackagesFailed };
8291    }
8292
8293    @Override
8294    public void notifyPackageUse(String packageName, int reason) {
8295        synchronized (mPackages) {
8296            PackageParser.Package p = mPackages.get(packageName);
8297            if (p == null) {
8298                return;
8299            }
8300            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8301        }
8302    }
8303
8304    @Override
8305    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8306        int userId = UserHandle.getCallingUserId();
8307        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8308        if (ai == null) {
8309            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8310                + loadingPackageName + ", user=" + userId);
8311            return;
8312        }
8313        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8314    }
8315
8316    // TODO: this is not used nor needed. Delete it.
8317    @Override
8318    public boolean performDexOptIfNeeded(String packageName) {
8319        int dexOptStatus = performDexOptTraced(packageName,
8320                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8321        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8322    }
8323
8324    @Override
8325    public boolean performDexOpt(String packageName,
8326            boolean checkProfiles, int compileReason, boolean force) {
8327        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8328                getCompilerFilterForReason(compileReason), force);
8329        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8330    }
8331
8332    @Override
8333    public boolean performDexOptMode(String packageName,
8334            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8335        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8336                targetCompilerFilter, force);
8337        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8338    }
8339
8340    private int performDexOptTraced(String packageName,
8341                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8342        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8343        try {
8344            return performDexOptInternal(packageName, checkProfiles,
8345                    targetCompilerFilter, force);
8346        } finally {
8347            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8348        }
8349    }
8350
8351    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8352    // if the package can now be considered up to date for the given filter.
8353    private int performDexOptInternal(String packageName,
8354                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8355        PackageParser.Package p;
8356        synchronized (mPackages) {
8357            p = mPackages.get(packageName);
8358            if (p == null) {
8359                // Package could not be found. Report failure.
8360                return PackageDexOptimizer.DEX_OPT_FAILED;
8361            }
8362            mPackageUsage.maybeWriteAsync(mPackages);
8363            mCompilerStats.maybeWriteAsync();
8364        }
8365        long callingId = Binder.clearCallingIdentity();
8366        try {
8367            synchronized (mInstallLock) {
8368                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8369                        targetCompilerFilter, force);
8370            }
8371        } finally {
8372            Binder.restoreCallingIdentity(callingId);
8373        }
8374    }
8375
8376    public ArraySet<String> getOptimizablePackages() {
8377        ArraySet<String> pkgs = new ArraySet<String>();
8378        synchronized (mPackages) {
8379            for (PackageParser.Package p : mPackages.values()) {
8380                if (PackageDexOptimizer.canOptimizePackage(p)) {
8381                    pkgs.add(p.packageName);
8382                }
8383            }
8384        }
8385        return pkgs;
8386    }
8387
8388    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8389            boolean checkProfiles, String targetCompilerFilter,
8390            boolean force) {
8391        // Select the dex optimizer based on the force parameter.
8392        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8393        //       allocate an object here.
8394        PackageDexOptimizer pdo = force
8395                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8396                : mPackageDexOptimizer;
8397
8398        // Optimize all dependencies first. Note: we ignore the return value and march on
8399        // on errors.
8400        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8401        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8402        if (!deps.isEmpty()) {
8403            for (PackageParser.Package depPackage : deps) {
8404                // TODO: Analyze and investigate if we (should) profile libraries.
8405                // Currently this will do a full compilation of the library by default.
8406                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8407                        false /* checkProfiles */,
8408                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8409                        getOrCreateCompilerPackageStats(depPackage),
8410                        mDexManager.isUsedByOtherApps(p.packageName));
8411            }
8412        }
8413        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8414                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8415                mDexManager.isUsedByOtherApps(p.packageName));
8416    }
8417
8418    // Performs dexopt on the used secondary dex files belonging to the given package.
8419    // Returns true if all dex files were process successfully (which could mean either dexopt or
8420    // skip). Returns false if any of the files caused errors.
8421    @Override
8422    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8423            boolean force) {
8424        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8425    }
8426
8427    public boolean performDexOptSecondary(String packageName, int compileReason,
8428            boolean force) {
8429        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8430    }
8431
8432    /**
8433     * Reconcile the information we have about the secondary dex files belonging to
8434     * {@code packagName} and the actual dex files. For all dex files that were
8435     * deleted, update the internal records and delete the generated oat files.
8436     */
8437    @Override
8438    public void reconcileSecondaryDexFiles(String packageName) {
8439        mDexManager.reconcileSecondaryDexFiles(packageName);
8440    }
8441
8442    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8443    // a reference there.
8444    /*package*/ DexManager getDexManager() {
8445        return mDexManager;
8446    }
8447
8448    /**
8449     * Execute the background dexopt job immediately.
8450     */
8451    @Override
8452    public boolean runBackgroundDexoptJob() {
8453        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8454    }
8455
8456    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8457        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8458                || p.usesStaticLibraries != null) {
8459            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8460            Set<String> collectedNames = new HashSet<>();
8461            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8462
8463            retValue.remove(p);
8464
8465            return retValue;
8466        } else {
8467            return Collections.emptyList();
8468        }
8469    }
8470
8471    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8472            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8473        if (!collectedNames.contains(p.packageName)) {
8474            collectedNames.add(p.packageName);
8475            collected.add(p);
8476
8477            if (p.usesLibraries != null) {
8478                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8479                        null, collected, collectedNames);
8480            }
8481            if (p.usesOptionalLibraries != null) {
8482                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8483                        null, collected, collectedNames);
8484            }
8485            if (p.usesStaticLibraries != null) {
8486                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8487                        p.usesStaticLibrariesVersions, collected, collectedNames);
8488            }
8489        }
8490    }
8491
8492    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8493            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8494        final int libNameCount = libs.size();
8495        for (int i = 0; i < libNameCount; i++) {
8496            String libName = libs.get(i);
8497            int version = (versions != null && versions.length == libNameCount)
8498                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8499            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8500            if (libPkg != null) {
8501                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8502            }
8503        }
8504    }
8505
8506    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8507        synchronized (mPackages) {
8508            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8509            if (libEntry != null) {
8510                return mPackages.get(libEntry.apk);
8511            }
8512            return null;
8513        }
8514    }
8515
8516    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8517        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8518        if (versionedLib == null) {
8519            return null;
8520        }
8521        return versionedLib.get(version);
8522    }
8523
8524    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8525        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8526                pkg.staticSharedLibName);
8527        if (versionedLib == null) {
8528            return null;
8529        }
8530        int previousLibVersion = -1;
8531        final int versionCount = versionedLib.size();
8532        for (int i = 0; i < versionCount; i++) {
8533            final int libVersion = versionedLib.keyAt(i);
8534            if (libVersion < pkg.staticSharedLibVersion) {
8535                previousLibVersion = Math.max(previousLibVersion, libVersion);
8536            }
8537        }
8538        if (previousLibVersion >= 0) {
8539            return versionedLib.get(previousLibVersion);
8540        }
8541        return null;
8542    }
8543
8544    public void shutdown() {
8545        mPackageUsage.writeNow(mPackages);
8546        mCompilerStats.writeNow();
8547    }
8548
8549    @Override
8550    public void dumpProfiles(String packageName) {
8551        PackageParser.Package pkg;
8552        synchronized (mPackages) {
8553            pkg = mPackages.get(packageName);
8554            if (pkg == null) {
8555                throw new IllegalArgumentException("Unknown package: " + packageName);
8556            }
8557        }
8558        /* Only the shell, root, or the app user should be able to dump profiles. */
8559        int callingUid = Binder.getCallingUid();
8560        if (callingUid != Process.SHELL_UID &&
8561            callingUid != Process.ROOT_UID &&
8562            callingUid != pkg.applicationInfo.uid) {
8563            throw new SecurityException("dumpProfiles");
8564        }
8565
8566        synchronized (mInstallLock) {
8567            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8568            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8569            try {
8570                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8571                String codePaths = TextUtils.join(";", allCodePaths);
8572                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8573            } catch (InstallerException e) {
8574                Slog.w(TAG, "Failed to dump profiles", e);
8575            }
8576            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8577        }
8578    }
8579
8580    @Override
8581    public void forceDexOpt(String packageName) {
8582        enforceSystemOrRoot("forceDexOpt");
8583
8584        PackageParser.Package pkg;
8585        synchronized (mPackages) {
8586            pkg = mPackages.get(packageName);
8587            if (pkg == null) {
8588                throw new IllegalArgumentException("Unknown package: " + packageName);
8589            }
8590        }
8591
8592        synchronized (mInstallLock) {
8593            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8594
8595            // Whoever is calling forceDexOpt wants a fully compiled package.
8596            // Don't use profiles since that may cause compilation to be skipped.
8597            final int res = performDexOptInternalWithDependenciesLI(pkg,
8598                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8599                    true /* force */);
8600
8601            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8602            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8603                throw new IllegalStateException("Failed to dexopt: " + res);
8604            }
8605        }
8606    }
8607
8608    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8609        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8610            Slog.w(TAG, "Unable to update from " + oldPkg.name
8611                    + " to " + newPkg.packageName
8612                    + ": old package not in system partition");
8613            return false;
8614        } else if (mPackages.get(oldPkg.name) != null) {
8615            Slog.w(TAG, "Unable to update from " + oldPkg.name
8616                    + " to " + newPkg.packageName
8617                    + ": old package still exists");
8618            return false;
8619        }
8620        return true;
8621    }
8622
8623    void removeCodePathLI(File codePath) {
8624        if (codePath.isDirectory()) {
8625            try {
8626                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8627            } catch (InstallerException e) {
8628                Slog.w(TAG, "Failed to remove code path", e);
8629            }
8630        } else {
8631            codePath.delete();
8632        }
8633    }
8634
8635    private int[] resolveUserIds(int userId) {
8636        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8637    }
8638
8639    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8640        if (pkg == null) {
8641            Slog.wtf(TAG, "Package was null!", new Throwable());
8642            return;
8643        }
8644        clearAppDataLeafLIF(pkg, userId, flags);
8645        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8646        for (int i = 0; i < childCount; i++) {
8647            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8648        }
8649    }
8650
8651    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8652        final PackageSetting ps;
8653        synchronized (mPackages) {
8654            ps = mSettings.mPackages.get(pkg.packageName);
8655        }
8656        for (int realUserId : resolveUserIds(userId)) {
8657            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8658            try {
8659                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8660                        ceDataInode);
8661            } catch (InstallerException e) {
8662                Slog.w(TAG, String.valueOf(e));
8663            }
8664        }
8665    }
8666
8667    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8668        if (pkg == null) {
8669            Slog.wtf(TAG, "Package was null!", new Throwable());
8670            return;
8671        }
8672        destroyAppDataLeafLIF(pkg, userId, flags);
8673        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8674        for (int i = 0; i < childCount; i++) {
8675            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8676        }
8677    }
8678
8679    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8680        final PackageSetting ps;
8681        synchronized (mPackages) {
8682            ps = mSettings.mPackages.get(pkg.packageName);
8683        }
8684        for (int realUserId : resolveUserIds(userId)) {
8685            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8686            try {
8687                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8688                        ceDataInode);
8689            } catch (InstallerException e) {
8690                Slog.w(TAG, String.valueOf(e));
8691            }
8692            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8693        }
8694    }
8695
8696    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8697        if (pkg == null) {
8698            Slog.wtf(TAG, "Package was null!", new Throwable());
8699            return;
8700        }
8701        destroyAppProfilesLeafLIF(pkg);
8702        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8703        for (int i = 0; i < childCount; i++) {
8704            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8705        }
8706    }
8707
8708    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8709        try {
8710            mInstaller.destroyAppProfiles(pkg.packageName);
8711        } catch (InstallerException e) {
8712            Slog.w(TAG, String.valueOf(e));
8713        }
8714    }
8715
8716    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8717        if (pkg == null) {
8718            Slog.wtf(TAG, "Package was null!", new Throwable());
8719            return;
8720        }
8721        clearAppProfilesLeafLIF(pkg);
8722        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8723        for (int i = 0; i < childCount; i++) {
8724            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8725        }
8726    }
8727
8728    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8729        try {
8730            mInstaller.clearAppProfiles(pkg.packageName);
8731        } catch (InstallerException e) {
8732            Slog.w(TAG, String.valueOf(e));
8733        }
8734    }
8735
8736    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8737            long lastUpdateTime) {
8738        // Set parent install/update time
8739        PackageSetting ps = (PackageSetting) pkg.mExtras;
8740        if (ps != null) {
8741            ps.firstInstallTime = firstInstallTime;
8742            ps.lastUpdateTime = lastUpdateTime;
8743        }
8744        // Set children install/update time
8745        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8746        for (int i = 0; i < childCount; i++) {
8747            PackageParser.Package childPkg = pkg.childPackages.get(i);
8748            ps = (PackageSetting) childPkg.mExtras;
8749            if (ps != null) {
8750                ps.firstInstallTime = firstInstallTime;
8751                ps.lastUpdateTime = lastUpdateTime;
8752            }
8753        }
8754    }
8755
8756    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8757            PackageParser.Package changingLib) {
8758        if (file.path != null) {
8759            usesLibraryFiles.add(file.path);
8760            return;
8761        }
8762        PackageParser.Package p = mPackages.get(file.apk);
8763        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8764            // If we are doing this while in the middle of updating a library apk,
8765            // then we need to make sure to use that new apk for determining the
8766            // dependencies here.  (We haven't yet finished committing the new apk
8767            // to the package manager state.)
8768            if (p == null || p.packageName.equals(changingLib.packageName)) {
8769                p = changingLib;
8770            }
8771        }
8772        if (p != null) {
8773            usesLibraryFiles.addAll(p.getAllCodePaths());
8774        }
8775    }
8776
8777    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8778            PackageParser.Package changingLib) throws PackageManagerException {
8779        if (pkg == null) {
8780            return;
8781        }
8782        ArraySet<String> usesLibraryFiles = null;
8783        if (pkg.usesLibraries != null) {
8784            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8785                    null, null, pkg.packageName, changingLib, true, null);
8786        }
8787        if (pkg.usesStaticLibraries != null) {
8788            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8789                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8790                    pkg.packageName, changingLib, true, usesLibraryFiles);
8791        }
8792        if (pkg.usesOptionalLibraries != null) {
8793            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8794                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8795        }
8796        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8797            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8798        } else {
8799            pkg.usesLibraryFiles = null;
8800        }
8801    }
8802
8803    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8804            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8805            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8806            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8807            throws PackageManagerException {
8808        final int libCount = requestedLibraries.size();
8809        for (int i = 0; i < libCount; i++) {
8810            final String libName = requestedLibraries.get(i);
8811            final int libVersion = requiredVersions != null ? requiredVersions[i]
8812                    : SharedLibraryInfo.VERSION_UNDEFINED;
8813            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8814            if (libEntry == null) {
8815                if (required) {
8816                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8817                            "Package " + packageName + " requires unavailable shared library "
8818                                    + libName + "; failing!");
8819                } else {
8820                    Slog.w(TAG, "Package " + packageName
8821                            + " desires unavailable shared library "
8822                            + libName + "; ignoring!");
8823                }
8824            } else {
8825                if (requiredVersions != null && requiredCertDigests != null) {
8826                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8827                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8828                            "Package " + packageName + " requires unavailable static shared"
8829                                    + " library " + libName + " version "
8830                                    + libEntry.info.getVersion() + "; failing!");
8831                    }
8832
8833                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8834                    if (libPkg == null) {
8835                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8836                                "Package " + packageName + " requires unavailable static shared"
8837                                        + " library; failing!");
8838                    }
8839
8840                    String expectedCertDigest = requiredCertDigests[i];
8841                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8842                                libPkg.mSignatures[0]);
8843                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8844                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8845                                "Package " + packageName + " requires differently signed" +
8846                                        " static shared library; failing!");
8847                    }
8848                }
8849
8850                if (outUsedLibraries == null) {
8851                    outUsedLibraries = new ArraySet<>();
8852                }
8853                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8854            }
8855        }
8856        return outUsedLibraries;
8857    }
8858
8859    private static boolean hasString(List<String> list, List<String> which) {
8860        if (list == null) {
8861            return false;
8862        }
8863        for (int i=list.size()-1; i>=0; i--) {
8864            for (int j=which.size()-1; j>=0; j--) {
8865                if (which.get(j).equals(list.get(i))) {
8866                    return true;
8867                }
8868            }
8869        }
8870        return false;
8871    }
8872
8873    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8874            PackageParser.Package changingPkg) {
8875        ArrayList<PackageParser.Package> res = null;
8876        for (PackageParser.Package pkg : mPackages.values()) {
8877            if (changingPkg != null
8878                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8879                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8880                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8881                            changingPkg.staticSharedLibName)) {
8882                return null;
8883            }
8884            if (res == null) {
8885                res = new ArrayList<>();
8886            }
8887            res.add(pkg);
8888            try {
8889                updateSharedLibrariesLPr(pkg, changingPkg);
8890            } catch (PackageManagerException e) {
8891                // If a system app update or an app and a required lib missing we
8892                // delete the package and for updated system apps keep the data as
8893                // it is better for the user to reinstall than to be in an limbo
8894                // state. Also libs disappearing under an app should never happen
8895                // - just in case.
8896                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8897                    final int flags = pkg.isUpdatedSystemApp()
8898                            ? PackageManager.DELETE_KEEP_DATA : 0;
8899                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8900                            flags , null, true, null);
8901                }
8902                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8903            }
8904        }
8905        return res;
8906    }
8907
8908    /**
8909     * Derive the value of the {@code cpuAbiOverride} based on the provided
8910     * value and an optional stored value from the package settings.
8911     */
8912    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8913        String cpuAbiOverride = null;
8914
8915        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8916            cpuAbiOverride = null;
8917        } else if (abiOverride != null) {
8918            cpuAbiOverride = abiOverride;
8919        } else if (settings != null) {
8920            cpuAbiOverride = settings.cpuAbiOverrideString;
8921        }
8922
8923        return cpuAbiOverride;
8924    }
8925
8926    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8927            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8928                    throws PackageManagerException {
8929        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8930        // If the package has children and this is the first dive in the function
8931        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8932        // whether all packages (parent and children) would be successfully scanned
8933        // before the actual scan since scanning mutates internal state and we want
8934        // to atomically install the package and its children.
8935        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8936            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8937                scanFlags |= SCAN_CHECK_ONLY;
8938            }
8939        } else {
8940            scanFlags &= ~SCAN_CHECK_ONLY;
8941        }
8942
8943        final PackageParser.Package scannedPkg;
8944        try {
8945            // Scan the parent
8946            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8947            // Scan the children
8948            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8949            for (int i = 0; i < childCount; i++) {
8950                PackageParser.Package childPkg = pkg.childPackages.get(i);
8951                scanPackageLI(childPkg, policyFlags,
8952                        scanFlags, currentTime, user);
8953            }
8954        } finally {
8955            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8956        }
8957
8958        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8959            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8960        }
8961
8962        return scannedPkg;
8963    }
8964
8965    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8966            int scanFlags, long currentTime, @Nullable UserHandle user)
8967                    throws PackageManagerException {
8968        boolean success = false;
8969        try {
8970            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8971                    currentTime, user);
8972            success = true;
8973            return res;
8974        } finally {
8975            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8976                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8977                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8978                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8979                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8980            }
8981        }
8982    }
8983
8984    /**
8985     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8986     */
8987    private static boolean apkHasCode(String fileName) {
8988        StrictJarFile jarFile = null;
8989        try {
8990            jarFile = new StrictJarFile(fileName,
8991                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8992            return jarFile.findEntry("classes.dex") != null;
8993        } catch (IOException ignore) {
8994        } finally {
8995            try {
8996                if (jarFile != null) {
8997                    jarFile.close();
8998                }
8999            } catch (IOException ignore) {}
9000        }
9001        return false;
9002    }
9003
9004    /**
9005     * Enforces code policy for the package. This ensures that if an APK has
9006     * declared hasCode="true" in its manifest that the APK actually contains
9007     * code.
9008     *
9009     * @throws PackageManagerException If bytecode could not be found when it should exist
9010     */
9011    private static void assertCodePolicy(PackageParser.Package pkg)
9012            throws PackageManagerException {
9013        final boolean shouldHaveCode =
9014                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9015        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9016            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9017                    "Package " + pkg.baseCodePath + " code is missing");
9018        }
9019
9020        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9021            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9022                final boolean splitShouldHaveCode =
9023                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9024                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9025                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9026                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9027                }
9028            }
9029        }
9030    }
9031
9032    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9033            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9034                    throws PackageManagerException {
9035        if (DEBUG_PACKAGE_SCANNING) {
9036            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9037                Log.d(TAG, "Scanning package " + pkg.packageName);
9038        }
9039
9040        applyPolicy(pkg, policyFlags);
9041
9042        assertPackageIsValid(pkg, policyFlags, scanFlags);
9043
9044        // Initialize package source and resource directories
9045        final File scanFile = new File(pkg.codePath);
9046        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9047        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9048
9049        SharedUserSetting suid = null;
9050        PackageSetting pkgSetting = null;
9051
9052        // Getting the package setting may have a side-effect, so if we
9053        // are only checking if scan would succeed, stash a copy of the
9054        // old setting to restore at the end.
9055        PackageSetting nonMutatedPs = null;
9056
9057        // We keep references to the derived CPU Abis from settings in oder to reuse
9058        // them in the case where we're not upgrading or booting for the first time.
9059        String primaryCpuAbiFromSettings = null;
9060        String secondaryCpuAbiFromSettings = null;
9061
9062        // writer
9063        synchronized (mPackages) {
9064            if (pkg.mSharedUserId != null) {
9065                // SIDE EFFECTS; may potentially allocate a new shared user
9066                suid = mSettings.getSharedUserLPw(
9067                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9068                if (DEBUG_PACKAGE_SCANNING) {
9069                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9070                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9071                                + "): packages=" + suid.packages);
9072                }
9073            }
9074
9075            // Check if we are renaming from an original package name.
9076            PackageSetting origPackage = null;
9077            String realName = null;
9078            if (pkg.mOriginalPackages != null) {
9079                // This package may need to be renamed to a previously
9080                // installed name.  Let's check on that...
9081                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9082                if (pkg.mOriginalPackages.contains(renamed)) {
9083                    // This package had originally been installed as the
9084                    // original name, and we have already taken care of
9085                    // transitioning to the new one.  Just update the new
9086                    // one to continue using the old name.
9087                    realName = pkg.mRealPackage;
9088                    if (!pkg.packageName.equals(renamed)) {
9089                        // Callers into this function may have already taken
9090                        // care of renaming the package; only do it here if
9091                        // it is not already done.
9092                        pkg.setPackageName(renamed);
9093                    }
9094                } else {
9095                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9096                        if ((origPackage = mSettings.getPackageLPr(
9097                                pkg.mOriginalPackages.get(i))) != null) {
9098                            // We do have the package already installed under its
9099                            // original name...  should we use it?
9100                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9101                                // New package is not compatible with original.
9102                                origPackage = null;
9103                                continue;
9104                            } else if (origPackage.sharedUser != null) {
9105                                // Make sure uid is compatible between packages.
9106                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9107                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9108                                            + " to " + pkg.packageName + ": old uid "
9109                                            + origPackage.sharedUser.name
9110                                            + " differs from " + pkg.mSharedUserId);
9111                                    origPackage = null;
9112                                    continue;
9113                                }
9114                                // TODO: Add case when shared user id is added [b/28144775]
9115                            } else {
9116                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9117                                        + pkg.packageName + " to old name " + origPackage.name);
9118                            }
9119                            break;
9120                        }
9121                    }
9122                }
9123            }
9124
9125            if (mTransferedPackages.contains(pkg.packageName)) {
9126                Slog.w(TAG, "Package " + pkg.packageName
9127                        + " was transferred to another, but its .apk remains");
9128            }
9129
9130            // See comments in nonMutatedPs declaration
9131            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9132                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9133                if (foundPs != null) {
9134                    nonMutatedPs = new PackageSetting(foundPs);
9135                }
9136            }
9137
9138            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9139                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9140                if (foundPs != null) {
9141                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9142                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9143                }
9144            }
9145
9146            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9147            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9148                PackageManagerService.reportSettingsProblem(Log.WARN,
9149                        "Package " + pkg.packageName + " shared user changed from "
9150                                + (pkgSetting.sharedUser != null
9151                                        ? pkgSetting.sharedUser.name : "<nothing>")
9152                                + " to "
9153                                + (suid != null ? suid.name : "<nothing>")
9154                                + "; replacing with new");
9155                pkgSetting = null;
9156            }
9157            final PackageSetting oldPkgSetting =
9158                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9159            final PackageSetting disabledPkgSetting =
9160                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9161
9162            String[] usesStaticLibraries = null;
9163            if (pkg.usesStaticLibraries != null) {
9164                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9165                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9166            }
9167
9168            if (pkgSetting == null) {
9169                final String parentPackageName = (pkg.parentPackage != null)
9170                        ? pkg.parentPackage.packageName : null;
9171                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9172                // REMOVE SharedUserSetting from method; update in a separate call
9173                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9174                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9175                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9176                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9177                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9178                        true /*allowInstall*/, instantApp, parentPackageName,
9179                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9180                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9181                // SIDE EFFECTS; updates system state; move elsewhere
9182                if (origPackage != null) {
9183                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9184                }
9185                mSettings.addUserToSettingLPw(pkgSetting);
9186            } else {
9187                // REMOVE SharedUserSetting from method; update in a separate call.
9188                //
9189                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9190                // secondaryCpuAbi are not known at this point so we always update them
9191                // to null here, only to reset them at a later point.
9192                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9193                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9194                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9195                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9196                        UserManagerService.getInstance(), usesStaticLibraries,
9197                        pkg.usesStaticLibrariesVersions);
9198            }
9199            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9200            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9201
9202            // SIDE EFFECTS; modifies system state; move elsewhere
9203            if (pkgSetting.origPackage != null) {
9204                // If we are first transitioning from an original package,
9205                // fix up the new package's name now.  We need to do this after
9206                // looking up the package under its new name, so getPackageLP
9207                // can take care of fiddling things correctly.
9208                pkg.setPackageName(origPackage.name);
9209
9210                // File a report about this.
9211                String msg = "New package " + pkgSetting.realName
9212                        + " renamed to replace old package " + pkgSetting.name;
9213                reportSettingsProblem(Log.WARN, msg);
9214
9215                // Make a note of it.
9216                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9217                    mTransferedPackages.add(origPackage.name);
9218                }
9219
9220                // No longer need to retain this.
9221                pkgSetting.origPackage = null;
9222            }
9223
9224            // SIDE EFFECTS; modifies system state; move elsewhere
9225            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9226                // Make a note of it.
9227                mTransferedPackages.add(pkg.packageName);
9228            }
9229
9230            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9231                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9232            }
9233
9234            if ((scanFlags & SCAN_BOOTING) == 0
9235                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9236                // Check all shared libraries and map to their actual file path.
9237                // We only do this here for apps not on a system dir, because those
9238                // are the only ones that can fail an install due to this.  We
9239                // will take care of the system apps by updating all of their
9240                // library paths after the scan is done. Also during the initial
9241                // scan don't update any libs as we do this wholesale after all
9242                // apps are scanned to avoid dependency based scanning.
9243                updateSharedLibrariesLPr(pkg, null);
9244            }
9245
9246            if (mFoundPolicyFile) {
9247                SELinuxMMAC.assignSeInfoValue(pkg);
9248            }
9249            pkg.applicationInfo.uid = pkgSetting.appId;
9250            pkg.mExtras = pkgSetting;
9251
9252
9253            // Static shared libs have same package with different versions where
9254            // we internally use a synthetic package name to allow multiple versions
9255            // of the same package, therefore we need to compare signatures against
9256            // the package setting for the latest library version.
9257            PackageSetting signatureCheckPs = pkgSetting;
9258            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9259                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9260                if (libraryEntry != null) {
9261                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9262                }
9263            }
9264
9265            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9266                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9267                    // We just determined the app is signed correctly, so bring
9268                    // over the latest parsed certs.
9269                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9270                } else {
9271                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9272                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9273                                "Package " + pkg.packageName + " upgrade keys do not match the "
9274                                + "previously installed version");
9275                    } else {
9276                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9277                        String msg = "System package " + pkg.packageName
9278                                + " signature changed; retaining data.";
9279                        reportSettingsProblem(Log.WARN, msg);
9280                    }
9281                }
9282            } else {
9283                try {
9284                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9285                    verifySignaturesLP(signatureCheckPs, pkg);
9286                    // We just determined the app is signed correctly, so bring
9287                    // over the latest parsed certs.
9288                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9289                } catch (PackageManagerException e) {
9290                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9291                        throw e;
9292                    }
9293                    // The signature has changed, but this package is in the system
9294                    // image...  let's recover!
9295                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9296                    // However...  if this package is part of a shared user, but it
9297                    // doesn't match the signature of the shared user, let's fail.
9298                    // What this means is that you can't change the signatures
9299                    // associated with an overall shared user, which doesn't seem all
9300                    // that unreasonable.
9301                    if (signatureCheckPs.sharedUser != null) {
9302                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9303                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9304                            throw new PackageManagerException(
9305                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9306                                    "Signature mismatch for shared user: "
9307                                            + pkgSetting.sharedUser);
9308                        }
9309                    }
9310                    // File a report about this.
9311                    String msg = "System package " + pkg.packageName
9312                            + " signature changed; retaining data.";
9313                    reportSettingsProblem(Log.WARN, msg);
9314                }
9315            }
9316
9317            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9318                // This package wants to adopt ownership of permissions from
9319                // another package.
9320                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9321                    final String origName = pkg.mAdoptPermissions.get(i);
9322                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9323                    if (orig != null) {
9324                        if (verifyPackageUpdateLPr(orig, pkg)) {
9325                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9326                                    + pkg.packageName);
9327                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9328                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9329                        }
9330                    }
9331                }
9332            }
9333        }
9334
9335        pkg.applicationInfo.processName = fixProcessName(
9336                pkg.applicationInfo.packageName,
9337                pkg.applicationInfo.processName);
9338
9339        if (pkg != mPlatformPackage) {
9340            // Get all of our default paths setup
9341            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9342        }
9343
9344        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9345
9346        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9347            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9348                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9349                derivePackageAbi(
9350                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9351                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9352
9353                // Some system apps still use directory structure for native libraries
9354                // in which case we might end up not detecting abi solely based on apk
9355                // structure. Try to detect abi based on directory structure.
9356                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9357                        pkg.applicationInfo.primaryCpuAbi == null) {
9358                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9359                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9360                }
9361            } else {
9362                // This is not a first boot or an upgrade, don't bother deriving the
9363                // ABI during the scan. Instead, trust the value that was stored in the
9364                // package setting.
9365                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9366                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9367
9368                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9369
9370                if (DEBUG_ABI_SELECTION) {
9371                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9372                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9373                        pkg.applicationInfo.secondaryCpuAbi);
9374                }
9375            }
9376        } else {
9377            if ((scanFlags & SCAN_MOVE) != 0) {
9378                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9379                // but we already have this packages package info in the PackageSetting. We just
9380                // use that and derive the native library path based on the new codepath.
9381                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9382                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9383            }
9384
9385            // Set native library paths again. For moves, the path will be updated based on the
9386            // ABIs we've determined above. For non-moves, the path will be updated based on the
9387            // ABIs we determined during compilation, but the path will depend on the final
9388            // package path (after the rename away from the stage path).
9389            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9390        }
9391
9392        // This is a special case for the "system" package, where the ABI is
9393        // dictated by the zygote configuration (and init.rc). We should keep track
9394        // of this ABI so that we can deal with "normal" applications that run under
9395        // the same UID correctly.
9396        if (mPlatformPackage == pkg) {
9397            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9398                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9399        }
9400
9401        // If there's a mismatch between the abi-override in the package setting
9402        // and the abiOverride specified for the install. Warn about this because we
9403        // would've already compiled the app without taking the package setting into
9404        // account.
9405        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9406            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9407                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9408                        " for package " + pkg.packageName);
9409            }
9410        }
9411
9412        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9413        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9414        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9415
9416        // Copy the derived override back to the parsed package, so that we can
9417        // update the package settings accordingly.
9418        pkg.cpuAbiOverride = cpuAbiOverride;
9419
9420        if (DEBUG_ABI_SELECTION) {
9421            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9422                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9423                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9424        }
9425
9426        // Push the derived path down into PackageSettings so we know what to
9427        // clean up at uninstall time.
9428        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9429
9430        if (DEBUG_ABI_SELECTION) {
9431            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9432                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9433                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9434        }
9435
9436        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9437        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9438            // We don't do this here during boot because we can do it all
9439            // at once after scanning all existing packages.
9440            //
9441            // We also do this *before* we perform dexopt on this package, so that
9442            // we can avoid redundant dexopts, and also to make sure we've got the
9443            // code and package path correct.
9444            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9445        }
9446
9447        if (mFactoryTest && pkg.requestedPermissions.contains(
9448                android.Manifest.permission.FACTORY_TEST)) {
9449            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9450        }
9451
9452        if (isSystemApp(pkg)) {
9453            pkgSetting.isOrphaned = true;
9454        }
9455
9456        // Take care of first install / last update times.
9457        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9458        if (currentTime != 0) {
9459            if (pkgSetting.firstInstallTime == 0) {
9460                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9461            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9462                pkgSetting.lastUpdateTime = currentTime;
9463            }
9464        } else if (pkgSetting.firstInstallTime == 0) {
9465            // We need *something*.  Take time time stamp of the file.
9466            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9467        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9468            if (scanFileTime != pkgSetting.timeStamp) {
9469                // A package on the system image has changed; consider this
9470                // to be an update.
9471                pkgSetting.lastUpdateTime = scanFileTime;
9472            }
9473        }
9474        pkgSetting.setTimeStamp(scanFileTime);
9475
9476        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9477            if (nonMutatedPs != null) {
9478                synchronized (mPackages) {
9479                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9480                }
9481            }
9482        } else {
9483            final int userId = user == null ? 0 : user.getIdentifier();
9484            // Modify state for the given package setting
9485            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9486                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9487            if (pkgSetting.getInstantApp(userId)) {
9488                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9489            }
9490        }
9491        return pkg;
9492    }
9493
9494    /**
9495     * Applies policy to the parsed package based upon the given policy flags.
9496     * Ensures the package is in a good state.
9497     * <p>
9498     * Implementation detail: This method must NOT have any side effect. It would
9499     * ideally be static, but, it requires locks to read system state.
9500     */
9501    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9502        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9503            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9504            if (pkg.applicationInfo.isDirectBootAware()) {
9505                // we're direct boot aware; set for all components
9506                for (PackageParser.Service s : pkg.services) {
9507                    s.info.encryptionAware = s.info.directBootAware = true;
9508                }
9509                for (PackageParser.Provider p : pkg.providers) {
9510                    p.info.encryptionAware = p.info.directBootAware = true;
9511                }
9512                for (PackageParser.Activity a : pkg.activities) {
9513                    a.info.encryptionAware = a.info.directBootAware = true;
9514                }
9515                for (PackageParser.Activity r : pkg.receivers) {
9516                    r.info.encryptionAware = r.info.directBootAware = true;
9517                }
9518            }
9519        } else {
9520            // Only allow system apps to be flagged as core apps.
9521            pkg.coreApp = false;
9522            // clear flags not applicable to regular apps
9523            pkg.applicationInfo.privateFlags &=
9524                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9525            pkg.applicationInfo.privateFlags &=
9526                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9527        }
9528        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9529
9530        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9531            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9532        }
9533
9534        if (!isSystemApp(pkg)) {
9535            // Only system apps can use these features.
9536            pkg.mOriginalPackages = null;
9537            pkg.mRealPackage = null;
9538            pkg.mAdoptPermissions = null;
9539        }
9540    }
9541
9542    /**
9543     * Asserts the parsed package is valid according to the given policy. If the
9544     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9545     * <p>
9546     * Implementation detail: This method must NOT have any side effects. It would
9547     * ideally be static, but, it requires locks to read system state.
9548     *
9549     * @throws PackageManagerException If the package fails any of the validation checks
9550     */
9551    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9552            throws PackageManagerException {
9553        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9554            assertCodePolicy(pkg);
9555        }
9556
9557        if (pkg.applicationInfo.getCodePath() == null ||
9558                pkg.applicationInfo.getResourcePath() == null) {
9559            // Bail out. The resource and code paths haven't been set.
9560            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9561                    "Code and resource paths haven't been set correctly");
9562        }
9563
9564        // Make sure we're not adding any bogus keyset info
9565        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9566        ksms.assertScannedPackageValid(pkg);
9567
9568        synchronized (mPackages) {
9569            // The special "android" package can only be defined once
9570            if (pkg.packageName.equals("android")) {
9571                if (mAndroidApplication != null) {
9572                    Slog.w(TAG, "*************************************************");
9573                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9574                    Slog.w(TAG, " codePath=" + pkg.codePath);
9575                    Slog.w(TAG, "*************************************************");
9576                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9577                            "Core android package being redefined.  Skipping.");
9578                }
9579            }
9580
9581            // A package name must be unique; don't allow duplicates
9582            if (mPackages.containsKey(pkg.packageName)) {
9583                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9584                        "Application package " + pkg.packageName
9585                        + " already installed.  Skipping duplicate.");
9586            }
9587
9588            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9589                // Static libs have a synthetic package name containing the version
9590                // but we still want the base name to be unique.
9591                if (mPackages.containsKey(pkg.manifestPackageName)) {
9592                    throw new PackageManagerException(
9593                            "Duplicate static shared lib provider package");
9594                }
9595
9596                // Static shared libraries should have at least O target SDK
9597                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9598                    throw new PackageManagerException(
9599                            "Packages declaring static-shared libs must target O SDK or higher");
9600                }
9601
9602                // Package declaring static a shared lib cannot be instant apps
9603                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9604                    throw new PackageManagerException(
9605                            "Packages declaring static-shared libs cannot be instant apps");
9606                }
9607
9608                // Package declaring static a shared lib cannot be renamed since the package
9609                // name is synthetic and apps can't code around package manager internals.
9610                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9611                    throw new PackageManagerException(
9612                            "Packages declaring static-shared libs cannot be renamed");
9613                }
9614
9615                // Package declaring static a shared lib cannot declare child packages
9616                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9617                    throw new PackageManagerException(
9618                            "Packages declaring static-shared libs cannot have child packages");
9619                }
9620
9621                // Package declaring static a shared lib cannot declare dynamic libs
9622                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9623                    throw new PackageManagerException(
9624                            "Packages declaring static-shared libs cannot declare dynamic libs");
9625                }
9626
9627                // Package declaring static a shared lib cannot declare shared users
9628                if (pkg.mSharedUserId != null) {
9629                    throw new PackageManagerException(
9630                            "Packages declaring static-shared libs cannot declare shared users");
9631                }
9632
9633                // Static shared libs cannot declare activities
9634                if (!pkg.activities.isEmpty()) {
9635                    throw new PackageManagerException(
9636                            "Static shared libs cannot declare activities");
9637                }
9638
9639                // Static shared libs cannot declare services
9640                if (!pkg.services.isEmpty()) {
9641                    throw new PackageManagerException(
9642                            "Static shared libs cannot declare services");
9643                }
9644
9645                // Static shared libs cannot declare providers
9646                if (!pkg.providers.isEmpty()) {
9647                    throw new PackageManagerException(
9648                            "Static shared libs cannot declare content providers");
9649                }
9650
9651                // Static shared libs cannot declare receivers
9652                if (!pkg.receivers.isEmpty()) {
9653                    throw new PackageManagerException(
9654                            "Static shared libs cannot declare broadcast receivers");
9655                }
9656
9657                // Static shared libs cannot declare permission groups
9658                if (!pkg.permissionGroups.isEmpty()) {
9659                    throw new PackageManagerException(
9660                            "Static shared libs cannot declare permission groups");
9661                }
9662
9663                // Static shared libs cannot declare permissions
9664                if (!pkg.permissions.isEmpty()) {
9665                    throw new PackageManagerException(
9666                            "Static shared libs cannot declare permissions");
9667                }
9668
9669                // Static shared libs cannot declare protected broadcasts
9670                if (pkg.protectedBroadcasts != null) {
9671                    throw new PackageManagerException(
9672                            "Static shared libs cannot declare protected broadcasts");
9673                }
9674
9675                // Static shared libs cannot be overlay targets
9676                if (pkg.mOverlayTarget != null) {
9677                    throw new PackageManagerException(
9678                            "Static shared libs cannot be overlay targets");
9679                }
9680
9681                // The version codes must be ordered as lib versions
9682                int minVersionCode = Integer.MIN_VALUE;
9683                int maxVersionCode = Integer.MAX_VALUE;
9684
9685                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9686                        pkg.staticSharedLibName);
9687                if (versionedLib != null) {
9688                    final int versionCount = versionedLib.size();
9689                    for (int i = 0; i < versionCount; i++) {
9690                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9691                        // TODO: We will change version code to long, so in the new API it is long
9692                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9693                                .getVersionCode();
9694                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9695                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9696                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9697                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9698                        } else {
9699                            minVersionCode = maxVersionCode = libVersionCode;
9700                            break;
9701                        }
9702                    }
9703                }
9704                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9705                    throw new PackageManagerException("Static shared"
9706                            + " lib version codes must be ordered as lib versions");
9707                }
9708            }
9709
9710            // Only privileged apps and updated privileged apps can add child packages.
9711            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9712                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9713                    throw new PackageManagerException("Only privileged apps can add child "
9714                            + "packages. Ignoring package " + pkg.packageName);
9715                }
9716                final int childCount = pkg.childPackages.size();
9717                for (int i = 0; i < childCount; i++) {
9718                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9719                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9720                            childPkg.packageName)) {
9721                        throw new PackageManagerException("Can't override child of "
9722                                + "another disabled app. Ignoring package " + pkg.packageName);
9723                    }
9724                }
9725            }
9726
9727            // If we're only installing presumed-existing packages, require that the
9728            // scanned APK is both already known and at the path previously established
9729            // for it.  Previously unknown packages we pick up normally, but if we have an
9730            // a priori expectation about this package's install presence, enforce it.
9731            // With a singular exception for new system packages. When an OTA contains
9732            // a new system package, we allow the codepath to change from a system location
9733            // to the user-installed location. If we don't allow this change, any newer,
9734            // user-installed version of the application will be ignored.
9735            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9736                if (mExpectingBetter.containsKey(pkg.packageName)) {
9737                    logCriticalInfo(Log.WARN,
9738                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9739                } else {
9740                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9741                    if (known != null) {
9742                        if (DEBUG_PACKAGE_SCANNING) {
9743                            Log.d(TAG, "Examining " + pkg.codePath
9744                                    + " and requiring known paths " + known.codePathString
9745                                    + " & " + known.resourcePathString);
9746                        }
9747                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9748                                || !pkg.applicationInfo.getResourcePath().equals(
9749                                        known.resourcePathString)) {
9750                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9751                                    "Application package " + pkg.packageName
9752                                    + " found at " + pkg.applicationInfo.getCodePath()
9753                                    + " but expected at " + known.codePathString
9754                                    + "; ignoring.");
9755                        }
9756                    }
9757                }
9758            }
9759
9760            // Verify that this new package doesn't have any content providers
9761            // that conflict with existing packages.  Only do this if the
9762            // package isn't already installed, since we don't want to break
9763            // things that are installed.
9764            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9765                final int N = pkg.providers.size();
9766                int i;
9767                for (i=0; i<N; i++) {
9768                    PackageParser.Provider p = pkg.providers.get(i);
9769                    if (p.info.authority != null) {
9770                        String names[] = p.info.authority.split(";");
9771                        for (int j = 0; j < names.length; j++) {
9772                            if (mProvidersByAuthority.containsKey(names[j])) {
9773                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9774                                final String otherPackageName =
9775                                        ((other != null && other.getComponentName() != null) ?
9776                                                other.getComponentName().getPackageName() : "?");
9777                                throw new PackageManagerException(
9778                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9779                                        "Can't install because provider name " + names[j]
9780                                                + " (in package " + pkg.applicationInfo.packageName
9781                                                + ") is already used by " + otherPackageName);
9782                            }
9783                        }
9784                    }
9785                }
9786            }
9787        }
9788    }
9789
9790    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9791            int type, String declaringPackageName, int declaringVersionCode) {
9792        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9793        if (versionedLib == null) {
9794            versionedLib = new SparseArray<>();
9795            mSharedLibraries.put(name, versionedLib);
9796            if (type == SharedLibraryInfo.TYPE_STATIC) {
9797                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9798            }
9799        } else if (versionedLib.indexOfKey(version) >= 0) {
9800            return false;
9801        }
9802        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9803                version, type, declaringPackageName, declaringVersionCode);
9804        versionedLib.put(version, libEntry);
9805        return true;
9806    }
9807
9808    private boolean removeSharedLibraryLPw(String name, int version) {
9809        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9810        if (versionedLib == null) {
9811            return false;
9812        }
9813        final int libIdx = versionedLib.indexOfKey(version);
9814        if (libIdx < 0) {
9815            return false;
9816        }
9817        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9818        versionedLib.remove(version);
9819        if (versionedLib.size() <= 0) {
9820            mSharedLibraries.remove(name);
9821            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9822                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9823                        .getPackageName());
9824            }
9825        }
9826        return true;
9827    }
9828
9829    /**
9830     * Adds a scanned package to the system. When this method is finished, the package will
9831     * be available for query, resolution, etc...
9832     */
9833    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9834            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9835        final String pkgName = pkg.packageName;
9836        if (mCustomResolverComponentName != null &&
9837                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9838            setUpCustomResolverActivity(pkg);
9839        }
9840
9841        if (pkg.packageName.equals("android")) {
9842            synchronized (mPackages) {
9843                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9844                    // Set up information for our fall-back user intent resolution activity.
9845                    mPlatformPackage = pkg;
9846                    pkg.mVersionCode = mSdkVersion;
9847                    mAndroidApplication = pkg.applicationInfo;
9848                    if (!mResolverReplaced) {
9849                        mResolveActivity.applicationInfo = mAndroidApplication;
9850                        mResolveActivity.name = ResolverActivity.class.getName();
9851                        mResolveActivity.packageName = mAndroidApplication.packageName;
9852                        mResolveActivity.processName = "system:ui";
9853                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9854                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9855                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9856                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9857                        mResolveActivity.exported = true;
9858                        mResolveActivity.enabled = true;
9859                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9860                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9861                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9862                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9863                                | ActivityInfo.CONFIG_ORIENTATION
9864                                | ActivityInfo.CONFIG_KEYBOARD
9865                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9866                        mResolveInfo.activityInfo = mResolveActivity;
9867                        mResolveInfo.priority = 0;
9868                        mResolveInfo.preferredOrder = 0;
9869                        mResolveInfo.match = 0;
9870                        mResolveComponentName = new ComponentName(
9871                                mAndroidApplication.packageName, mResolveActivity.name);
9872                    }
9873                }
9874            }
9875        }
9876
9877        ArrayList<PackageParser.Package> clientLibPkgs = null;
9878        // writer
9879        synchronized (mPackages) {
9880            boolean hasStaticSharedLibs = false;
9881
9882            // Any app can add new static shared libraries
9883            if (pkg.staticSharedLibName != null) {
9884                // Static shared libs don't allow renaming as they have synthetic package
9885                // names to allow install of multiple versions, so use name from manifest.
9886                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9887                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9888                        pkg.manifestPackageName, pkg.mVersionCode)) {
9889                    hasStaticSharedLibs = true;
9890                } else {
9891                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9892                                + pkg.staticSharedLibName + " already exists; skipping");
9893                }
9894                // Static shared libs cannot be updated once installed since they
9895                // use synthetic package name which includes the version code, so
9896                // not need to update other packages's shared lib dependencies.
9897            }
9898
9899            if (!hasStaticSharedLibs
9900                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9901                // Only system apps can add new dynamic shared libraries.
9902                if (pkg.libraryNames != null) {
9903                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9904                        String name = pkg.libraryNames.get(i);
9905                        boolean allowed = false;
9906                        if (pkg.isUpdatedSystemApp()) {
9907                            // New library entries can only be added through the
9908                            // system image.  This is important to get rid of a lot
9909                            // of nasty edge cases: for example if we allowed a non-
9910                            // system update of the app to add a library, then uninstalling
9911                            // the update would make the library go away, and assumptions
9912                            // we made such as through app install filtering would now
9913                            // have allowed apps on the device which aren't compatible
9914                            // with it.  Better to just have the restriction here, be
9915                            // conservative, and create many fewer cases that can negatively
9916                            // impact the user experience.
9917                            final PackageSetting sysPs = mSettings
9918                                    .getDisabledSystemPkgLPr(pkg.packageName);
9919                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9920                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9921                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9922                                        allowed = true;
9923                                        break;
9924                                    }
9925                                }
9926                            }
9927                        } else {
9928                            allowed = true;
9929                        }
9930                        if (allowed) {
9931                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9932                                    SharedLibraryInfo.VERSION_UNDEFINED,
9933                                    SharedLibraryInfo.TYPE_DYNAMIC,
9934                                    pkg.packageName, pkg.mVersionCode)) {
9935                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9936                                        + name + " already exists; skipping");
9937                            }
9938                        } else {
9939                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9940                                    + name + " that is not declared on system image; skipping");
9941                        }
9942                    }
9943
9944                    if ((scanFlags & SCAN_BOOTING) == 0) {
9945                        // If we are not booting, we need to update any applications
9946                        // that are clients of our shared library.  If we are booting,
9947                        // this will all be done once the scan is complete.
9948                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9949                    }
9950                }
9951            }
9952        }
9953
9954        if ((scanFlags & SCAN_BOOTING) != 0) {
9955            // No apps can run during boot scan, so they don't need to be frozen
9956        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9957            // Caller asked to not kill app, so it's probably not frozen
9958        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9959            // Caller asked us to ignore frozen check for some reason; they
9960            // probably didn't know the package name
9961        } else {
9962            // We're doing major surgery on this package, so it better be frozen
9963            // right now to keep it from launching
9964            checkPackageFrozen(pkgName);
9965        }
9966
9967        // Also need to kill any apps that are dependent on the library.
9968        if (clientLibPkgs != null) {
9969            for (int i=0; i<clientLibPkgs.size(); i++) {
9970                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9971                killApplication(clientPkg.applicationInfo.packageName,
9972                        clientPkg.applicationInfo.uid, "update lib");
9973            }
9974        }
9975
9976        // writer
9977        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9978
9979        synchronized (mPackages) {
9980            // We don't expect installation to fail beyond this point
9981
9982            // Add the new setting to mSettings
9983            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9984            // Add the new setting to mPackages
9985            mPackages.put(pkg.applicationInfo.packageName, pkg);
9986            // Make sure we don't accidentally delete its data.
9987            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9988            while (iter.hasNext()) {
9989                PackageCleanItem item = iter.next();
9990                if (pkgName.equals(item.packageName)) {
9991                    iter.remove();
9992                }
9993            }
9994
9995            // Add the package's KeySets to the global KeySetManagerService
9996            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9997            ksms.addScannedPackageLPw(pkg);
9998
9999            int N = pkg.providers.size();
10000            StringBuilder r = null;
10001            int i;
10002            for (i=0; i<N; i++) {
10003                PackageParser.Provider p = pkg.providers.get(i);
10004                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10005                        p.info.processName);
10006                mProviders.addProvider(p);
10007                p.syncable = p.info.isSyncable;
10008                if (p.info.authority != null) {
10009                    String names[] = p.info.authority.split(";");
10010                    p.info.authority = null;
10011                    for (int j = 0; j < names.length; j++) {
10012                        if (j == 1 && p.syncable) {
10013                            // We only want the first authority for a provider to possibly be
10014                            // syncable, so if we already added this provider using a different
10015                            // authority clear the syncable flag. We copy the provider before
10016                            // changing it because the mProviders object contains a reference
10017                            // to a provider that we don't want to change.
10018                            // Only do this for the second authority since the resulting provider
10019                            // object can be the same for all future authorities for this provider.
10020                            p = new PackageParser.Provider(p);
10021                            p.syncable = false;
10022                        }
10023                        if (!mProvidersByAuthority.containsKey(names[j])) {
10024                            mProvidersByAuthority.put(names[j], p);
10025                            if (p.info.authority == null) {
10026                                p.info.authority = names[j];
10027                            } else {
10028                                p.info.authority = p.info.authority + ";" + names[j];
10029                            }
10030                            if (DEBUG_PACKAGE_SCANNING) {
10031                                if (chatty)
10032                                    Log.d(TAG, "Registered content provider: " + names[j]
10033                                            + ", className = " + p.info.name + ", isSyncable = "
10034                                            + p.info.isSyncable);
10035                            }
10036                        } else {
10037                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10038                            Slog.w(TAG, "Skipping provider name " + names[j] +
10039                                    " (in package " + pkg.applicationInfo.packageName +
10040                                    "): name already used by "
10041                                    + ((other != null && other.getComponentName() != null)
10042                                            ? other.getComponentName().getPackageName() : "?"));
10043                        }
10044                    }
10045                }
10046                if (chatty) {
10047                    if (r == null) {
10048                        r = new StringBuilder(256);
10049                    } else {
10050                        r.append(' ');
10051                    }
10052                    r.append(p.info.name);
10053                }
10054            }
10055            if (r != null) {
10056                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10057            }
10058
10059            N = pkg.services.size();
10060            r = null;
10061            for (i=0; i<N; i++) {
10062                PackageParser.Service s = pkg.services.get(i);
10063                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10064                        s.info.processName);
10065                mServices.addService(s);
10066                if (chatty) {
10067                    if (r == null) {
10068                        r = new StringBuilder(256);
10069                    } else {
10070                        r.append(' ');
10071                    }
10072                    r.append(s.info.name);
10073                }
10074            }
10075            if (r != null) {
10076                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10077            }
10078
10079            N = pkg.receivers.size();
10080            r = null;
10081            for (i=0; i<N; i++) {
10082                PackageParser.Activity a = pkg.receivers.get(i);
10083                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10084                        a.info.processName);
10085                mReceivers.addActivity(a, "receiver");
10086                if (chatty) {
10087                    if (r == null) {
10088                        r = new StringBuilder(256);
10089                    } else {
10090                        r.append(' ');
10091                    }
10092                    r.append(a.info.name);
10093                }
10094            }
10095            if (r != null) {
10096                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10097            }
10098
10099            N = pkg.activities.size();
10100            r = null;
10101            for (i=0; i<N; i++) {
10102                PackageParser.Activity a = pkg.activities.get(i);
10103                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10104                        a.info.processName);
10105                mActivities.addActivity(a, "activity");
10106                if (chatty) {
10107                    if (r == null) {
10108                        r = new StringBuilder(256);
10109                    } else {
10110                        r.append(' ');
10111                    }
10112                    r.append(a.info.name);
10113                }
10114            }
10115            if (r != null) {
10116                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10117            }
10118
10119            N = pkg.permissionGroups.size();
10120            r = null;
10121            for (i=0; i<N; i++) {
10122                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10123                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10124                final String curPackageName = cur == null ? null : cur.info.packageName;
10125                // Dont allow ephemeral apps to define new permission groups.
10126                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10127                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10128                            + pg.info.packageName
10129                            + " ignored: instant apps cannot define new permission groups.");
10130                    continue;
10131                }
10132                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10133                if (cur == null || isPackageUpdate) {
10134                    mPermissionGroups.put(pg.info.name, pg);
10135                    if (chatty) {
10136                        if (r == null) {
10137                            r = new StringBuilder(256);
10138                        } else {
10139                            r.append(' ');
10140                        }
10141                        if (isPackageUpdate) {
10142                            r.append("UPD:");
10143                        }
10144                        r.append(pg.info.name);
10145                    }
10146                } else {
10147                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10148                            + pg.info.packageName + " ignored: original from "
10149                            + cur.info.packageName);
10150                    if (chatty) {
10151                        if (r == null) {
10152                            r = new StringBuilder(256);
10153                        } else {
10154                            r.append(' ');
10155                        }
10156                        r.append("DUP:");
10157                        r.append(pg.info.name);
10158                    }
10159                }
10160            }
10161            if (r != null) {
10162                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10163            }
10164
10165            N = pkg.permissions.size();
10166            r = null;
10167            for (i=0; i<N; i++) {
10168                PackageParser.Permission p = pkg.permissions.get(i);
10169
10170                // Dont allow ephemeral apps to define new permissions.
10171                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10172                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10173                            + p.info.packageName
10174                            + " ignored: instant apps cannot define new permissions.");
10175                    continue;
10176                }
10177
10178                // Assume by default that we did not install this permission into the system.
10179                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10180
10181                // Now that permission groups have a special meaning, we ignore permission
10182                // groups for legacy apps to prevent unexpected behavior. In particular,
10183                // permissions for one app being granted to someone just becase they happen
10184                // to be in a group defined by another app (before this had no implications).
10185                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10186                    p.group = mPermissionGroups.get(p.info.group);
10187                    // Warn for a permission in an unknown group.
10188                    if (p.info.group != null && p.group == null) {
10189                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10190                                + p.info.packageName + " in an unknown group " + p.info.group);
10191                    }
10192                }
10193
10194                ArrayMap<String, BasePermission> permissionMap =
10195                        p.tree ? mSettings.mPermissionTrees
10196                                : mSettings.mPermissions;
10197                BasePermission bp = permissionMap.get(p.info.name);
10198
10199                // Allow system apps to redefine non-system permissions
10200                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10201                    final boolean currentOwnerIsSystem = (bp.perm != null
10202                            && isSystemApp(bp.perm.owner));
10203                    if (isSystemApp(p.owner)) {
10204                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10205                            // It's a built-in permission and no owner, take ownership now
10206                            bp.packageSetting = pkgSetting;
10207                            bp.perm = p;
10208                            bp.uid = pkg.applicationInfo.uid;
10209                            bp.sourcePackage = p.info.packageName;
10210                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10211                        } else if (!currentOwnerIsSystem) {
10212                            String msg = "New decl " + p.owner + " of permission  "
10213                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10214                            reportSettingsProblem(Log.WARN, msg);
10215                            bp = null;
10216                        }
10217                    }
10218                }
10219
10220                if (bp == null) {
10221                    bp = new BasePermission(p.info.name, p.info.packageName,
10222                            BasePermission.TYPE_NORMAL);
10223                    permissionMap.put(p.info.name, bp);
10224                }
10225
10226                if (bp.perm == null) {
10227                    if (bp.sourcePackage == null
10228                            || bp.sourcePackage.equals(p.info.packageName)) {
10229                        BasePermission tree = findPermissionTreeLP(p.info.name);
10230                        if (tree == null
10231                                || tree.sourcePackage.equals(p.info.packageName)) {
10232                            bp.packageSetting = pkgSetting;
10233                            bp.perm = p;
10234                            bp.uid = pkg.applicationInfo.uid;
10235                            bp.sourcePackage = p.info.packageName;
10236                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10237                            if (chatty) {
10238                                if (r == null) {
10239                                    r = new StringBuilder(256);
10240                                } else {
10241                                    r.append(' ');
10242                                }
10243                                r.append(p.info.name);
10244                            }
10245                        } else {
10246                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10247                                    + p.info.packageName + " ignored: base tree "
10248                                    + tree.name + " is from package "
10249                                    + tree.sourcePackage);
10250                        }
10251                    } else {
10252                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10253                                + p.info.packageName + " ignored: original from "
10254                                + bp.sourcePackage);
10255                    }
10256                } else if (chatty) {
10257                    if (r == null) {
10258                        r = new StringBuilder(256);
10259                    } else {
10260                        r.append(' ');
10261                    }
10262                    r.append("DUP:");
10263                    r.append(p.info.name);
10264                }
10265                if (bp.perm == p) {
10266                    bp.protectionLevel = p.info.protectionLevel;
10267                }
10268            }
10269
10270            if (r != null) {
10271                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10272            }
10273
10274            N = pkg.instrumentation.size();
10275            r = null;
10276            for (i=0; i<N; i++) {
10277                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10278                a.info.packageName = pkg.applicationInfo.packageName;
10279                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10280                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10281                a.info.splitNames = pkg.splitNames;
10282                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10283                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10284                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10285                a.info.dataDir = pkg.applicationInfo.dataDir;
10286                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10287                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10288                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10289                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10290                mInstrumentation.put(a.getComponentName(), a);
10291                if (chatty) {
10292                    if (r == null) {
10293                        r = new StringBuilder(256);
10294                    } else {
10295                        r.append(' ');
10296                    }
10297                    r.append(a.info.name);
10298                }
10299            }
10300            if (r != null) {
10301                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10302            }
10303
10304            if (pkg.protectedBroadcasts != null) {
10305                N = pkg.protectedBroadcasts.size();
10306                for (i=0; i<N; i++) {
10307                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10308                }
10309            }
10310        }
10311
10312        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10313    }
10314
10315    /**
10316     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10317     * is derived purely on the basis of the contents of {@code scanFile} and
10318     * {@code cpuAbiOverride}.
10319     *
10320     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10321     */
10322    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10323                                 String cpuAbiOverride, boolean extractLibs,
10324                                 File appLib32InstallDir)
10325            throws PackageManagerException {
10326        // Give ourselves some initial paths; we'll come back for another
10327        // pass once we've determined ABI below.
10328        setNativeLibraryPaths(pkg, appLib32InstallDir);
10329
10330        // We would never need to extract libs for forward-locked and external packages,
10331        // since the container service will do it for us. We shouldn't attempt to
10332        // extract libs from system app when it was not updated.
10333        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10334                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10335            extractLibs = false;
10336        }
10337
10338        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10339        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10340
10341        NativeLibraryHelper.Handle handle = null;
10342        try {
10343            handle = NativeLibraryHelper.Handle.create(pkg);
10344            // TODO(multiArch): This can be null for apps that didn't go through the
10345            // usual installation process. We can calculate it again, like we
10346            // do during install time.
10347            //
10348            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10349            // unnecessary.
10350            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10351
10352            // Null out the abis so that they can be recalculated.
10353            pkg.applicationInfo.primaryCpuAbi = null;
10354            pkg.applicationInfo.secondaryCpuAbi = null;
10355            if (isMultiArch(pkg.applicationInfo)) {
10356                // Warn if we've set an abiOverride for multi-lib packages..
10357                // By definition, we need to copy both 32 and 64 bit libraries for
10358                // such packages.
10359                if (pkg.cpuAbiOverride != null
10360                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10361                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10362                }
10363
10364                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10365                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10366                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10367                    if (extractLibs) {
10368                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10369                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10370                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10371                                useIsaSpecificSubdirs);
10372                    } else {
10373                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10374                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10375                    }
10376                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10377                }
10378
10379                maybeThrowExceptionForMultiArchCopy(
10380                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10381
10382                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10383                    if (extractLibs) {
10384                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10385                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10386                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10387                                useIsaSpecificSubdirs);
10388                    } else {
10389                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10390                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10391                    }
10392                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10393                }
10394
10395                maybeThrowExceptionForMultiArchCopy(
10396                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10397
10398                if (abi64 >= 0) {
10399                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10400                }
10401
10402                if (abi32 >= 0) {
10403                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10404                    if (abi64 >= 0) {
10405                        if (pkg.use32bitAbi) {
10406                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10407                            pkg.applicationInfo.primaryCpuAbi = abi;
10408                        } else {
10409                            pkg.applicationInfo.secondaryCpuAbi = abi;
10410                        }
10411                    } else {
10412                        pkg.applicationInfo.primaryCpuAbi = abi;
10413                    }
10414                }
10415
10416            } else {
10417                String[] abiList = (cpuAbiOverride != null) ?
10418                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10419
10420                // Enable gross and lame hacks for apps that are built with old
10421                // SDK tools. We must scan their APKs for renderscript bitcode and
10422                // not launch them if it's present. Don't bother checking on devices
10423                // that don't have 64 bit support.
10424                boolean needsRenderScriptOverride = false;
10425                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10426                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10427                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10428                    needsRenderScriptOverride = true;
10429                }
10430
10431                final int copyRet;
10432                if (extractLibs) {
10433                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10434                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10435                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10436                } else {
10437                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10438                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10439                }
10440                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10441
10442                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10443                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10444                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10445                }
10446
10447                if (copyRet >= 0) {
10448                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10449                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10450                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10451                } else if (needsRenderScriptOverride) {
10452                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10453                }
10454            }
10455        } catch (IOException ioe) {
10456            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10457        } finally {
10458            IoUtils.closeQuietly(handle);
10459        }
10460
10461        // Now that we've calculated the ABIs and determined if it's an internal app,
10462        // we will go ahead and populate the nativeLibraryPath.
10463        setNativeLibraryPaths(pkg, appLib32InstallDir);
10464    }
10465
10466    /**
10467     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10468     * i.e, so that all packages can be run inside a single process if required.
10469     *
10470     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10471     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10472     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10473     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10474     * updating a package that belongs to a shared user.
10475     *
10476     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10477     * adds unnecessary complexity.
10478     */
10479    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10480            PackageParser.Package scannedPackage) {
10481        String requiredInstructionSet = null;
10482        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10483            requiredInstructionSet = VMRuntime.getInstructionSet(
10484                     scannedPackage.applicationInfo.primaryCpuAbi);
10485        }
10486
10487        PackageSetting requirer = null;
10488        for (PackageSetting ps : packagesForUser) {
10489            // If packagesForUser contains scannedPackage, we skip it. This will happen
10490            // when scannedPackage is an update of an existing package. Without this check,
10491            // we will never be able to change the ABI of any package belonging to a shared
10492            // user, even if it's compatible with other packages.
10493            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10494                if (ps.primaryCpuAbiString == null) {
10495                    continue;
10496                }
10497
10498                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10499                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10500                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10501                    // this but there's not much we can do.
10502                    String errorMessage = "Instruction set mismatch, "
10503                            + ((requirer == null) ? "[caller]" : requirer)
10504                            + " requires " + requiredInstructionSet + " whereas " + ps
10505                            + " requires " + instructionSet;
10506                    Slog.w(TAG, errorMessage);
10507                }
10508
10509                if (requiredInstructionSet == null) {
10510                    requiredInstructionSet = instructionSet;
10511                    requirer = ps;
10512                }
10513            }
10514        }
10515
10516        if (requiredInstructionSet != null) {
10517            String adjustedAbi;
10518            if (requirer != null) {
10519                // requirer != null implies that either scannedPackage was null or that scannedPackage
10520                // did not require an ABI, in which case we have to adjust scannedPackage to match
10521                // the ABI of the set (which is the same as requirer's ABI)
10522                adjustedAbi = requirer.primaryCpuAbiString;
10523                if (scannedPackage != null) {
10524                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10525                }
10526            } else {
10527                // requirer == null implies that we're updating all ABIs in the set to
10528                // match scannedPackage.
10529                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10530            }
10531
10532            for (PackageSetting ps : packagesForUser) {
10533                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10534                    if (ps.primaryCpuAbiString != null) {
10535                        continue;
10536                    }
10537
10538                    ps.primaryCpuAbiString = adjustedAbi;
10539                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10540                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10541                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10542                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10543                                + " (requirer="
10544                                + (requirer != null ? requirer.pkg : "null")
10545                                + ", scannedPackage="
10546                                + (scannedPackage != null ? scannedPackage : "null")
10547                                + ")");
10548                        try {
10549                            mInstaller.rmdex(ps.codePathString,
10550                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10551                        } catch (InstallerException ignored) {
10552                        }
10553                    }
10554                }
10555            }
10556        }
10557    }
10558
10559    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10560        synchronized (mPackages) {
10561            mResolverReplaced = true;
10562            // Set up information for custom user intent resolution activity.
10563            mResolveActivity.applicationInfo = pkg.applicationInfo;
10564            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10565            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10566            mResolveActivity.processName = pkg.applicationInfo.packageName;
10567            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10568            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10569                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10570            mResolveActivity.theme = 0;
10571            mResolveActivity.exported = true;
10572            mResolveActivity.enabled = true;
10573            mResolveInfo.activityInfo = mResolveActivity;
10574            mResolveInfo.priority = 0;
10575            mResolveInfo.preferredOrder = 0;
10576            mResolveInfo.match = 0;
10577            mResolveComponentName = mCustomResolverComponentName;
10578            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10579                    mResolveComponentName);
10580        }
10581    }
10582
10583    private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) {
10584        if (installerComponent == null) {
10585            if (DEBUG_EPHEMERAL) {
10586                Slog.d(TAG, "Clear ephemeral installer activity");
10587            }
10588            mInstantAppInstallerActivity.applicationInfo = null;
10589            return;
10590        }
10591
10592        if (DEBUG_EPHEMERAL) {
10593            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10594        }
10595        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10596        // Set up information for ephemeral installer activity
10597        mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo;
10598        mInstantAppInstallerActivity.name = installerComponent.getClassName();
10599        mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName;
10600        mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName;
10601        mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10602        mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10603                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10604        mInstantAppInstallerActivity.theme = 0;
10605        mInstantAppInstallerActivity.exported = true;
10606        mInstantAppInstallerActivity.enabled = true;
10607        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10608        mInstantAppInstallerInfo.priority = 0;
10609        mInstantAppInstallerInfo.preferredOrder = 1;
10610        mInstantAppInstallerInfo.isDefault = true;
10611        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10612                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10613    }
10614
10615    private static String calculateBundledApkRoot(final String codePathString) {
10616        final File codePath = new File(codePathString);
10617        final File codeRoot;
10618        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10619            codeRoot = Environment.getRootDirectory();
10620        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10621            codeRoot = Environment.getOemDirectory();
10622        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10623            codeRoot = Environment.getVendorDirectory();
10624        } else {
10625            // Unrecognized code path; take its top real segment as the apk root:
10626            // e.g. /something/app/blah.apk => /something
10627            try {
10628                File f = codePath.getCanonicalFile();
10629                File parent = f.getParentFile();    // non-null because codePath is a file
10630                File tmp;
10631                while ((tmp = parent.getParentFile()) != null) {
10632                    f = parent;
10633                    parent = tmp;
10634                }
10635                codeRoot = f;
10636                Slog.w(TAG, "Unrecognized code path "
10637                        + codePath + " - using " + codeRoot);
10638            } catch (IOException e) {
10639                // Can't canonicalize the code path -- shenanigans?
10640                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10641                return Environment.getRootDirectory().getPath();
10642            }
10643        }
10644        return codeRoot.getPath();
10645    }
10646
10647    /**
10648     * Derive and set the location of native libraries for the given package,
10649     * which varies depending on where and how the package was installed.
10650     */
10651    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10652        final ApplicationInfo info = pkg.applicationInfo;
10653        final String codePath = pkg.codePath;
10654        final File codeFile = new File(codePath);
10655        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10656        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10657
10658        info.nativeLibraryRootDir = null;
10659        info.nativeLibraryRootRequiresIsa = false;
10660        info.nativeLibraryDir = null;
10661        info.secondaryNativeLibraryDir = null;
10662
10663        if (isApkFile(codeFile)) {
10664            // Monolithic install
10665            if (bundledApp) {
10666                // If "/system/lib64/apkname" exists, assume that is the per-package
10667                // native library directory to use; otherwise use "/system/lib/apkname".
10668                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10669                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10670                        getPrimaryInstructionSet(info));
10671
10672                // This is a bundled system app so choose the path based on the ABI.
10673                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10674                // is just the default path.
10675                final String apkName = deriveCodePathName(codePath);
10676                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10677                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10678                        apkName).getAbsolutePath();
10679
10680                if (info.secondaryCpuAbi != null) {
10681                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10682                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10683                            secondaryLibDir, apkName).getAbsolutePath();
10684                }
10685            } else if (asecApp) {
10686                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10687                        .getAbsolutePath();
10688            } else {
10689                final String apkName = deriveCodePathName(codePath);
10690                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10691                        .getAbsolutePath();
10692            }
10693
10694            info.nativeLibraryRootRequiresIsa = false;
10695            info.nativeLibraryDir = info.nativeLibraryRootDir;
10696        } else {
10697            // Cluster install
10698            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10699            info.nativeLibraryRootRequiresIsa = true;
10700
10701            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10702                    getPrimaryInstructionSet(info)).getAbsolutePath();
10703
10704            if (info.secondaryCpuAbi != null) {
10705                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10706                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10707            }
10708        }
10709    }
10710
10711    /**
10712     * Calculate the abis and roots for a bundled app. These can uniquely
10713     * be determined from the contents of the system partition, i.e whether
10714     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10715     * of this information, and instead assume that the system was built
10716     * sensibly.
10717     */
10718    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10719                                           PackageSetting pkgSetting) {
10720        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10721
10722        // If "/system/lib64/apkname" exists, assume that is the per-package
10723        // native library directory to use; otherwise use "/system/lib/apkname".
10724        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10725        setBundledAppAbi(pkg, apkRoot, apkName);
10726        // pkgSetting might be null during rescan following uninstall of updates
10727        // to a bundled app, so accommodate that possibility.  The settings in
10728        // that case will be established later from the parsed package.
10729        //
10730        // If the settings aren't null, sync them up with what we've just derived.
10731        // note that apkRoot isn't stored in the package settings.
10732        if (pkgSetting != null) {
10733            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10734            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10735        }
10736    }
10737
10738    /**
10739     * Deduces the ABI of a bundled app and sets the relevant fields on the
10740     * parsed pkg object.
10741     *
10742     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10743     *        under which system libraries are installed.
10744     * @param apkName the name of the installed package.
10745     */
10746    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10747        final File codeFile = new File(pkg.codePath);
10748
10749        final boolean has64BitLibs;
10750        final boolean has32BitLibs;
10751        if (isApkFile(codeFile)) {
10752            // Monolithic install
10753            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10754            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10755        } else {
10756            // Cluster install
10757            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10758            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10759                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10760                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10761                has64BitLibs = (new File(rootDir, isa)).exists();
10762            } else {
10763                has64BitLibs = false;
10764            }
10765            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10766                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10767                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10768                has32BitLibs = (new File(rootDir, isa)).exists();
10769            } else {
10770                has32BitLibs = false;
10771            }
10772        }
10773
10774        if (has64BitLibs && !has32BitLibs) {
10775            // The package has 64 bit libs, but not 32 bit libs. Its primary
10776            // ABI should be 64 bit. We can safely assume here that the bundled
10777            // native libraries correspond to the most preferred ABI in the list.
10778
10779            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10780            pkg.applicationInfo.secondaryCpuAbi = null;
10781        } else if (has32BitLibs && !has64BitLibs) {
10782            // The package has 32 bit libs but not 64 bit libs. Its primary
10783            // ABI should be 32 bit.
10784
10785            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10786            pkg.applicationInfo.secondaryCpuAbi = null;
10787        } else if (has32BitLibs && has64BitLibs) {
10788            // The application has both 64 and 32 bit bundled libraries. We check
10789            // here that the app declares multiArch support, and warn if it doesn't.
10790            //
10791            // We will be lenient here and record both ABIs. The primary will be the
10792            // ABI that's higher on the list, i.e, a device that's configured to prefer
10793            // 64 bit apps will see a 64 bit primary ABI,
10794
10795            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10796                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10797            }
10798
10799            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10800                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10801                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10802            } else {
10803                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10804                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10805            }
10806        } else {
10807            pkg.applicationInfo.primaryCpuAbi = null;
10808            pkg.applicationInfo.secondaryCpuAbi = null;
10809        }
10810    }
10811
10812    private void killApplication(String pkgName, int appId, String reason) {
10813        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10814    }
10815
10816    private void killApplication(String pkgName, int appId, int userId, String reason) {
10817        // Request the ActivityManager to kill the process(only for existing packages)
10818        // so that we do not end up in a confused state while the user is still using the older
10819        // version of the application while the new one gets installed.
10820        final long token = Binder.clearCallingIdentity();
10821        try {
10822            IActivityManager am = ActivityManager.getService();
10823            if (am != null) {
10824                try {
10825                    am.killApplication(pkgName, appId, userId, reason);
10826                } catch (RemoteException e) {
10827                }
10828            }
10829        } finally {
10830            Binder.restoreCallingIdentity(token);
10831        }
10832    }
10833
10834    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10835        // Remove the parent package setting
10836        PackageSetting ps = (PackageSetting) pkg.mExtras;
10837        if (ps != null) {
10838            removePackageLI(ps, chatty);
10839        }
10840        // Remove the child package setting
10841        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10842        for (int i = 0; i < childCount; i++) {
10843            PackageParser.Package childPkg = pkg.childPackages.get(i);
10844            ps = (PackageSetting) childPkg.mExtras;
10845            if (ps != null) {
10846                removePackageLI(ps, chatty);
10847            }
10848        }
10849    }
10850
10851    void removePackageLI(PackageSetting ps, boolean chatty) {
10852        if (DEBUG_INSTALL) {
10853            if (chatty)
10854                Log.d(TAG, "Removing package " + ps.name);
10855        }
10856
10857        // writer
10858        synchronized (mPackages) {
10859            mPackages.remove(ps.name);
10860            final PackageParser.Package pkg = ps.pkg;
10861            if (pkg != null) {
10862                cleanPackageDataStructuresLILPw(pkg, chatty);
10863            }
10864        }
10865    }
10866
10867    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10868        if (DEBUG_INSTALL) {
10869            if (chatty)
10870                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10871        }
10872
10873        // writer
10874        synchronized (mPackages) {
10875            // Remove the parent package
10876            mPackages.remove(pkg.applicationInfo.packageName);
10877            cleanPackageDataStructuresLILPw(pkg, chatty);
10878
10879            // Remove the child packages
10880            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10881            for (int i = 0; i < childCount; i++) {
10882                PackageParser.Package childPkg = pkg.childPackages.get(i);
10883                mPackages.remove(childPkg.applicationInfo.packageName);
10884                cleanPackageDataStructuresLILPw(childPkg, chatty);
10885            }
10886        }
10887    }
10888
10889    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10890        int N = pkg.providers.size();
10891        StringBuilder r = null;
10892        int i;
10893        for (i=0; i<N; i++) {
10894            PackageParser.Provider p = pkg.providers.get(i);
10895            mProviders.removeProvider(p);
10896            if (p.info.authority == null) {
10897
10898                /* There was another ContentProvider with this authority when
10899                 * this app was installed so this authority is null,
10900                 * Ignore it as we don't have to unregister the provider.
10901                 */
10902                continue;
10903            }
10904            String names[] = p.info.authority.split(";");
10905            for (int j = 0; j < names.length; j++) {
10906                if (mProvidersByAuthority.get(names[j]) == p) {
10907                    mProvidersByAuthority.remove(names[j]);
10908                    if (DEBUG_REMOVE) {
10909                        if (chatty)
10910                            Log.d(TAG, "Unregistered content provider: " + names[j]
10911                                    + ", className = " + p.info.name + ", isSyncable = "
10912                                    + p.info.isSyncable);
10913                    }
10914                }
10915            }
10916            if (DEBUG_REMOVE && chatty) {
10917                if (r == null) {
10918                    r = new StringBuilder(256);
10919                } else {
10920                    r.append(' ');
10921                }
10922                r.append(p.info.name);
10923            }
10924        }
10925        if (r != null) {
10926            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10927        }
10928
10929        N = pkg.services.size();
10930        r = null;
10931        for (i=0; i<N; i++) {
10932            PackageParser.Service s = pkg.services.get(i);
10933            mServices.removeService(s);
10934            if (chatty) {
10935                if (r == null) {
10936                    r = new StringBuilder(256);
10937                } else {
10938                    r.append(' ');
10939                }
10940                r.append(s.info.name);
10941            }
10942        }
10943        if (r != null) {
10944            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10945        }
10946
10947        N = pkg.receivers.size();
10948        r = null;
10949        for (i=0; i<N; i++) {
10950            PackageParser.Activity a = pkg.receivers.get(i);
10951            mReceivers.removeActivity(a, "receiver");
10952            if (DEBUG_REMOVE && chatty) {
10953                if (r == null) {
10954                    r = new StringBuilder(256);
10955                } else {
10956                    r.append(' ');
10957                }
10958                r.append(a.info.name);
10959            }
10960        }
10961        if (r != null) {
10962            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10963        }
10964
10965        N = pkg.activities.size();
10966        r = null;
10967        for (i=0; i<N; i++) {
10968            PackageParser.Activity a = pkg.activities.get(i);
10969            mActivities.removeActivity(a, "activity");
10970            if (DEBUG_REMOVE && chatty) {
10971                if (r == null) {
10972                    r = new StringBuilder(256);
10973                } else {
10974                    r.append(' ');
10975                }
10976                r.append(a.info.name);
10977            }
10978        }
10979        if (r != null) {
10980            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10981        }
10982
10983        N = pkg.permissions.size();
10984        r = null;
10985        for (i=0; i<N; i++) {
10986            PackageParser.Permission p = pkg.permissions.get(i);
10987            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10988            if (bp == null) {
10989                bp = mSettings.mPermissionTrees.get(p.info.name);
10990            }
10991            if (bp != null && bp.perm == p) {
10992                bp.perm = null;
10993                if (DEBUG_REMOVE && chatty) {
10994                    if (r == null) {
10995                        r = new StringBuilder(256);
10996                    } else {
10997                        r.append(' ');
10998                    }
10999                    r.append(p.info.name);
11000                }
11001            }
11002            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11003                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11004                if (appOpPkgs != null) {
11005                    appOpPkgs.remove(pkg.packageName);
11006                }
11007            }
11008        }
11009        if (r != null) {
11010            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11011        }
11012
11013        N = pkg.requestedPermissions.size();
11014        r = null;
11015        for (i=0; i<N; i++) {
11016            String perm = pkg.requestedPermissions.get(i);
11017            BasePermission bp = mSettings.mPermissions.get(perm);
11018            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11019                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11020                if (appOpPkgs != null) {
11021                    appOpPkgs.remove(pkg.packageName);
11022                    if (appOpPkgs.isEmpty()) {
11023                        mAppOpPermissionPackages.remove(perm);
11024                    }
11025                }
11026            }
11027        }
11028        if (r != null) {
11029            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11030        }
11031
11032        N = pkg.instrumentation.size();
11033        r = null;
11034        for (i=0; i<N; i++) {
11035            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11036            mInstrumentation.remove(a.getComponentName());
11037            if (DEBUG_REMOVE && chatty) {
11038                if (r == null) {
11039                    r = new StringBuilder(256);
11040                } else {
11041                    r.append(' ');
11042                }
11043                r.append(a.info.name);
11044            }
11045        }
11046        if (r != null) {
11047            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11048        }
11049
11050        r = null;
11051        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11052            // Only system apps can hold shared libraries.
11053            if (pkg.libraryNames != null) {
11054                for (i = 0; i < pkg.libraryNames.size(); i++) {
11055                    String name = pkg.libraryNames.get(i);
11056                    if (removeSharedLibraryLPw(name, 0)) {
11057                        if (DEBUG_REMOVE && chatty) {
11058                            if (r == null) {
11059                                r = new StringBuilder(256);
11060                            } else {
11061                                r.append(' ');
11062                            }
11063                            r.append(name);
11064                        }
11065                    }
11066                }
11067            }
11068        }
11069
11070        r = null;
11071
11072        // Any package can hold static shared libraries.
11073        if (pkg.staticSharedLibName != null) {
11074            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11075                if (DEBUG_REMOVE && chatty) {
11076                    if (r == null) {
11077                        r = new StringBuilder(256);
11078                    } else {
11079                        r.append(' ');
11080                    }
11081                    r.append(pkg.staticSharedLibName);
11082                }
11083            }
11084        }
11085
11086        if (r != null) {
11087            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11088        }
11089    }
11090
11091    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11092        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11093            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11094                return true;
11095            }
11096        }
11097        return false;
11098    }
11099
11100    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11101    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11102    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11103
11104    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11105        // Update the parent permissions
11106        updatePermissionsLPw(pkg.packageName, pkg, flags);
11107        // Update the child permissions
11108        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11109        for (int i = 0; i < childCount; i++) {
11110            PackageParser.Package childPkg = pkg.childPackages.get(i);
11111            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11112        }
11113    }
11114
11115    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11116            int flags) {
11117        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11118        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11119    }
11120
11121    private void updatePermissionsLPw(String changingPkg,
11122            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11123        // Make sure there are no dangling permission trees.
11124        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11125        while (it.hasNext()) {
11126            final BasePermission bp = it.next();
11127            if (bp.packageSetting == null) {
11128                // We may not yet have parsed the package, so just see if
11129                // we still know about its settings.
11130                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11131            }
11132            if (bp.packageSetting == null) {
11133                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11134                        + " from package " + bp.sourcePackage);
11135                it.remove();
11136            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11137                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11138                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11139                            + " from package " + bp.sourcePackage);
11140                    flags |= UPDATE_PERMISSIONS_ALL;
11141                    it.remove();
11142                }
11143            }
11144        }
11145
11146        // Make sure all dynamic permissions have been assigned to a package,
11147        // and make sure there are no dangling permissions.
11148        it = mSettings.mPermissions.values().iterator();
11149        while (it.hasNext()) {
11150            final BasePermission bp = it.next();
11151            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11152                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11153                        + bp.name + " pkg=" + bp.sourcePackage
11154                        + " info=" + bp.pendingInfo);
11155                if (bp.packageSetting == null && bp.pendingInfo != null) {
11156                    final BasePermission tree = findPermissionTreeLP(bp.name);
11157                    if (tree != null && tree.perm != null) {
11158                        bp.packageSetting = tree.packageSetting;
11159                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11160                                new PermissionInfo(bp.pendingInfo));
11161                        bp.perm.info.packageName = tree.perm.info.packageName;
11162                        bp.perm.info.name = bp.name;
11163                        bp.uid = tree.uid;
11164                    }
11165                }
11166            }
11167            if (bp.packageSetting == null) {
11168                // We may not yet have parsed the package, so just see if
11169                // we still know about its settings.
11170                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11171            }
11172            if (bp.packageSetting == null) {
11173                Slog.w(TAG, "Removing dangling permission: " + bp.name
11174                        + " from package " + bp.sourcePackage);
11175                it.remove();
11176            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11177                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11178                    Slog.i(TAG, "Removing old permission: " + bp.name
11179                            + " from package " + bp.sourcePackage);
11180                    flags |= UPDATE_PERMISSIONS_ALL;
11181                    it.remove();
11182                }
11183            }
11184        }
11185
11186        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11187        // Now update the permissions for all packages, in particular
11188        // replace the granted permissions of the system packages.
11189        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11190            for (PackageParser.Package pkg : mPackages.values()) {
11191                if (pkg != pkgInfo) {
11192                    // Only replace for packages on requested volume
11193                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11194                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11195                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11196                    grantPermissionsLPw(pkg, replace, changingPkg);
11197                }
11198            }
11199        }
11200
11201        if (pkgInfo != null) {
11202            // Only replace for packages on requested volume
11203            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11204            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11205                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11206            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11207        }
11208        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11209    }
11210
11211    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11212            String packageOfInterest) {
11213        // IMPORTANT: There are two types of permissions: install and runtime.
11214        // Install time permissions are granted when the app is installed to
11215        // all device users and users added in the future. Runtime permissions
11216        // are granted at runtime explicitly to specific users. Normal and signature
11217        // protected permissions are install time permissions. Dangerous permissions
11218        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11219        // otherwise they are runtime permissions. This function does not manage
11220        // runtime permissions except for the case an app targeting Lollipop MR1
11221        // being upgraded to target a newer SDK, in which case dangerous permissions
11222        // are transformed from install time to runtime ones.
11223
11224        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11225        if (ps == null) {
11226            return;
11227        }
11228
11229        PermissionsState permissionsState = ps.getPermissionsState();
11230        PermissionsState origPermissions = permissionsState;
11231
11232        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11233
11234        boolean runtimePermissionsRevoked = false;
11235        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11236
11237        boolean changedInstallPermission = false;
11238
11239        if (replace) {
11240            ps.installPermissionsFixed = false;
11241            if (!ps.isSharedUser()) {
11242                origPermissions = new PermissionsState(permissionsState);
11243                permissionsState.reset();
11244            } else {
11245                // We need to know only about runtime permission changes since the
11246                // calling code always writes the install permissions state but
11247                // the runtime ones are written only if changed. The only cases of
11248                // changed runtime permissions here are promotion of an install to
11249                // runtime and revocation of a runtime from a shared user.
11250                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11251                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11252                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11253                    runtimePermissionsRevoked = true;
11254                }
11255            }
11256        }
11257
11258        permissionsState.setGlobalGids(mGlobalGids);
11259
11260        final int N = pkg.requestedPermissions.size();
11261        for (int i=0; i<N; i++) {
11262            final String name = pkg.requestedPermissions.get(i);
11263            final BasePermission bp = mSettings.mPermissions.get(name);
11264
11265            if (DEBUG_INSTALL) {
11266                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11267            }
11268
11269            if (bp == null || bp.packageSetting == null) {
11270                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11271                    Slog.w(TAG, "Unknown permission " + name
11272                            + " in package " + pkg.packageName);
11273                }
11274                continue;
11275            }
11276
11277
11278            // Limit ephemeral apps to ephemeral allowed permissions.
11279            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11280                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11281                        + pkg.packageName);
11282                continue;
11283            }
11284
11285            final String perm = bp.name;
11286            boolean allowedSig = false;
11287            int grant = GRANT_DENIED;
11288
11289            // Keep track of app op permissions.
11290            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11291                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11292                if (pkgs == null) {
11293                    pkgs = new ArraySet<>();
11294                    mAppOpPermissionPackages.put(bp.name, pkgs);
11295                }
11296                pkgs.add(pkg.packageName);
11297            }
11298
11299            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11300            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11301                    >= Build.VERSION_CODES.M;
11302            switch (level) {
11303                case PermissionInfo.PROTECTION_NORMAL: {
11304                    // For all apps normal permissions are install time ones.
11305                    grant = GRANT_INSTALL;
11306                } break;
11307
11308                case PermissionInfo.PROTECTION_DANGEROUS: {
11309                    // If a permission review is required for legacy apps we represent
11310                    // their permissions as always granted runtime ones since we need
11311                    // to keep the review required permission flag per user while an
11312                    // install permission's state is shared across all users.
11313                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11314                        // For legacy apps dangerous permissions are install time ones.
11315                        grant = GRANT_INSTALL;
11316                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11317                        // For legacy apps that became modern, install becomes runtime.
11318                        grant = GRANT_UPGRADE;
11319                    } else if (mPromoteSystemApps
11320                            && isSystemApp(ps)
11321                            && mExistingSystemPackages.contains(ps.name)) {
11322                        // For legacy system apps, install becomes runtime.
11323                        // We cannot check hasInstallPermission() for system apps since those
11324                        // permissions were granted implicitly and not persisted pre-M.
11325                        grant = GRANT_UPGRADE;
11326                    } else {
11327                        // For modern apps keep runtime permissions unchanged.
11328                        grant = GRANT_RUNTIME;
11329                    }
11330                } break;
11331
11332                case PermissionInfo.PROTECTION_SIGNATURE: {
11333                    // For all apps signature permissions are install time ones.
11334                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11335                    if (allowedSig) {
11336                        grant = GRANT_INSTALL;
11337                    }
11338                } break;
11339            }
11340
11341            if (DEBUG_INSTALL) {
11342                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11343            }
11344
11345            if (grant != GRANT_DENIED) {
11346                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11347                    // If this is an existing, non-system package, then
11348                    // we can't add any new permissions to it.
11349                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11350                        // Except...  if this is a permission that was added
11351                        // to the platform (note: need to only do this when
11352                        // updating the platform).
11353                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11354                            grant = GRANT_DENIED;
11355                        }
11356                    }
11357                }
11358
11359                switch (grant) {
11360                    case GRANT_INSTALL: {
11361                        // Revoke this as runtime permission to handle the case of
11362                        // a runtime permission being downgraded to an install one.
11363                        // Also in permission review mode we keep dangerous permissions
11364                        // for legacy apps
11365                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11366                            if (origPermissions.getRuntimePermissionState(
11367                                    bp.name, userId) != null) {
11368                                // Revoke the runtime permission and clear the flags.
11369                                origPermissions.revokeRuntimePermission(bp, userId);
11370                                origPermissions.updatePermissionFlags(bp, userId,
11371                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11372                                // If we revoked a permission permission, we have to write.
11373                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11374                                        changedRuntimePermissionUserIds, userId);
11375                            }
11376                        }
11377                        // Grant an install permission.
11378                        if (permissionsState.grantInstallPermission(bp) !=
11379                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11380                            changedInstallPermission = true;
11381                        }
11382                    } break;
11383
11384                    case GRANT_RUNTIME: {
11385                        // Grant previously granted runtime permissions.
11386                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11387                            PermissionState permissionState = origPermissions
11388                                    .getRuntimePermissionState(bp.name, userId);
11389                            int flags = permissionState != null
11390                                    ? permissionState.getFlags() : 0;
11391                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11392                                // Don't propagate the permission in a permission review mode if
11393                                // the former was revoked, i.e. marked to not propagate on upgrade.
11394                                // Note that in a permission review mode install permissions are
11395                                // represented as constantly granted runtime ones since we need to
11396                                // keep a per user state associated with the permission. Also the
11397                                // revoke on upgrade flag is no longer applicable and is reset.
11398                                final boolean revokeOnUpgrade = (flags & PackageManager
11399                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11400                                if (revokeOnUpgrade) {
11401                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11402                                    // Since we changed the flags, we have to write.
11403                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11404                                            changedRuntimePermissionUserIds, userId);
11405                                }
11406                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11407                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11408                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11409                                        // If we cannot put the permission as it was,
11410                                        // we have to write.
11411                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11412                                                changedRuntimePermissionUserIds, userId);
11413                                    }
11414                                }
11415
11416                                // If the app supports runtime permissions no need for a review.
11417                                if (mPermissionReviewRequired
11418                                        && appSupportsRuntimePermissions
11419                                        && (flags & PackageManager
11420                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11421                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11422                                    // Since we changed the flags, we have to write.
11423                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11424                                            changedRuntimePermissionUserIds, userId);
11425                                }
11426                            } else if (mPermissionReviewRequired
11427                                    && !appSupportsRuntimePermissions) {
11428                                // For legacy apps that need a permission review, every new
11429                                // runtime permission is granted but it is pending a review.
11430                                // We also need to review only platform defined runtime
11431                                // permissions as these are the only ones the platform knows
11432                                // how to disable the API to simulate revocation as legacy
11433                                // apps don't expect to run with revoked permissions.
11434                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11435                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11436                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11437                                        // We changed the flags, hence have to write.
11438                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11439                                                changedRuntimePermissionUserIds, userId);
11440                                    }
11441                                }
11442                                if (permissionsState.grantRuntimePermission(bp, userId)
11443                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11444                                    // We changed the permission, hence have to write.
11445                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11446                                            changedRuntimePermissionUserIds, userId);
11447                                }
11448                            }
11449                            // Propagate the permission flags.
11450                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11451                        }
11452                    } break;
11453
11454                    case GRANT_UPGRADE: {
11455                        // Grant runtime permissions for a previously held install permission.
11456                        PermissionState permissionState = origPermissions
11457                                .getInstallPermissionState(bp.name);
11458                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11459
11460                        if (origPermissions.revokeInstallPermission(bp)
11461                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11462                            // We will be transferring the permission flags, so clear them.
11463                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11464                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11465                            changedInstallPermission = true;
11466                        }
11467
11468                        // If the permission is not to be promoted to runtime we ignore it and
11469                        // also its other flags as they are not applicable to install permissions.
11470                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11471                            for (int userId : currentUserIds) {
11472                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11473                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11474                                    // Transfer the permission flags.
11475                                    permissionsState.updatePermissionFlags(bp, userId,
11476                                            flags, flags);
11477                                    // If we granted the permission, we have to write.
11478                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11479                                            changedRuntimePermissionUserIds, userId);
11480                                }
11481                            }
11482                        }
11483                    } break;
11484
11485                    default: {
11486                        if (packageOfInterest == null
11487                                || packageOfInterest.equals(pkg.packageName)) {
11488                            Slog.w(TAG, "Not granting permission " + perm
11489                                    + " to package " + pkg.packageName
11490                                    + " because it was previously installed without");
11491                        }
11492                    } break;
11493                }
11494            } else {
11495                if (permissionsState.revokeInstallPermission(bp) !=
11496                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11497                    // Also drop the permission flags.
11498                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11499                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11500                    changedInstallPermission = true;
11501                    Slog.i(TAG, "Un-granting permission " + perm
11502                            + " from package " + pkg.packageName
11503                            + " (protectionLevel=" + bp.protectionLevel
11504                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11505                            + ")");
11506                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11507                    // Don't print warning for app op permissions, since it is fine for them
11508                    // not to be granted, there is a UI for the user to decide.
11509                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11510                        Slog.w(TAG, "Not granting permission " + perm
11511                                + " to package " + pkg.packageName
11512                                + " (protectionLevel=" + bp.protectionLevel
11513                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11514                                + ")");
11515                    }
11516                }
11517            }
11518        }
11519
11520        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11521                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11522            // This is the first that we have heard about this package, so the
11523            // permissions we have now selected are fixed until explicitly
11524            // changed.
11525            ps.installPermissionsFixed = true;
11526        }
11527
11528        // Persist the runtime permissions state for users with changes. If permissions
11529        // were revoked because no app in the shared user declares them we have to
11530        // write synchronously to avoid losing runtime permissions state.
11531        for (int userId : changedRuntimePermissionUserIds) {
11532            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11533        }
11534    }
11535
11536    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11537        boolean allowed = false;
11538        final int NP = PackageParser.NEW_PERMISSIONS.length;
11539        for (int ip=0; ip<NP; ip++) {
11540            final PackageParser.NewPermissionInfo npi
11541                    = PackageParser.NEW_PERMISSIONS[ip];
11542            if (npi.name.equals(perm)
11543                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11544                allowed = true;
11545                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11546                        + pkg.packageName);
11547                break;
11548            }
11549        }
11550        return allowed;
11551    }
11552
11553    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11554            BasePermission bp, PermissionsState origPermissions) {
11555        boolean privilegedPermission = (bp.protectionLevel
11556                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11557        boolean privappPermissionsDisable =
11558                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11559        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11560        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11561        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11562                && !platformPackage && platformPermission) {
11563            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11564                    .getPrivAppPermissions(pkg.packageName);
11565            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11566            if (!whitelisted) {
11567                Slog.w(TAG, "Privileged permission " + perm + " for package "
11568                        + pkg.packageName + " - not in privapp-permissions whitelist");
11569                // Only report violations for apps on system image
11570                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11571                    if (mPrivappPermissionsViolations == null) {
11572                        mPrivappPermissionsViolations = new ArraySet<>();
11573                    }
11574                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11575                }
11576                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11577                    return false;
11578                }
11579            }
11580        }
11581        boolean allowed = (compareSignatures(
11582                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11583                        == PackageManager.SIGNATURE_MATCH)
11584                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11585                        == PackageManager.SIGNATURE_MATCH);
11586        if (!allowed && privilegedPermission) {
11587            if (isSystemApp(pkg)) {
11588                // For updated system applications, a system permission
11589                // is granted only if it had been defined by the original application.
11590                if (pkg.isUpdatedSystemApp()) {
11591                    final PackageSetting sysPs = mSettings
11592                            .getDisabledSystemPkgLPr(pkg.packageName);
11593                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11594                        // If the original was granted this permission, we take
11595                        // that grant decision as read and propagate it to the
11596                        // update.
11597                        if (sysPs.isPrivileged()) {
11598                            allowed = true;
11599                        }
11600                    } else {
11601                        // The system apk may have been updated with an older
11602                        // version of the one on the data partition, but which
11603                        // granted a new system permission that it didn't have
11604                        // before.  In this case we do want to allow the app to
11605                        // now get the new permission if the ancestral apk is
11606                        // privileged to get it.
11607                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11608                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11609                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11610                                    allowed = true;
11611                                    break;
11612                                }
11613                            }
11614                        }
11615                        // Also if a privileged parent package on the system image or any of
11616                        // its children requested a privileged permission, the updated child
11617                        // packages can also get the permission.
11618                        if (pkg.parentPackage != null) {
11619                            final PackageSetting disabledSysParentPs = mSettings
11620                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11621                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11622                                    && disabledSysParentPs.isPrivileged()) {
11623                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11624                                    allowed = true;
11625                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11626                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11627                                    for (int i = 0; i < count; i++) {
11628                                        PackageParser.Package disabledSysChildPkg =
11629                                                disabledSysParentPs.pkg.childPackages.get(i);
11630                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11631                                                perm)) {
11632                                            allowed = true;
11633                                            break;
11634                                        }
11635                                    }
11636                                }
11637                            }
11638                        }
11639                    }
11640                } else {
11641                    allowed = isPrivilegedApp(pkg);
11642                }
11643            }
11644        }
11645        if (!allowed) {
11646            if (!allowed && (bp.protectionLevel
11647                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11648                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11649                // If this was a previously normal/dangerous permission that got moved
11650                // to a system permission as part of the runtime permission redesign, then
11651                // we still want to blindly grant it to old apps.
11652                allowed = true;
11653            }
11654            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11655                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11656                // If this permission is to be granted to the system installer and
11657                // this app is an installer, then it gets the permission.
11658                allowed = true;
11659            }
11660            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11661                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11662                // If this permission is to be granted to the system verifier and
11663                // this app is a verifier, then it gets the permission.
11664                allowed = true;
11665            }
11666            if (!allowed && (bp.protectionLevel
11667                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11668                    && isSystemApp(pkg)) {
11669                // Any pre-installed system app is allowed to get this permission.
11670                allowed = true;
11671            }
11672            if (!allowed && (bp.protectionLevel
11673                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11674                // For development permissions, a development permission
11675                // is granted only if it was already granted.
11676                allowed = origPermissions.hasInstallPermission(perm);
11677            }
11678            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11679                    && pkg.packageName.equals(mSetupWizardPackage)) {
11680                // If this permission is to be granted to the system setup wizard and
11681                // this app is a setup wizard, then it gets the permission.
11682                allowed = true;
11683            }
11684        }
11685        return allowed;
11686    }
11687
11688    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11689        final int permCount = pkg.requestedPermissions.size();
11690        for (int j = 0; j < permCount; j++) {
11691            String requestedPermission = pkg.requestedPermissions.get(j);
11692            if (permission.equals(requestedPermission)) {
11693                return true;
11694            }
11695        }
11696        return false;
11697    }
11698
11699    final class ActivityIntentResolver
11700            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11701        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11702                boolean defaultOnly, int userId) {
11703            if (!sUserManager.exists(userId)) return null;
11704            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11705            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11706        }
11707
11708        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11709                int userId) {
11710            if (!sUserManager.exists(userId)) return null;
11711            mFlags = flags;
11712            return super.queryIntent(intent, resolvedType,
11713                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11714                    userId);
11715        }
11716
11717        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11718                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11719            if (!sUserManager.exists(userId)) return null;
11720            if (packageActivities == null) {
11721                return null;
11722            }
11723            mFlags = flags;
11724            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11725            final int N = packageActivities.size();
11726            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11727                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11728
11729            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11730            for (int i = 0; i < N; ++i) {
11731                intentFilters = packageActivities.get(i).intents;
11732                if (intentFilters != null && intentFilters.size() > 0) {
11733                    PackageParser.ActivityIntentInfo[] array =
11734                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11735                    intentFilters.toArray(array);
11736                    listCut.add(array);
11737                }
11738            }
11739            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11740        }
11741
11742        /**
11743         * Finds a privileged activity that matches the specified activity names.
11744         */
11745        private PackageParser.Activity findMatchingActivity(
11746                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11747            for (PackageParser.Activity sysActivity : activityList) {
11748                if (sysActivity.info.name.equals(activityInfo.name)) {
11749                    return sysActivity;
11750                }
11751                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11752                    return sysActivity;
11753                }
11754                if (sysActivity.info.targetActivity != null) {
11755                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11756                        return sysActivity;
11757                    }
11758                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11759                        return sysActivity;
11760                    }
11761                }
11762            }
11763            return null;
11764        }
11765
11766        public class IterGenerator<E> {
11767            public Iterator<E> generate(ActivityIntentInfo info) {
11768                return null;
11769            }
11770        }
11771
11772        public class ActionIterGenerator extends IterGenerator<String> {
11773            @Override
11774            public Iterator<String> generate(ActivityIntentInfo info) {
11775                return info.actionsIterator();
11776            }
11777        }
11778
11779        public class CategoriesIterGenerator extends IterGenerator<String> {
11780            @Override
11781            public Iterator<String> generate(ActivityIntentInfo info) {
11782                return info.categoriesIterator();
11783            }
11784        }
11785
11786        public class SchemesIterGenerator extends IterGenerator<String> {
11787            @Override
11788            public Iterator<String> generate(ActivityIntentInfo info) {
11789                return info.schemesIterator();
11790            }
11791        }
11792
11793        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11794            @Override
11795            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11796                return info.authoritiesIterator();
11797            }
11798        }
11799
11800        /**
11801         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11802         * MODIFIED. Do not pass in a list that should not be changed.
11803         */
11804        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11805                IterGenerator<T> generator, Iterator<T> searchIterator) {
11806            // loop through the set of actions; every one must be found in the intent filter
11807            while (searchIterator.hasNext()) {
11808                // we must have at least one filter in the list to consider a match
11809                if (intentList.size() == 0) {
11810                    break;
11811                }
11812
11813                final T searchAction = searchIterator.next();
11814
11815                // loop through the set of intent filters
11816                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11817                while (intentIter.hasNext()) {
11818                    final ActivityIntentInfo intentInfo = intentIter.next();
11819                    boolean selectionFound = false;
11820
11821                    // loop through the intent filter's selection criteria; at least one
11822                    // of them must match the searched criteria
11823                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11824                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11825                        final T intentSelection = intentSelectionIter.next();
11826                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11827                            selectionFound = true;
11828                            break;
11829                        }
11830                    }
11831
11832                    // the selection criteria wasn't found in this filter's set; this filter
11833                    // is not a potential match
11834                    if (!selectionFound) {
11835                        intentIter.remove();
11836                    }
11837                }
11838            }
11839        }
11840
11841        private boolean isProtectedAction(ActivityIntentInfo filter) {
11842            final Iterator<String> actionsIter = filter.actionsIterator();
11843            while (actionsIter != null && actionsIter.hasNext()) {
11844                final String filterAction = actionsIter.next();
11845                if (PROTECTED_ACTIONS.contains(filterAction)) {
11846                    return true;
11847                }
11848            }
11849            return false;
11850        }
11851
11852        /**
11853         * Adjusts the priority of the given intent filter according to policy.
11854         * <p>
11855         * <ul>
11856         * <li>The priority for non privileged applications is capped to '0'</li>
11857         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11858         * <li>The priority for unbundled updates to privileged applications is capped to the
11859         *      priority defined on the system partition</li>
11860         * </ul>
11861         * <p>
11862         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11863         * allowed to obtain any priority on any action.
11864         */
11865        private void adjustPriority(
11866                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11867            // nothing to do; priority is fine as-is
11868            if (intent.getPriority() <= 0) {
11869                return;
11870            }
11871
11872            final ActivityInfo activityInfo = intent.activity.info;
11873            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11874
11875            final boolean privilegedApp =
11876                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11877            if (!privilegedApp) {
11878                // non-privileged applications can never define a priority >0
11879                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11880                        + " package: " + applicationInfo.packageName
11881                        + " activity: " + intent.activity.className
11882                        + " origPrio: " + intent.getPriority());
11883                intent.setPriority(0);
11884                return;
11885            }
11886
11887            if (systemActivities == null) {
11888                // the system package is not disabled; we're parsing the system partition
11889                if (isProtectedAction(intent)) {
11890                    if (mDeferProtectedFilters) {
11891                        // We can't deal with these just yet. No component should ever obtain a
11892                        // >0 priority for a protected actions, with ONE exception -- the setup
11893                        // wizard. The setup wizard, however, cannot be known until we're able to
11894                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11895                        // until all intent filters have been processed. Chicken, meet egg.
11896                        // Let the filter temporarily have a high priority and rectify the
11897                        // priorities after all system packages have been scanned.
11898                        mProtectedFilters.add(intent);
11899                        if (DEBUG_FILTERS) {
11900                            Slog.i(TAG, "Protected action; save for later;"
11901                                    + " package: " + applicationInfo.packageName
11902                                    + " activity: " + intent.activity.className
11903                                    + " origPrio: " + intent.getPriority());
11904                        }
11905                        return;
11906                    } else {
11907                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11908                            Slog.i(TAG, "No setup wizard;"
11909                                + " All protected intents capped to priority 0");
11910                        }
11911                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11912                            if (DEBUG_FILTERS) {
11913                                Slog.i(TAG, "Found setup wizard;"
11914                                    + " allow priority " + intent.getPriority() + ";"
11915                                    + " package: " + intent.activity.info.packageName
11916                                    + " activity: " + intent.activity.className
11917                                    + " priority: " + intent.getPriority());
11918                            }
11919                            // setup wizard gets whatever it wants
11920                            return;
11921                        }
11922                        Slog.w(TAG, "Protected action; cap priority to 0;"
11923                                + " package: " + intent.activity.info.packageName
11924                                + " activity: " + intent.activity.className
11925                                + " origPrio: " + intent.getPriority());
11926                        intent.setPriority(0);
11927                        return;
11928                    }
11929                }
11930                // privileged apps on the system image get whatever priority they request
11931                return;
11932            }
11933
11934            // privileged app unbundled update ... try to find the same activity
11935            final PackageParser.Activity foundActivity =
11936                    findMatchingActivity(systemActivities, activityInfo);
11937            if (foundActivity == null) {
11938                // this is a new activity; it cannot obtain >0 priority
11939                if (DEBUG_FILTERS) {
11940                    Slog.i(TAG, "New activity; cap priority to 0;"
11941                            + " package: " + applicationInfo.packageName
11942                            + " activity: " + intent.activity.className
11943                            + " origPrio: " + intent.getPriority());
11944                }
11945                intent.setPriority(0);
11946                return;
11947            }
11948
11949            // found activity, now check for filter equivalence
11950
11951            // a shallow copy is enough; we modify the list, not its contents
11952            final List<ActivityIntentInfo> intentListCopy =
11953                    new ArrayList<>(foundActivity.intents);
11954            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11955
11956            // find matching action subsets
11957            final Iterator<String> actionsIterator = intent.actionsIterator();
11958            if (actionsIterator != null) {
11959                getIntentListSubset(
11960                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11961                if (intentListCopy.size() == 0) {
11962                    // no more intents to match; we're not equivalent
11963                    if (DEBUG_FILTERS) {
11964                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11965                                + " package: " + applicationInfo.packageName
11966                                + " activity: " + intent.activity.className
11967                                + " origPrio: " + intent.getPriority());
11968                    }
11969                    intent.setPriority(0);
11970                    return;
11971                }
11972            }
11973
11974            // find matching category subsets
11975            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11976            if (categoriesIterator != null) {
11977                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11978                        categoriesIterator);
11979                if (intentListCopy.size() == 0) {
11980                    // no more intents to match; we're not equivalent
11981                    if (DEBUG_FILTERS) {
11982                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11983                                + " package: " + applicationInfo.packageName
11984                                + " activity: " + intent.activity.className
11985                                + " origPrio: " + intent.getPriority());
11986                    }
11987                    intent.setPriority(0);
11988                    return;
11989                }
11990            }
11991
11992            // find matching schemes subsets
11993            final Iterator<String> schemesIterator = intent.schemesIterator();
11994            if (schemesIterator != null) {
11995                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11996                        schemesIterator);
11997                if (intentListCopy.size() == 0) {
11998                    // no more intents to match; we're not equivalent
11999                    if (DEBUG_FILTERS) {
12000                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12001                                + " package: " + applicationInfo.packageName
12002                                + " activity: " + intent.activity.className
12003                                + " origPrio: " + intent.getPriority());
12004                    }
12005                    intent.setPriority(0);
12006                    return;
12007                }
12008            }
12009
12010            // find matching authorities subsets
12011            final Iterator<IntentFilter.AuthorityEntry>
12012                    authoritiesIterator = intent.authoritiesIterator();
12013            if (authoritiesIterator != null) {
12014                getIntentListSubset(intentListCopy,
12015                        new AuthoritiesIterGenerator(),
12016                        authoritiesIterator);
12017                if (intentListCopy.size() == 0) {
12018                    // no more intents to match; we're not equivalent
12019                    if (DEBUG_FILTERS) {
12020                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12021                                + " package: " + applicationInfo.packageName
12022                                + " activity: " + intent.activity.className
12023                                + " origPrio: " + intent.getPriority());
12024                    }
12025                    intent.setPriority(0);
12026                    return;
12027                }
12028            }
12029
12030            // we found matching filter(s); app gets the max priority of all intents
12031            int cappedPriority = 0;
12032            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12033                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12034            }
12035            if (intent.getPriority() > cappedPriority) {
12036                if (DEBUG_FILTERS) {
12037                    Slog.i(TAG, "Found matching filter(s);"
12038                            + " cap priority to " + cappedPriority + ";"
12039                            + " package: " + applicationInfo.packageName
12040                            + " activity: " + intent.activity.className
12041                            + " origPrio: " + intent.getPriority());
12042                }
12043                intent.setPriority(cappedPriority);
12044                return;
12045            }
12046            // all this for nothing; the requested priority was <= what was on the system
12047        }
12048
12049        public final void addActivity(PackageParser.Activity a, String type) {
12050            mActivities.put(a.getComponentName(), a);
12051            if (DEBUG_SHOW_INFO)
12052                Log.v(
12053                TAG, "  " + type + " " +
12054                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12055            if (DEBUG_SHOW_INFO)
12056                Log.v(TAG, "    Class=" + a.info.name);
12057            final int NI = a.intents.size();
12058            for (int j=0; j<NI; j++) {
12059                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12060                if ("activity".equals(type)) {
12061                    final PackageSetting ps =
12062                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12063                    final List<PackageParser.Activity> systemActivities =
12064                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12065                    adjustPriority(systemActivities, intent);
12066                }
12067                if (DEBUG_SHOW_INFO) {
12068                    Log.v(TAG, "    IntentFilter:");
12069                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12070                }
12071                if (!intent.debugCheck()) {
12072                    Log.w(TAG, "==> For Activity " + a.info.name);
12073                }
12074                addFilter(intent);
12075            }
12076        }
12077
12078        public final void removeActivity(PackageParser.Activity a, String type) {
12079            mActivities.remove(a.getComponentName());
12080            if (DEBUG_SHOW_INFO) {
12081                Log.v(TAG, "  " + type + " "
12082                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12083                                : a.info.name) + ":");
12084                Log.v(TAG, "    Class=" + a.info.name);
12085            }
12086            final int NI = a.intents.size();
12087            for (int j=0; j<NI; j++) {
12088                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12089                if (DEBUG_SHOW_INFO) {
12090                    Log.v(TAG, "    IntentFilter:");
12091                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12092                }
12093                removeFilter(intent);
12094            }
12095        }
12096
12097        @Override
12098        protected boolean allowFilterResult(
12099                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12100            ActivityInfo filterAi = filter.activity.info;
12101            for (int i=dest.size()-1; i>=0; i--) {
12102                ActivityInfo destAi = dest.get(i).activityInfo;
12103                if (destAi.name == filterAi.name
12104                        && destAi.packageName == filterAi.packageName) {
12105                    return false;
12106                }
12107            }
12108            return true;
12109        }
12110
12111        @Override
12112        protected ActivityIntentInfo[] newArray(int size) {
12113            return new ActivityIntentInfo[size];
12114        }
12115
12116        @Override
12117        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12118            if (!sUserManager.exists(userId)) return true;
12119            PackageParser.Package p = filter.activity.owner;
12120            if (p != null) {
12121                PackageSetting ps = (PackageSetting)p.mExtras;
12122                if (ps != null) {
12123                    // System apps are never considered stopped for purposes of
12124                    // filtering, because there may be no way for the user to
12125                    // actually re-launch them.
12126                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12127                            && ps.getStopped(userId);
12128                }
12129            }
12130            return false;
12131        }
12132
12133        @Override
12134        protected boolean isPackageForFilter(String packageName,
12135                PackageParser.ActivityIntentInfo info) {
12136            return packageName.equals(info.activity.owner.packageName);
12137        }
12138
12139        @Override
12140        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12141                int match, int userId) {
12142            if (!sUserManager.exists(userId)) return null;
12143            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12144                return null;
12145            }
12146            final PackageParser.Activity activity = info.activity;
12147            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12148            if (ps == null) {
12149                return null;
12150            }
12151            final PackageUserState userState = ps.readUserState(userId);
12152            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12153                    userState, userId);
12154            if (ai == null) {
12155                return null;
12156            }
12157            final boolean matchVisibleToInstantApp =
12158                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12159            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12160            // throw out filters that aren't visible to ephemeral apps
12161            if (matchVisibleToInstantApp
12162                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12163                return null;
12164            }
12165            // throw out ephemeral filters if we're not explicitly requesting them
12166            if (!isInstantApp && userState.instantApp) {
12167                return null;
12168            }
12169            // throw out instant app filters if updates are available; will trigger
12170            // instant app resolution
12171            if (userState.instantApp && ps.isUpdateAvailable()) {
12172                return null;
12173            }
12174            final ResolveInfo res = new ResolveInfo();
12175            res.activityInfo = ai;
12176            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12177                res.filter = info;
12178            }
12179            if (info != null) {
12180                res.handleAllWebDataURI = info.handleAllWebDataURI();
12181            }
12182            res.priority = info.getPriority();
12183            res.preferredOrder = activity.owner.mPreferredOrder;
12184            //System.out.println("Result: " + res.activityInfo.className +
12185            //                   " = " + res.priority);
12186            res.match = match;
12187            res.isDefault = info.hasDefault;
12188            res.labelRes = info.labelRes;
12189            res.nonLocalizedLabel = info.nonLocalizedLabel;
12190            if (userNeedsBadging(userId)) {
12191                res.noResourceId = true;
12192            } else {
12193                res.icon = info.icon;
12194            }
12195            res.iconResourceId = info.icon;
12196            res.system = res.activityInfo.applicationInfo.isSystemApp();
12197            res.instantAppAvailable = userState.instantApp;
12198            return res;
12199        }
12200
12201        @Override
12202        protected void sortResults(List<ResolveInfo> results) {
12203            Collections.sort(results, mResolvePrioritySorter);
12204        }
12205
12206        @Override
12207        protected void dumpFilter(PrintWriter out, String prefix,
12208                PackageParser.ActivityIntentInfo filter) {
12209            out.print(prefix); out.print(
12210                    Integer.toHexString(System.identityHashCode(filter.activity)));
12211                    out.print(' ');
12212                    filter.activity.printComponentShortName(out);
12213                    out.print(" filter ");
12214                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12215        }
12216
12217        @Override
12218        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12219            return filter.activity;
12220        }
12221
12222        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12223            PackageParser.Activity activity = (PackageParser.Activity)label;
12224            out.print(prefix); out.print(
12225                    Integer.toHexString(System.identityHashCode(activity)));
12226                    out.print(' ');
12227                    activity.printComponentShortName(out);
12228            if (count > 1) {
12229                out.print(" ("); out.print(count); out.print(" filters)");
12230            }
12231            out.println();
12232        }
12233
12234        // Keys are String (activity class name), values are Activity.
12235        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12236                = new ArrayMap<ComponentName, PackageParser.Activity>();
12237        private int mFlags;
12238    }
12239
12240    private final class ServiceIntentResolver
12241            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12242        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12243                boolean defaultOnly, int userId) {
12244            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12245            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12246        }
12247
12248        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12249                int userId) {
12250            if (!sUserManager.exists(userId)) return null;
12251            mFlags = flags;
12252            return super.queryIntent(intent, resolvedType,
12253                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12254                    userId);
12255        }
12256
12257        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12258                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12259            if (!sUserManager.exists(userId)) return null;
12260            if (packageServices == null) {
12261                return null;
12262            }
12263            mFlags = flags;
12264            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12265            final int N = packageServices.size();
12266            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12267                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12268
12269            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12270            for (int i = 0; i < N; ++i) {
12271                intentFilters = packageServices.get(i).intents;
12272                if (intentFilters != null && intentFilters.size() > 0) {
12273                    PackageParser.ServiceIntentInfo[] array =
12274                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12275                    intentFilters.toArray(array);
12276                    listCut.add(array);
12277                }
12278            }
12279            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12280        }
12281
12282        public final void addService(PackageParser.Service s) {
12283            mServices.put(s.getComponentName(), s);
12284            if (DEBUG_SHOW_INFO) {
12285                Log.v(TAG, "  "
12286                        + (s.info.nonLocalizedLabel != null
12287                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12288                Log.v(TAG, "    Class=" + s.info.name);
12289            }
12290            final int NI = s.intents.size();
12291            int j;
12292            for (j=0; j<NI; j++) {
12293                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12294                if (DEBUG_SHOW_INFO) {
12295                    Log.v(TAG, "    IntentFilter:");
12296                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12297                }
12298                if (!intent.debugCheck()) {
12299                    Log.w(TAG, "==> For Service " + s.info.name);
12300                }
12301                addFilter(intent);
12302            }
12303        }
12304
12305        public final void removeService(PackageParser.Service s) {
12306            mServices.remove(s.getComponentName());
12307            if (DEBUG_SHOW_INFO) {
12308                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12309                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12310                Log.v(TAG, "    Class=" + s.info.name);
12311            }
12312            final int NI = s.intents.size();
12313            int j;
12314            for (j=0; j<NI; j++) {
12315                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12316                if (DEBUG_SHOW_INFO) {
12317                    Log.v(TAG, "    IntentFilter:");
12318                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12319                }
12320                removeFilter(intent);
12321            }
12322        }
12323
12324        @Override
12325        protected boolean allowFilterResult(
12326                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12327            ServiceInfo filterSi = filter.service.info;
12328            for (int i=dest.size()-1; i>=0; i--) {
12329                ServiceInfo destAi = dest.get(i).serviceInfo;
12330                if (destAi.name == filterSi.name
12331                        && destAi.packageName == filterSi.packageName) {
12332                    return false;
12333                }
12334            }
12335            return true;
12336        }
12337
12338        @Override
12339        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12340            return new PackageParser.ServiceIntentInfo[size];
12341        }
12342
12343        @Override
12344        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12345            if (!sUserManager.exists(userId)) return true;
12346            PackageParser.Package p = filter.service.owner;
12347            if (p != null) {
12348                PackageSetting ps = (PackageSetting)p.mExtras;
12349                if (ps != null) {
12350                    // System apps are never considered stopped for purposes of
12351                    // filtering, because there may be no way for the user to
12352                    // actually re-launch them.
12353                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12354                            && ps.getStopped(userId);
12355                }
12356            }
12357            return false;
12358        }
12359
12360        @Override
12361        protected boolean isPackageForFilter(String packageName,
12362                PackageParser.ServiceIntentInfo info) {
12363            return packageName.equals(info.service.owner.packageName);
12364        }
12365
12366        @Override
12367        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12368                int match, int userId) {
12369            if (!sUserManager.exists(userId)) return null;
12370            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12371            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12372                return null;
12373            }
12374            final PackageParser.Service service = info.service;
12375            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12376            if (ps == null) {
12377                return null;
12378            }
12379            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12380                    ps.readUserState(userId), userId);
12381            if (si == null) {
12382                return null;
12383            }
12384            final ResolveInfo res = new ResolveInfo();
12385            res.serviceInfo = si;
12386            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12387                res.filter = filter;
12388            }
12389            res.priority = info.getPriority();
12390            res.preferredOrder = service.owner.mPreferredOrder;
12391            res.match = match;
12392            res.isDefault = info.hasDefault;
12393            res.labelRes = info.labelRes;
12394            res.nonLocalizedLabel = info.nonLocalizedLabel;
12395            res.icon = info.icon;
12396            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12397            return res;
12398        }
12399
12400        @Override
12401        protected void sortResults(List<ResolveInfo> results) {
12402            Collections.sort(results, mResolvePrioritySorter);
12403        }
12404
12405        @Override
12406        protected void dumpFilter(PrintWriter out, String prefix,
12407                PackageParser.ServiceIntentInfo filter) {
12408            out.print(prefix); out.print(
12409                    Integer.toHexString(System.identityHashCode(filter.service)));
12410                    out.print(' ');
12411                    filter.service.printComponentShortName(out);
12412                    out.print(" filter ");
12413                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12414        }
12415
12416        @Override
12417        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12418            return filter.service;
12419        }
12420
12421        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12422            PackageParser.Service service = (PackageParser.Service)label;
12423            out.print(prefix); out.print(
12424                    Integer.toHexString(System.identityHashCode(service)));
12425                    out.print(' ');
12426                    service.printComponentShortName(out);
12427            if (count > 1) {
12428                out.print(" ("); out.print(count); out.print(" filters)");
12429            }
12430            out.println();
12431        }
12432
12433//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12434//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12435//            final List<ResolveInfo> retList = Lists.newArrayList();
12436//            while (i.hasNext()) {
12437//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12438//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12439//                    retList.add(resolveInfo);
12440//                }
12441//            }
12442//            return retList;
12443//        }
12444
12445        // Keys are String (activity class name), values are Activity.
12446        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12447                = new ArrayMap<ComponentName, PackageParser.Service>();
12448        private int mFlags;
12449    }
12450
12451    private final class ProviderIntentResolver
12452            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12453        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12454                boolean defaultOnly, int userId) {
12455            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12456            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12457        }
12458
12459        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12460                int userId) {
12461            if (!sUserManager.exists(userId))
12462                return null;
12463            mFlags = flags;
12464            return super.queryIntent(intent, resolvedType,
12465                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12466                    userId);
12467        }
12468
12469        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12470                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12471            if (!sUserManager.exists(userId))
12472                return null;
12473            if (packageProviders == null) {
12474                return null;
12475            }
12476            mFlags = flags;
12477            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12478            final int N = packageProviders.size();
12479            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12480                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12481
12482            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12483            for (int i = 0; i < N; ++i) {
12484                intentFilters = packageProviders.get(i).intents;
12485                if (intentFilters != null && intentFilters.size() > 0) {
12486                    PackageParser.ProviderIntentInfo[] array =
12487                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12488                    intentFilters.toArray(array);
12489                    listCut.add(array);
12490                }
12491            }
12492            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12493        }
12494
12495        public final void addProvider(PackageParser.Provider p) {
12496            if (mProviders.containsKey(p.getComponentName())) {
12497                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12498                return;
12499            }
12500
12501            mProviders.put(p.getComponentName(), p);
12502            if (DEBUG_SHOW_INFO) {
12503                Log.v(TAG, "  "
12504                        + (p.info.nonLocalizedLabel != null
12505                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12506                Log.v(TAG, "    Class=" + p.info.name);
12507            }
12508            final int NI = p.intents.size();
12509            int j;
12510            for (j = 0; j < NI; j++) {
12511                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12512                if (DEBUG_SHOW_INFO) {
12513                    Log.v(TAG, "    IntentFilter:");
12514                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12515                }
12516                if (!intent.debugCheck()) {
12517                    Log.w(TAG, "==> For Provider " + p.info.name);
12518                }
12519                addFilter(intent);
12520            }
12521        }
12522
12523        public final void removeProvider(PackageParser.Provider p) {
12524            mProviders.remove(p.getComponentName());
12525            if (DEBUG_SHOW_INFO) {
12526                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12527                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12528                Log.v(TAG, "    Class=" + p.info.name);
12529            }
12530            final int NI = p.intents.size();
12531            int j;
12532            for (j = 0; j < NI; j++) {
12533                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12534                if (DEBUG_SHOW_INFO) {
12535                    Log.v(TAG, "    IntentFilter:");
12536                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12537                }
12538                removeFilter(intent);
12539            }
12540        }
12541
12542        @Override
12543        protected boolean allowFilterResult(
12544                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12545            ProviderInfo filterPi = filter.provider.info;
12546            for (int i = dest.size() - 1; i >= 0; i--) {
12547                ProviderInfo destPi = dest.get(i).providerInfo;
12548                if (destPi.name == filterPi.name
12549                        && destPi.packageName == filterPi.packageName) {
12550                    return false;
12551                }
12552            }
12553            return true;
12554        }
12555
12556        @Override
12557        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12558            return new PackageParser.ProviderIntentInfo[size];
12559        }
12560
12561        @Override
12562        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12563            if (!sUserManager.exists(userId))
12564                return true;
12565            PackageParser.Package p = filter.provider.owner;
12566            if (p != null) {
12567                PackageSetting ps = (PackageSetting) p.mExtras;
12568                if (ps != null) {
12569                    // System apps are never considered stopped for purposes of
12570                    // filtering, because there may be no way for the user to
12571                    // actually re-launch them.
12572                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12573                            && ps.getStopped(userId);
12574                }
12575            }
12576            return false;
12577        }
12578
12579        @Override
12580        protected boolean isPackageForFilter(String packageName,
12581                PackageParser.ProviderIntentInfo info) {
12582            return packageName.equals(info.provider.owner.packageName);
12583        }
12584
12585        @Override
12586        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12587                int match, int userId) {
12588            if (!sUserManager.exists(userId))
12589                return null;
12590            final PackageParser.ProviderIntentInfo info = filter;
12591            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12592                return null;
12593            }
12594            final PackageParser.Provider provider = info.provider;
12595            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12596            if (ps == null) {
12597                return null;
12598            }
12599            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12600                    ps.readUserState(userId), userId);
12601            if (pi == null) {
12602                return null;
12603            }
12604            final ResolveInfo res = new ResolveInfo();
12605            res.providerInfo = pi;
12606            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12607                res.filter = filter;
12608            }
12609            res.priority = info.getPriority();
12610            res.preferredOrder = provider.owner.mPreferredOrder;
12611            res.match = match;
12612            res.isDefault = info.hasDefault;
12613            res.labelRes = info.labelRes;
12614            res.nonLocalizedLabel = info.nonLocalizedLabel;
12615            res.icon = info.icon;
12616            res.system = res.providerInfo.applicationInfo.isSystemApp();
12617            return res;
12618        }
12619
12620        @Override
12621        protected void sortResults(List<ResolveInfo> results) {
12622            Collections.sort(results, mResolvePrioritySorter);
12623        }
12624
12625        @Override
12626        protected void dumpFilter(PrintWriter out, String prefix,
12627                PackageParser.ProviderIntentInfo filter) {
12628            out.print(prefix);
12629            out.print(
12630                    Integer.toHexString(System.identityHashCode(filter.provider)));
12631            out.print(' ');
12632            filter.provider.printComponentShortName(out);
12633            out.print(" filter ");
12634            out.println(Integer.toHexString(System.identityHashCode(filter)));
12635        }
12636
12637        @Override
12638        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12639            return filter.provider;
12640        }
12641
12642        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12643            PackageParser.Provider provider = (PackageParser.Provider)label;
12644            out.print(prefix); out.print(
12645                    Integer.toHexString(System.identityHashCode(provider)));
12646                    out.print(' ');
12647                    provider.printComponentShortName(out);
12648            if (count > 1) {
12649                out.print(" ("); out.print(count); out.print(" filters)");
12650            }
12651            out.println();
12652        }
12653
12654        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12655                = new ArrayMap<ComponentName, PackageParser.Provider>();
12656        private int mFlags;
12657    }
12658
12659    static final class EphemeralIntentResolver
12660            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12661        /**
12662         * The result that has the highest defined order. Ordering applies on a
12663         * per-package basis. Mapping is from package name to Pair of order and
12664         * EphemeralResolveInfo.
12665         * <p>
12666         * NOTE: This is implemented as a field variable for convenience and efficiency.
12667         * By having a field variable, we're able to track filter ordering as soon as
12668         * a non-zero order is defined. Otherwise, multiple loops across the result set
12669         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12670         * this needs to be contained entirely within {@link #filterResults}.
12671         */
12672        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12673
12674        @Override
12675        protected AuxiliaryResolveInfo[] newArray(int size) {
12676            return new AuxiliaryResolveInfo[size];
12677        }
12678
12679        @Override
12680        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12681            return true;
12682        }
12683
12684        @Override
12685        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12686                int userId) {
12687            if (!sUserManager.exists(userId)) {
12688                return null;
12689            }
12690            final String packageName = responseObj.resolveInfo.getPackageName();
12691            final Integer order = responseObj.getOrder();
12692            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12693                    mOrderResult.get(packageName);
12694            // ordering is enabled and this item's order isn't high enough
12695            if (lastOrderResult != null && lastOrderResult.first >= order) {
12696                return null;
12697            }
12698            final InstantAppResolveInfo res = responseObj.resolveInfo;
12699            if (order > 0) {
12700                // non-zero order, enable ordering
12701                mOrderResult.put(packageName, new Pair<>(order, res));
12702            }
12703            return responseObj;
12704        }
12705
12706        @Override
12707        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12708            // only do work if ordering is enabled [most of the time it won't be]
12709            if (mOrderResult.size() == 0) {
12710                return;
12711            }
12712            int resultSize = results.size();
12713            for (int i = 0; i < resultSize; i++) {
12714                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12715                final String packageName = info.getPackageName();
12716                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12717                if (savedInfo == null) {
12718                    // package doesn't having ordering
12719                    continue;
12720                }
12721                if (savedInfo.second == info) {
12722                    // circled back to the highest ordered item; remove from order list
12723                    mOrderResult.remove(savedInfo);
12724                    if (mOrderResult.size() == 0) {
12725                        // no more ordered items
12726                        break;
12727                    }
12728                    continue;
12729                }
12730                // item has a worse order, remove it from the result list
12731                results.remove(i);
12732                resultSize--;
12733                i--;
12734            }
12735        }
12736    }
12737
12738    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12739            new Comparator<ResolveInfo>() {
12740        public int compare(ResolveInfo r1, ResolveInfo r2) {
12741            int v1 = r1.priority;
12742            int v2 = r2.priority;
12743            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12744            if (v1 != v2) {
12745                return (v1 > v2) ? -1 : 1;
12746            }
12747            v1 = r1.preferredOrder;
12748            v2 = r2.preferredOrder;
12749            if (v1 != v2) {
12750                return (v1 > v2) ? -1 : 1;
12751            }
12752            if (r1.isDefault != r2.isDefault) {
12753                return r1.isDefault ? -1 : 1;
12754            }
12755            v1 = r1.match;
12756            v2 = r2.match;
12757            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12758            if (v1 != v2) {
12759                return (v1 > v2) ? -1 : 1;
12760            }
12761            if (r1.system != r2.system) {
12762                return r1.system ? -1 : 1;
12763            }
12764            if (r1.activityInfo != null) {
12765                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12766            }
12767            if (r1.serviceInfo != null) {
12768                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12769            }
12770            if (r1.providerInfo != null) {
12771                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12772            }
12773            return 0;
12774        }
12775    };
12776
12777    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12778            new Comparator<ProviderInfo>() {
12779        public int compare(ProviderInfo p1, ProviderInfo p2) {
12780            final int v1 = p1.initOrder;
12781            final int v2 = p2.initOrder;
12782            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12783        }
12784    };
12785
12786    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12787            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12788            final int[] userIds) {
12789        mHandler.post(new Runnable() {
12790            @Override
12791            public void run() {
12792                try {
12793                    final IActivityManager am = ActivityManager.getService();
12794                    if (am == null) return;
12795                    final int[] resolvedUserIds;
12796                    if (userIds == null) {
12797                        resolvedUserIds = am.getRunningUserIds();
12798                    } else {
12799                        resolvedUserIds = userIds;
12800                    }
12801                    for (int id : resolvedUserIds) {
12802                        final Intent intent = new Intent(action,
12803                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12804                        if (extras != null) {
12805                            intent.putExtras(extras);
12806                        }
12807                        if (targetPkg != null) {
12808                            intent.setPackage(targetPkg);
12809                        }
12810                        // Modify the UID when posting to other users
12811                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12812                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12813                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12814                            intent.putExtra(Intent.EXTRA_UID, uid);
12815                        }
12816                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12817                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12818                        if (DEBUG_BROADCASTS) {
12819                            RuntimeException here = new RuntimeException("here");
12820                            here.fillInStackTrace();
12821                            Slog.d(TAG, "Sending to user " + id + ": "
12822                                    + intent.toShortString(false, true, false, false)
12823                                    + " " + intent.getExtras(), here);
12824                        }
12825                        am.broadcastIntent(null, intent, null, finishedReceiver,
12826                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12827                                null, finishedReceiver != null, false, id);
12828                    }
12829                } catch (RemoteException ex) {
12830                }
12831            }
12832        });
12833    }
12834
12835    /**
12836     * Check if the external storage media is available. This is true if there
12837     * is a mounted external storage medium or if the external storage is
12838     * emulated.
12839     */
12840    private boolean isExternalMediaAvailable() {
12841        return mMediaMounted || Environment.isExternalStorageEmulated();
12842    }
12843
12844    @Override
12845    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12846        // writer
12847        synchronized (mPackages) {
12848            if (!isExternalMediaAvailable()) {
12849                // If the external storage is no longer mounted at this point,
12850                // the caller may not have been able to delete all of this
12851                // packages files and can not delete any more.  Bail.
12852                return null;
12853            }
12854            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12855            if (lastPackage != null) {
12856                pkgs.remove(lastPackage);
12857            }
12858            if (pkgs.size() > 0) {
12859                return pkgs.get(0);
12860            }
12861        }
12862        return null;
12863    }
12864
12865    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12866        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12867                userId, andCode ? 1 : 0, packageName);
12868        if (mSystemReady) {
12869            msg.sendToTarget();
12870        } else {
12871            if (mPostSystemReadyMessages == null) {
12872                mPostSystemReadyMessages = new ArrayList<>();
12873            }
12874            mPostSystemReadyMessages.add(msg);
12875        }
12876    }
12877
12878    void startCleaningPackages() {
12879        // reader
12880        if (!isExternalMediaAvailable()) {
12881            return;
12882        }
12883        synchronized (mPackages) {
12884            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12885                return;
12886            }
12887        }
12888        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12889        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12890        IActivityManager am = ActivityManager.getService();
12891        if (am != null) {
12892            try {
12893                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12894                        UserHandle.USER_SYSTEM);
12895            } catch (RemoteException e) {
12896            }
12897        }
12898    }
12899
12900    @Override
12901    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12902            int installFlags, String installerPackageName, int userId) {
12903        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12904
12905        final int callingUid = Binder.getCallingUid();
12906        enforceCrossUserPermission(callingUid, userId,
12907                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12908
12909        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12910            try {
12911                if (observer != null) {
12912                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12913                }
12914            } catch (RemoteException re) {
12915            }
12916            return;
12917        }
12918
12919        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12920            installFlags |= PackageManager.INSTALL_FROM_ADB;
12921
12922        } else {
12923            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12924            // about installerPackageName.
12925
12926            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12927            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12928        }
12929
12930        UserHandle user;
12931        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12932            user = UserHandle.ALL;
12933        } else {
12934            user = new UserHandle(userId);
12935        }
12936
12937        // Only system components can circumvent runtime permissions when installing.
12938        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12939                && mContext.checkCallingOrSelfPermission(Manifest.permission
12940                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12941            throw new SecurityException("You need the "
12942                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12943                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12944        }
12945
12946        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12947                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12948            throw new IllegalArgumentException(
12949                    "New installs into ASEC containers no longer supported");
12950        }
12951
12952        final File originFile = new File(originPath);
12953        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12954
12955        final Message msg = mHandler.obtainMessage(INIT_COPY);
12956        final VerificationInfo verificationInfo = new VerificationInfo(
12957                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12958        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12959                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12960                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12961                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12962        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12963        msg.obj = params;
12964
12965        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12966                System.identityHashCode(msg.obj));
12967        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12968                System.identityHashCode(msg.obj));
12969
12970        mHandler.sendMessage(msg);
12971    }
12972
12973
12974    /**
12975     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12976     * it is acting on behalf on an enterprise or the user).
12977     *
12978     * Note that the ordering of the conditionals in this method is important. The checks we perform
12979     * are as follows, in this order:
12980     *
12981     * 1) If the install is being performed by a system app, we can trust the app to have set the
12982     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12983     *    what it is.
12984     * 2) If the install is being performed by a device or profile owner app, the install reason
12985     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12986     *    set the install reason correctly. If the app targets an older SDK version where install
12987     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12988     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12989     * 3) In all other cases, the install is being performed by a regular app that is neither part
12990     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12991     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12992     *    set to enterprise policy and if so, change it to unknown instead.
12993     */
12994    private int fixUpInstallReason(String installerPackageName, int installerUid,
12995            int installReason) {
12996        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12997                == PERMISSION_GRANTED) {
12998            // If the install is being performed by a system app, we trust that app to have set the
12999            // install reason correctly.
13000            return installReason;
13001        }
13002
13003        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13004            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13005        if (dpm != null) {
13006            ComponentName owner = null;
13007            try {
13008                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13009                if (owner == null) {
13010                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13011                }
13012            } catch (RemoteException e) {
13013            }
13014            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13015                // If the install is being performed by a device or profile owner, the install
13016                // reason should be enterprise policy.
13017                return PackageManager.INSTALL_REASON_POLICY;
13018            }
13019        }
13020
13021        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13022            // If the install is being performed by a regular app (i.e. neither system app nor
13023            // device or profile owner), we have no reason to believe that the app is acting on
13024            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13025            // change it to unknown instead.
13026            return PackageManager.INSTALL_REASON_UNKNOWN;
13027        }
13028
13029        // If the install is being performed by a regular app and the install reason was set to any
13030        // value but enterprise policy, leave the install reason unchanged.
13031        return installReason;
13032    }
13033
13034    void installStage(String packageName, File stagedDir, String stagedCid,
13035            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13036            String installerPackageName, int installerUid, UserHandle user,
13037            Certificate[][] certificates) {
13038        if (DEBUG_EPHEMERAL) {
13039            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13040                Slog.d(TAG, "Ephemeral install of " + packageName);
13041            }
13042        }
13043        final VerificationInfo verificationInfo = new VerificationInfo(
13044                sessionParams.originatingUri, sessionParams.referrerUri,
13045                sessionParams.originatingUid, installerUid);
13046
13047        final OriginInfo origin;
13048        if (stagedDir != null) {
13049            origin = OriginInfo.fromStagedFile(stagedDir);
13050        } else {
13051            origin = OriginInfo.fromStagedContainer(stagedCid);
13052        }
13053
13054        final Message msg = mHandler.obtainMessage(INIT_COPY);
13055        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13056                sessionParams.installReason);
13057        final InstallParams params = new InstallParams(origin, null, observer,
13058                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13059                verificationInfo, user, sessionParams.abiOverride,
13060                sessionParams.grantedRuntimePermissions, certificates, installReason);
13061        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13062        msg.obj = params;
13063
13064        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13065                System.identityHashCode(msg.obj));
13066        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13067                System.identityHashCode(msg.obj));
13068
13069        mHandler.sendMessage(msg);
13070    }
13071
13072    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13073            int userId) {
13074        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13075        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13076    }
13077
13078    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13079            int appId, int... userIds) {
13080        if (ArrayUtils.isEmpty(userIds)) {
13081            return;
13082        }
13083        Bundle extras = new Bundle(1);
13084        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13085        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13086
13087        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13088                packageName, extras, 0, null, null, userIds);
13089        if (isSystem) {
13090            mHandler.post(() -> {
13091                        for (int userId : userIds) {
13092                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13093                        }
13094                    }
13095            );
13096        }
13097    }
13098
13099    /**
13100     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13101     * automatically without needing an explicit launch.
13102     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13103     */
13104    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13105        // If user is not running, the app didn't miss any broadcast
13106        if (!mUserManagerInternal.isUserRunning(userId)) {
13107            return;
13108        }
13109        final IActivityManager am = ActivityManager.getService();
13110        try {
13111            // Deliver LOCKED_BOOT_COMPLETED first
13112            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13113                    .setPackage(packageName);
13114            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13115            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13116                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13117
13118            // Deliver BOOT_COMPLETED only if user is unlocked
13119            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13120                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13121                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13122                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13123            }
13124        } catch (RemoteException e) {
13125            throw e.rethrowFromSystemServer();
13126        }
13127    }
13128
13129    @Override
13130    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13131            int userId) {
13132        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13133        PackageSetting pkgSetting;
13134        final int uid = Binder.getCallingUid();
13135        enforceCrossUserPermission(uid, userId,
13136                true /* requireFullPermission */, true /* checkShell */,
13137                "setApplicationHiddenSetting for user " + userId);
13138
13139        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13140            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13141            return false;
13142        }
13143
13144        long callingId = Binder.clearCallingIdentity();
13145        try {
13146            boolean sendAdded = false;
13147            boolean sendRemoved = false;
13148            // writer
13149            synchronized (mPackages) {
13150                pkgSetting = mSettings.mPackages.get(packageName);
13151                if (pkgSetting == null) {
13152                    return false;
13153                }
13154                // Do not allow "android" is being disabled
13155                if ("android".equals(packageName)) {
13156                    Slog.w(TAG, "Cannot hide package: android");
13157                    return false;
13158                }
13159                // Cannot hide static shared libs as they are considered
13160                // a part of the using app (emulating static linking). Also
13161                // static libs are installed always on internal storage.
13162                PackageParser.Package pkg = mPackages.get(packageName);
13163                if (pkg != null && pkg.staticSharedLibName != null) {
13164                    Slog.w(TAG, "Cannot hide package: " + packageName
13165                            + " providing static shared library: "
13166                            + pkg.staticSharedLibName);
13167                    return false;
13168                }
13169                // Only allow protected packages to hide themselves.
13170                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13171                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13172                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13173                    return false;
13174                }
13175
13176                if (pkgSetting.getHidden(userId) != hidden) {
13177                    pkgSetting.setHidden(hidden, userId);
13178                    mSettings.writePackageRestrictionsLPr(userId);
13179                    if (hidden) {
13180                        sendRemoved = true;
13181                    } else {
13182                        sendAdded = true;
13183                    }
13184                }
13185            }
13186            if (sendAdded) {
13187                sendPackageAddedForUser(packageName, pkgSetting, userId);
13188                return true;
13189            }
13190            if (sendRemoved) {
13191                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13192                        "hiding pkg");
13193                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13194                return true;
13195            }
13196        } finally {
13197            Binder.restoreCallingIdentity(callingId);
13198        }
13199        return false;
13200    }
13201
13202    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13203            int userId) {
13204        final PackageRemovedInfo info = new PackageRemovedInfo();
13205        info.removedPackage = packageName;
13206        info.removedUsers = new int[] {userId};
13207        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13208        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13209    }
13210
13211    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13212        if (pkgList.length > 0) {
13213            Bundle extras = new Bundle(1);
13214            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13215
13216            sendPackageBroadcast(
13217                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13218                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13219                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13220                    new int[] {userId});
13221        }
13222    }
13223
13224    /**
13225     * Returns true if application is not found or there was an error. Otherwise it returns
13226     * the hidden state of the package for the given user.
13227     */
13228    @Override
13229    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13230        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13231        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13232                true /* requireFullPermission */, false /* checkShell */,
13233                "getApplicationHidden for user " + userId);
13234        PackageSetting pkgSetting;
13235        long callingId = Binder.clearCallingIdentity();
13236        try {
13237            // writer
13238            synchronized (mPackages) {
13239                pkgSetting = mSettings.mPackages.get(packageName);
13240                if (pkgSetting == null) {
13241                    return true;
13242                }
13243                return pkgSetting.getHidden(userId);
13244            }
13245        } finally {
13246            Binder.restoreCallingIdentity(callingId);
13247        }
13248    }
13249
13250    /**
13251     * @hide
13252     */
13253    @Override
13254    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13255            int installReason) {
13256        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13257                null);
13258        PackageSetting pkgSetting;
13259        final int uid = Binder.getCallingUid();
13260        enforceCrossUserPermission(uid, userId,
13261                true /* requireFullPermission */, true /* checkShell */,
13262                "installExistingPackage for user " + userId);
13263        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13264            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13265        }
13266
13267        long callingId = Binder.clearCallingIdentity();
13268        try {
13269            boolean installed = false;
13270            final boolean instantApp =
13271                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13272            final boolean fullApp =
13273                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13274
13275            // writer
13276            synchronized (mPackages) {
13277                pkgSetting = mSettings.mPackages.get(packageName);
13278                if (pkgSetting == null) {
13279                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13280                }
13281                if (!pkgSetting.getInstalled(userId)) {
13282                    pkgSetting.setInstalled(true, userId);
13283                    pkgSetting.setHidden(false, userId);
13284                    pkgSetting.setInstallReason(installReason, userId);
13285                    mSettings.writePackageRestrictionsLPr(userId);
13286                    mSettings.writeKernelMappingLPr(pkgSetting);
13287                    installed = true;
13288                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13289                    // upgrade app from instant to full; we don't allow app downgrade
13290                    installed = true;
13291                }
13292                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13293            }
13294
13295            if (installed) {
13296                if (pkgSetting.pkg != null) {
13297                    synchronized (mInstallLock) {
13298                        // We don't need to freeze for a brand new install
13299                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13300                    }
13301                }
13302                sendPackageAddedForUser(packageName, pkgSetting, userId);
13303                synchronized (mPackages) {
13304                    updateSequenceNumberLP(packageName, new int[]{ userId });
13305                }
13306            }
13307        } finally {
13308            Binder.restoreCallingIdentity(callingId);
13309        }
13310
13311        return PackageManager.INSTALL_SUCCEEDED;
13312    }
13313
13314    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13315            boolean instantApp, boolean fullApp) {
13316        // no state specified; do nothing
13317        if (!instantApp && !fullApp) {
13318            return;
13319        }
13320        if (userId != UserHandle.USER_ALL) {
13321            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13322                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13323            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13324                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13325            }
13326        } else {
13327            for (int currentUserId : sUserManager.getUserIds()) {
13328                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13329                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13330                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13331                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13332                }
13333            }
13334        }
13335    }
13336
13337    boolean isUserRestricted(int userId, String restrictionKey) {
13338        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13339        if (restrictions.getBoolean(restrictionKey, false)) {
13340            Log.w(TAG, "User is restricted: " + restrictionKey);
13341            return true;
13342        }
13343        return false;
13344    }
13345
13346    @Override
13347    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13348            int userId) {
13349        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13350        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13351                true /* requireFullPermission */, true /* checkShell */,
13352                "setPackagesSuspended for user " + userId);
13353
13354        if (ArrayUtils.isEmpty(packageNames)) {
13355            return packageNames;
13356        }
13357
13358        // List of package names for whom the suspended state has changed.
13359        List<String> changedPackages = new ArrayList<>(packageNames.length);
13360        // List of package names for whom the suspended state is not set as requested in this
13361        // method.
13362        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13363        long callingId = Binder.clearCallingIdentity();
13364        try {
13365            for (int i = 0; i < packageNames.length; i++) {
13366                String packageName = packageNames[i];
13367                boolean changed = false;
13368                final int appId;
13369                synchronized (mPackages) {
13370                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13371                    if (pkgSetting == null) {
13372                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13373                                + "\". Skipping suspending/un-suspending.");
13374                        unactionedPackages.add(packageName);
13375                        continue;
13376                    }
13377                    appId = pkgSetting.appId;
13378                    if (pkgSetting.getSuspended(userId) != suspended) {
13379                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13380                            unactionedPackages.add(packageName);
13381                            continue;
13382                        }
13383                        pkgSetting.setSuspended(suspended, userId);
13384                        mSettings.writePackageRestrictionsLPr(userId);
13385                        changed = true;
13386                        changedPackages.add(packageName);
13387                    }
13388                }
13389
13390                if (changed && suspended) {
13391                    killApplication(packageName, UserHandle.getUid(userId, appId),
13392                            "suspending package");
13393                }
13394            }
13395        } finally {
13396            Binder.restoreCallingIdentity(callingId);
13397        }
13398
13399        if (!changedPackages.isEmpty()) {
13400            sendPackagesSuspendedForUser(changedPackages.toArray(
13401                    new String[changedPackages.size()]), userId, suspended);
13402        }
13403
13404        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13405    }
13406
13407    @Override
13408    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13409        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13410                true /* requireFullPermission */, false /* checkShell */,
13411                "isPackageSuspendedForUser for user " + userId);
13412        synchronized (mPackages) {
13413            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13414            if (pkgSetting == null) {
13415                throw new IllegalArgumentException("Unknown target package: " + packageName);
13416            }
13417            return pkgSetting.getSuspended(userId);
13418        }
13419    }
13420
13421    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13422        if (isPackageDeviceAdmin(packageName, userId)) {
13423            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13424                    + "\": has an active device admin");
13425            return false;
13426        }
13427
13428        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13429        if (packageName.equals(activeLauncherPackageName)) {
13430            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13431                    + "\": contains the active launcher");
13432            return false;
13433        }
13434
13435        if (packageName.equals(mRequiredInstallerPackage)) {
13436            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13437                    + "\": required for package installation");
13438            return false;
13439        }
13440
13441        if (packageName.equals(mRequiredUninstallerPackage)) {
13442            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13443                    + "\": required for package uninstallation");
13444            return false;
13445        }
13446
13447        if (packageName.equals(mRequiredVerifierPackage)) {
13448            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13449                    + "\": required for package verification");
13450            return false;
13451        }
13452
13453        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13454            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13455                    + "\": is the default dialer");
13456            return false;
13457        }
13458
13459        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13460            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13461                    + "\": protected package");
13462            return false;
13463        }
13464
13465        // Cannot suspend static shared libs as they are considered
13466        // a part of the using app (emulating static linking). Also
13467        // static libs are installed always on internal storage.
13468        PackageParser.Package pkg = mPackages.get(packageName);
13469        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13470            Slog.w(TAG, "Cannot suspend package: " + packageName
13471                    + " providing static shared library: "
13472                    + pkg.staticSharedLibName);
13473            return false;
13474        }
13475
13476        return true;
13477    }
13478
13479    private String getActiveLauncherPackageName(int userId) {
13480        Intent intent = new Intent(Intent.ACTION_MAIN);
13481        intent.addCategory(Intent.CATEGORY_HOME);
13482        ResolveInfo resolveInfo = resolveIntent(
13483                intent,
13484                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13485                PackageManager.MATCH_DEFAULT_ONLY,
13486                userId);
13487
13488        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13489    }
13490
13491    private String getDefaultDialerPackageName(int userId) {
13492        synchronized (mPackages) {
13493            return mSettings.getDefaultDialerPackageNameLPw(userId);
13494        }
13495    }
13496
13497    @Override
13498    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13499        mContext.enforceCallingOrSelfPermission(
13500                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13501                "Only package verification agents can verify applications");
13502
13503        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13504        final PackageVerificationResponse response = new PackageVerificationResponse(
13505                verificationCode, Binder.getCallingUid());
13506        msg.arg1 = id;
13507        msg.obj = response;
13508        mHandler.sendMessage(msg);
13509    }
13510
13511    @Override
13512    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13513            long millisecondsToDelay) {
13514        mContext.enforceCallingOrSelfPermission(
13515                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13516                "Only package verification agents can extend verification timeouts");
13517
13518        final PackageVerificationState state = mPendingVerification.get(id);
13519        final PackageVerificationResponse response = new PackageVerificationResponse(
13520                verificationCodeAtTimeout, Binder.getCallingUid());
13521
13522        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13523            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13524        }
13525        if (millisecondsToDelay < 0) {
13526            millisecondsToDelay = 0;
13527        }
13528        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13529                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13530            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13531        }
13532
13533        if ((state != null) && !state.timeoutExtended()) {
13534            state.extendTimeout();
13535
13536            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13537            msg.arg1 = id;
13538            msg.obj = response;
13539            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13540        }
13541    }
13542
13543    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13544            int verificationCode, UserHandle user) {
13545        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13546        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13547        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13548        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13549        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13550
13551        mContext.sendBroadcastAsUser(intent, user,
13552                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13553    }
13554
13555    private ComponentName matchComponentForVerifier(String packageName,
13556            List<ResolveInfo> receivers) {
13557        ActivityInfo targetReceiver = null;
13558
13559        final int NR = receivers.size();
13560        for (int i = 0; i < NR; i++) {
13561            final ResolveInfo info = receivers.get(i);
13562            if (info.activityInfo == null) {
13563                continue;
13564            }
13565
13566            if (packageName.equals(info.activityInfo.packageName)) {
13567                targetReceiver = info.activityInfo;
13568                break;
13569            }
13570        }
13571
13572        if (targetReceiver == null) {
13573            return null;
13574        }
13575
13576        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13577    }
13578
13579    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13580            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13581        if (pkgInfo.verifiers.length == 0) {
13582            return null;
13583        }
13584
13585        final int N = pkgInfo.verifiers.length;
13586        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13587        for (int i = 0; i < N; i++) {
13588            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13589
13590            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13591                    receivers);
13592            if (comp == null) {
13593                continue;
13594            }
13595
13596            final int verifierUid = getUidForVerifier(verifierInfo);
13597            if (verifierUid == -1) {
13598                continue;
13599            }
13600
13601            if (DEBUG_VERIFY) {
13602                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13603                        + " with the correct signature");
13604            }
13605            sufficientVerifiers.add(comp);
13606            verificationState.addSufficientVerifier(verifierUid);
13607        }
13608
13609        return sufficientVerifiers;
13610    }
13611
13612    private int getUidForVerifier(VerifierInfo verifierInfo) {
13613        synchronized (mPackages) {
13614            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13615            if (pkg == null) {
13616                return -1;
13617            } else if (pkg.mSignatures.length != 1) {
13618                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13619                        + " has more than one signature; ignoring");
13620                return -1;
13621            }
13622
13623            /*
13624             * If the public key of the package's signature does not match
13625             * our expected public key, then this is a different package and
13626             * we should skip.
13627             */
13628
13629            final byte[] expectedPublicKey;
13630            try {
13631                final Signature verifierSig = pkg.mSignatures[0];
13632                final PublicKey publicKey = verifierSig.getPublicKey();
13633                expectedPublicKey = publicKey.getEncoded();
13634            } catch (CertificateException e) {
13635                return -1;
13636            }
13637
13638            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13639
13640            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13641                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13642                        + " does not have the expected public key; ignoring");
13643                return -1;
13644            }
13645
13646            return pkg.applicationInfo.uid;
13647        }
13648    }
13649
13650    @Override
13651    public void finishPackageInstall(int token, boolean didLaunch) {
13652        enforceSystemOrRoot("Only the system is allowed to finish installs");
13653
13654        if (DEBUG_INSTALL) {
13655            Slog.v(TAG, "BM finishing package install for " + token);
13656        }
13657        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13658
13659        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13660        mHandler.sendMessage(msg);
13661    }
13662
13663    /**
13664     * Get the verification agent timeout.
13665     *
13666     * @return verification timeout in milliseconds
13667     */
13668    private long getVerificationTimeout() {
13669        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13670                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13671                DEFAULT_VERIFICATION_TIMEOUT);
13672    }
13673
13674    /**
13675     * Get the default verification agent response code.
13676     *
13677     * @return default verification response code
13678     */
13679    private int getDefaultVerificationResponse() {
13680        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13681                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13682                DEFAULT_VERIFICATION_RESPONSE);
13683    }
13684
13685    /**
13686     * Check whether or not package verification has been enabled.
13687     *
13688     * @return true if verification should be performed
13689     */
13690    private boolean isVerificationEnabled(int userId, int installFlags) {
13691        if (!DEFAULT_VERIFY_ENABLE) {
13692            return false;
13693        }
13694
13695        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13696
13697        // Check if installing from ADB
13698        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13699            // Do not run verification in a test harness environment
13700            if (ActivityManager.isRunningInTestHarness()) {
13701                return false;
13702            }
13703            if (ensureVerifyAppsEnabled) {
13704                return true;
13705            }
13706            // Check if the developer does not want package verification for ADB installs
13707            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13708                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13709                return false;
13710            }
13711        }
13712
13713        if (ensureVerifyAppsEnabled) {
13714            return true;
13715        }
13716
13717        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13718                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13719    }
13720
13721    @Override
13722    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13723            throws RemoteException {
13724        mContext.enforceCallingOrSelfPermission(
13725                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13726                "Only intentfilter verification agents can verify applications");
13727
13728        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13729        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13730                Binder.getCallingUid(), verificationCode, failedDomains);
13731        msg.arg1 = id;
13732        msg.obj = response;
13733        mHandler.sendMessage(msg);
13734    }
13735
13736    @Override
13737    public int getIntentVerificationStatus(String packageName, int userId) {
13738        synchronized (mPackages) {
13739            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13740        }
13741    }
13742
13743    @Override
13744    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13745        mContext.enforceCallingOrSelfPermission(
13746                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13747
13748        boolean result = false;
13749        synchronized (mPackages) {
13750            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13751        }
13752        if (result) {
13753            scheduleWritePackageRestrictionsLocked(userId);
13754        }
13755        return result;
13756    }
13757
13758    @Override
13759    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13760            String packageName) {
13761        synchronized (mPackages) {
13762            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13763        }
13764    }
13765
13766    @Override
13767    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13768        if (TextUtils.isEmpty(packageName)) {
13769            return ParceledListSlice.emptyList();
13770        }
13771        synchronized (mPackages) {
13772            PackageParser.Package pkg = mPackages.get(packageName);
13773            if (pkg == null || pkg.activities == null) {
13774                return ParceledListSlice.emptyList();
13775            }
13776            final int count = pkg.activities.size();
13777            ArrayList<IntentFilter> result = new ArrayList<>();
13778            for (int n=0; n<count; n++) {
13779                PackageParser.Activity activity = pkg.activities.get(n);
13780                if (activity.intents != null && activity.intents.size() > 0) {
13781                    result.addAll(activity.intents);
13782                }
13783            }
13784            return new ParceledListSlice<>(result);
13785        }
13786    }
13787
13788    @Override
13789    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13790        mContext.enforceCallingOrSelfPermission(
13791                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13792
13793        synchronized (mPackages) {
13794            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13795            if (packageName != null) {
13796                result |= updateIntentVerificationStatus(packageName,
13797                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13798                        userId);
13799                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13800                        packageName, userId);
13801            }
13802            return result;
13803        }
13804    }
13805
13806    @Override
13807    public String getDefaultBrowserPackageName(int userId) {
13808        synchronized (mPackages) {
13809            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13810        }
13811    }
13812
13813    /**
13814     * Get the "allow unknown sources" setting.
13815     *
13816     * @return the current "allow unknown sources" setting
13817     */
13818    private int getUnknownSourcesSettings() {
13819        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13820                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13821                -1);
13822    }
13823
13824    @Override
13825    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13826        final int uid = Binder.getCallingUid();
13827        // writer
13828        synchronized (mPackages) {
13829            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13830            if (targetPackageSetting == null) {
13831                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13832            }
13833
13834            PackageSetting installerPackageSetting;
13835            if (installerPackageName != null) {
13836                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13837                if (installerPackageSetting == null) {
13838                    throw new IllegalArgumentException("Unknown installer package: "
13839                            + installerPackageName);
13840                }
13841            } else {
13842                installerPackageSetting = null;
13843            }
13844
13845            Signature[] callerSignature;
13846            Object obj = mSettings.getUserIdLPr(uid);
13847            if (obj != null) {
13848                if (obj instanceof SharedUserSetting) {
13849                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13850                } else if (obj instanceof PackageSetting) {
13851                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13852                } else {
13853                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13854                }
13855            } else {
13856                throw new SecurityException("Unknown calling UID: " + uid);
13857            }
13858
13859            // Verify: can't set installerPackageName to a package that is
13860            // not signed with the same cert as the caller.
13861            if (installerPackageSetting != null) {
13862                if (compareSignatures(callerSignature,
13863                        installerPackageSetting.signatures.mSignatures)
13864                        != PackageManager.SIGNATURE_MATCH) {
13865                    throw new SecurityException(
13866                            "Caller does not have same cert as new installer package "
13867                            + installerPackageName);
13868                }
13869            }
13870
13871            // Verify: if target already has an installer package, it must
13872            // be signed with the same cert as the caller.
13873            if (targetPackageSetting.installerPackageName != null) {
13874                PackageSetting setting = mSettings.mPackages.get(
13875                        targetPackageSetting.installerPackageName);
13876                // If the currently set package isn't valid, then it's always
13877                // okay to change it.
13878                if (setting != null) {
13879                    if (compareSignatures(callerSignature,
13880                            setting.signatures.mSignatures)
13881                            != PackageManager.SIGNATURE_MATCH) {
13882                        throw new SecurityException(
13883                                "Caller does not have same cert as old installer package "
13884                                + targetPackageSetting.installerPackageName);
13885                    }
13886                }
13887            }
13888
13889            // Okay!
13890            targetPackageSetting.installerPackageName = installerPackageName;
13891            if (installerPackageName != null) {
13892                mSettings.mInstallerPackages.add(installerPackageName);
13893            }
13894            scheduleWriteSettingsLocked();
13895        }
13896    }
13897
13898    @Override
13899    public void setApplicationCategoryHint(String packageName, int categoryHint,
13900            String callerPackageName) {
13901        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13902                callerPackageName);
13903        synchronized (mPackages) {
13904            PackageSetting ps = mSettings.mPackages.get(packageName);
13905            if (ps == null) {
13906                throw new IllegalArgumentException("Unknown target package " + packageName);
13907            }
13908
13909            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13910                throw new IllegalArgumentException("Calling package " + callerPackageName
13911                        + " is not installer for " + packageName);
13912            }
13913
13914            if (ps.categoryHint != categoryHint) {
13915                ps.categoryHint = categoryHint;
13916                scheduleWriteSettingsLocked();
13917            }
13918        }
13919    }
13920
13921    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13922        // Queue up an async operation since the package installation may take a little while.
13923        mHandler.post(new Runnable() {
13924            public void run() {
13925                mHandler.removeCallbacks(this);
13926                 // Result object to be returned
13927                PackageInstalledInfo res = new PackageInstalledInfo();
13928                res.setReturnCode(currentStatus);
13929                res.uid = -1;
13930                res.pkg = null;
13931                res.removedInfo = null;
13932                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13933                    args.doPreInstall(res.returnCode);
13934                    synchronized (mInstallLock) {
13935                        installPackageTracedLI(args, res);
13936                    }
13937                    args.doPostInstall(res.returnCode, res.uid);
13938                }
13939
13940                // A restore should be performed at this point if (a) the install
13941                // succeeded, (b) the operation is not an update, and (c) the new
13942                // package has not opted out of backup participation.
13943                final boolean update = res.removedInfo != null
13944                        && res.removedInfo.removedPackage != null;
13945                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13946                boolean doRestore = !update
13947                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13948
13949                // Set up the post-install work request bookkeeping.  This will be used
13950                // and cleaned up by the post-install event handling regardless of whether
13951                // there's a restore pass performed.  Token values are >= 1.
13952                int token;
13953                if (mNextInstallToken < 0) mNextInstallToken = 1;
13954                token = mNextInstallToken++;
13955
13956                PostInstallData data = new PostInstallData(args, res);
13957                mRunningInstalls.put(token, data);
13958                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13959
13960                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13961                    // Pass responsibility to the Backup Manager.  It will perform a
13962                    // restore if appropriate, then pass responsibility back to the
13963                    // Package Manager to run the post-install observer callbacks
13964                    // and broadcasts.
13965                    IBackupManager bm = IBackupManager.Stub.asInterface(
13966                            ServiceManager.getService(Context.BACKUP_SERVICE));
13967                    if (bm != null) {
13968                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13969                                + " to BM for possible restore");
13970                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13971                        try {
13972                            // TODO: http://b/22388012
13973                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13974                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13975                            } else {
13976                                doRestore = false;
13977                            }
13978                        } catch (RemoteException e) {
13979                            // can't happen; the backup manager is local
13980                        } catch (Exception e) {
13981                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13982                            doRestore = false;
13983                        }
13984                    } else {
13985                        Slog.e(TAG, "Backup Manager not found!");
13986                        doRestore = false;
13987                    }
13988                }
13989
13990                if (!doRestore) {
13991                    // No restore possible, or the Backup Manager was mysteriously not
13992                    // available -- just fire the post-install work request directly.
13993                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13994
13995                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13996
13997                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13998                    mHandler.sendMessage(msg);
13999                }
14000            }
14001        });
14002    }
14003
14004    /**
14005     * Callback from PackageSettings whenever an app is first transitioned out of the
14006     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14007     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14008     * here whether the app is the target of an ongoing install, and only send the
14009     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14010     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14011     * handling.
14012     */
14013    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14014        // Serialize this with the rest of the install-process message chain.  In the
14015        // restore-at-install case, this Runnable will necessarily run before the
14016        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14017        // are coherent.  In the non-restore case, the app has already completed install
14018        // and been launched through some other means, so it is not in a problematic
14019        // state for observers to see the FIRST_LAUNCH signal.
14020        mHandler.post(new Runnable() {
14021            @Override
14022            public void run() {
14023                for (int i = 0; i < mRunningInstalls.size(); i++) {
14024                    final PostInstallData data = mRunningInstalls.valueAt(i);
14025                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14026                        continue;
14027                    }
14028                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14029                        // right package; but is it for the right user?
14030                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14031                            if (userId == data.res.newUsers[uIndex]) {
14032                                if (DEBUG_BACKUP) {
14033                                    Slog.i(TAG, "Package " + pkgName
14034                                            + " being restored so deferring FIRST_LAUNCH");
14035                                }
14036                                return;
14037                            }
14038                        }
14039                    }
14040                }
14041                // didn't find it, so not being restored
14042                if (DEBUG_BACKUP) {
14043                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14044                }
14045                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14046            }
14047        });
14048    }
14049
14050    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14051        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14052                installerPkg, null, userIds);
14053    }
14054
14055    private abstract class HandlerParams {
14056        private static final int MAX_RETRIES = 4;
14057
14058        /**
14059         * Number of times startCopy() has been attempted and had a non-fatal
14060         * error.
14061         */
14062        private int mRetries = 0;
14063
14064        /** User handle for the user requesting the information or installation. */
14065        private final UserHandle mUser;
14066        String traceMethod;
14067        int traceCookie;
14068
14069        HandlerParams(UserHandle user) {
14070            mUser = user;
14071        }
14072
14073        UserHandle getUser() {
14074            return mUser;
14075        }
14076
14077        HandlerParams setTraceMethod(String traceMethod) {
14078            this.traceMethod = traceMethod;
14079            return this;
14080        }
14081
14082        HandlerParams setTraceCookie(int traceCookie) {
14083            this.traceCookie = traceCookie;
14084            return this;
14085        }
14086
14087        final boolean startCopy() {
14088            boolean res;
14089            try {
14090                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14091
14092                if (++mRetries > MAX_RETRIES) {
14093                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14094                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14095                    handleServiceError();
14096                    return false;
14097                } else {
14098                    handleStartCopy();
14099                    res = true;
14100                }
14101            } catch (RemoteException e) {
14102                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14103                mHandler.sendEmptyMessage(MCS_RECONNECT);
14104                res = false;
14105            }
14106            handleReturnCode();
14107            return res;
14108        }
14109
14110        final void serviceError() {
14111            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14112            handleServiceError();
14113            handleReturnCode();
14114        }
14115
14116        abstract void handleStartCopy() throws RemoteException;
14117        abstract void handleServiceError();
14118        abstract void handleReturnCode();
14119    }
14120
14121    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14122        for (File path : paths) {
14123            try {
14124                mcs.clearDirectory(path.getAbsolutePath());
14125            } catch (RemoteException e) {
14126            }
14127        }
14128    }
14129
14130    static class OriginInfo {
14131        /**
14132         * Location where install is coming from, before it has been
14133         * copied/renamed into place. This could be a single monolithic APK
14134         * file, or a cluster directory. This location may be untrusted.
14135         */
14136        final File file;
14137        final String cid;
14138
14139        /**
14140         * Flag indicating that {@link #file} or {@link #cid} has already been
14141         * staged, meaning downstream users don't need to defensively copy the
14142         * contents.
14143         */
14144        final boolean staged;
14145
14146        /**
14147         * Flag indicating that {@link #file} or {@link #cid} is an already
14148         * installed app that is being moved.
14149         */
14150        final boolean existing;
14151
14152        final String resolvedPath;
14153        final File resolvedFile;
14154
14155        static OriginInfo fromNothing() {
14156            return new OriginInfo(null, null, false, false);
14157        }
14158
14159        static OriginInfo fromUntrustedFile(File file) {
14160            return new OriginInfo(file, null, false, false);
14161        }
14162
14163        static OriginInfo fromExistingFile(File file) {
14164            return new OriginInfo(file, null, false, true);
14165        }
14166
14167        static OriginInfo fromStagedFile(File file) {
14168            return new OriginInfo(file, null, true, false);
14169        }
14170
14171        static OriginInfo fromStagedContainer(String cid) {
14172            return new OriginInfo(null, cid, true, false);
14173        }
14174
14175        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14176            this.file = file;
14177            this.cid = cid;
14178            this.staged = staged;
14179            this.existing = existing;
14180
14181            if (cid != null) {
14182                resolvedPath = PackageHelper.getSdDir(cid);
14183                resolvedFile = new File(resolvedPath);
14184            } else if (file != null) {
14185                resolvedPath = file.getAbsolutePath();
14186                resolvedFile = file;
14187            } else {
14188                resolvedPath = null;
14189                resolvedFile = null;
14190            }
14191        }
14192    }
14193
14194    static class MoveInfo {
14195        final int moveId;
14196        final String fromUuid;
14197        final String toUuid;
14198        final String packageName;
14199        final String dataAppName;
14200        final int appId;
14201        final String seinfo;
14202        final int targetSdkVersion;
14203
14204        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14205                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14206            this.moveId = moveId;
14207            this.fromUuid = fromUuid;
14208            this.toUuid = toUuid;
14209            this.packageName = packageName;
14210            this.dataAppName = dataAppName;
14211            this.appId = appId;
14212            this.seinfo = seinfo;
14213            this.targetSdkVersion = targetSdkVersion;
14214        }
14215    }
14216
14217    static class VerificationInfo {
14218        /** A constant used to indicate that a uid value is not present. */
14219        public static final int NO_UID = -1;
14220
14221        /** URI referencing where the package was downloaded from. */
14222        final Uri originatingUri;
14223
14224        /** HTTP referrer URI associated with the originatingURI. */
14225        final Uri referrer;
14226
14227        /** UID of the application that the install request originated from. */
14228        final int originatingUid;
14229
14230        /** UID of application requesting the install */
14231        final int installerUid;
14232
14233        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14234            this.originatingUri = originatingUri;
14235            this.referrer = referrer;
14236            this.originatingUid = originatingUid;
14237            this.installerUid = installerUid;
14238        }
14239    }
14240
14241    class InstallParams extends HandlerParams {
14242        final OriginInfo origin;
14243        final MoveInfo move;
14244        final IPackageInstallObserver2 observer;
14245        int installFlags;
14246        final String installerPackageName;
14247        final String volumeUuid;
14248        private InstallArgs mArgs;
14249        private int mRet;
14250        final String packageAbiOverride;
14251        final String[] grantedRuntimePermissions;
14252        final VerificationInfo verificationInfo;
14253        final Certificate[][] certificates;
14254        final int installReason;
14255
14256        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14257                int installFlags, String installerPackageName, String volumeUuid,
14258                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14259                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14260            super(user);
14261            this.origin = origin;
14262            this.move = move;
14263            this.observer = observer;
14264            this.installFlags = installFlags;
14265            this.installerPackageName = installerPackageName;
14266            this.volumeUuid = volumeUuid;
14267            this.verificationInfo = verificationInfo;
14268            this.packageAbiOverride = packageAbiOverride;
14269            this.grantedRuntimePermissions = grantedPermissions;
14270            this.certificates = certificates;
14271            this.installReason = installReason;
14272        }
14273
14274        @Override
14275        public String toString() {
14276            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14277                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14278        }
14279
14280        private int installLocationPolicy(PackageInfoLite pkgLite) {
14281            String packageName = pkgLite.packageName;
14282            int installLocation = pkgLite.installLocation;
14283            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14284            // reader
14285            synchronized (mPackages) {
14286                // Currently installed package which the new package is attempting to replace or
14287                // null if no such package is installed.
14288                PackageParser.Package installedPkg = mPackages.get(packageName);
14289                // Package which currently owns the data which the new package will own if installed.
14290                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14291                // will be null whereas dataOwnerPkg will contain information about the package
14292                // which was uninstalled while keeping its data.
14293                PackageParser.Package dataOwnerPkg = installedPkg;
14294                if (dataOwnerPkg  == null) {
14295                    PackageSetting ps = mSettings.mPackages.get(packageName);
14296                    if (ps != null) {
14297                        dataOwnerPkg = ps.pkg;
14298                    }
14299                }
14300
14301                if (dataOwnerPkg != null) {
14302                    // If installed, the package will get access to data left on the device by its
14303                    // predecessor. As a security measure, this is permited only if this is not a
14304                    // version downgrade or if the predecessor package is marked as debuggable and
14305                    // a downgrade is explicitly requested.
14306                    //
14307                    // On debuggable platform builds, downgrades are permitted even for
14308                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14309                    // not offer security guarantees and thus it's OK to disable some security
14310                    // mechanisms to make debugging/testing easier on those builds. However, even on
14311                    // debuggable builds downgrades of packages are permitted only if requested via
14312                    // installFlags. This is because we aim to keep the behavior of debuggable
14313                    // platform builds as close as possible to the behavior of non-debuggable
14314                    // platform builds.
14315                    final boolean downgradeRequested =
14316                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14317                    final boolean packageDebuggable =
14318                                (dataOwnerPkg.applicationInfo.flags
14319                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14320                    final boolean downgradePermitted =
14321                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14322                    if (!downgradePermitted) {
14323                        try {
14324                            checkDowngrade(dataOwnerPkg, pkgLite);
14325                        } catch (PackageManagerException e) {
14326                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14327                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14328                        }
14329                    }
14330                }
14331
14332                if (installedPkg != null) {
14333                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14334                        // Check for updated system application.
14335                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14336                            if (onSd) {
14337                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14338                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14339                            }
14340                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14341                        } else {
14342                            if (onSd) {
14343                                // Install flag overrides everything.
14344                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14345                            }
14346                            // If current upgrade specifies particular preference
14347                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14348                                // Application explicitly specified internal.
14349                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14350                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14351                                // App explictly prefers external. Let policy decide
14352                            } else {
14353                                // Prefer previous location
14354                                if (isExternal(installedPkg)) {
14355                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14356                                }
14357                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14358                            }
14359                        }
14360                    } else {
14361                        // Invalid install. Return error code
14362                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14363                    }
14364                }
14365            }
14366            // All the special cases have been taken care of.
14367            // Return result based on recommended install location.
14368            if (onSd) {
14369                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14370            }
14371            return pkgLite.recommendedInstallLocation;
14372        }
14373
14374        /*
14375         * Invoke remote method to get package information and install
14376         * location values. Override install location based on default
14377         * policy if needed and then create install arguments based
14378         * on the install location.
14379         */
14380        public void handleStartCopy() throws RemoteException {
14381            int ret = PackageManager.INSTALL_SUCCEEDED;
14382
14383            // If we're already staged, we've firmly committed to an install location
14384            if (origin.staged) {
14385                if (origin.file != null) {
14386                    installFlags |= PackageManager.INSTALL_INTERNAL;
14387                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14388                } else if (origin.cid != null) {
14389                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14390                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14391                } else {
14392                    throw new IllegalStateException("Invalid stage location");
14393                }
14394            }
14395
14396            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14397            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14398            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14399            PackageInfoLite pkgLite = null;
14400
14401            if (onInt && onSd) {
14402                // Check if both bits are set.
14403                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14404                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14405            } else if (onSd && ephemeral) {
14406                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14407                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14408            } else {
14409                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14410                        packageAbiOverride);
14411
14412                if (DEBUG_EPHEMERAL && ephemeral) {
14413                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14414                }
14415
14416                /*
14417                 * If we have too little free space, try to free cache
14418                 * before giving up.
14419                 */
14420                if (!origin.staged && pkgLite.recommendedInstallLocation
14421                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14422                    // TODO: focus freeing disk space on the target device
14423                    final StorageManager storage = StorageManager.from(mContext);
14424                    final long lowThreshold = storage.getStorageLowBytes(
14425                            Environment.getDataDirectory());
14426
14427                    final long sizeBytes = mContainerService.calculateInstalledSize(
14428                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14429
14430                    try {
14431                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14432                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14433                                installFlags, packageAbiOverride);
14434                    } catch (InstallerException e) {
14435                        Slog.w(TAG, "Failed to free cache", e);
14436                    }
14437
14438                    /*
14439                     * The cache free must have deleted the file we
14440                     * downloaded to install.
14441                     *
14442                     * TODO: fix the "freeCache" call to not delete
14443                     *       the file we care about.
14444                     */
14445                    if (pkgLite.recommendedInstallLocation
14446                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14447                        pkgLite.recommendedInstallLocation
14448                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14449                    }
14450                }
14451            }
14452
14453            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14454                int loc = pkgLite.recommendedInstallLocation;
14455                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14456                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14457                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14458                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14459                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14460                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14461                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14462                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14463                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14464                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14465                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14466                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14467                } else {
14468                    // Override with defaults if needed.
14469                    loc = installLocationPolicy(pkgLite);
14470                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14471                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14472                    } else if (!onSd && !onInt) {
14473                        // Override install location with flags
14474                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14475                            // Set the flag to install on external media.
14476                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14477                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14478                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14479                            if (DEBUG_EPHEMERAL) {
14480                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14481                            }
14482                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14483                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14484                                    |PackageManager.INSTALL_INTERNAL);
14485                        } else {
14486                            // Make sure the flag for installing on external
14487                            // media is unset
14488                            installFlags |= PackageManager.INSTALL_INTERNAL;
14489                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14490                        }
14491                    }
14492                }
14493            }
14494
14495            final InstallArgs args = createInstallArgs(this);
14496            mArgs = args;
14497
14498            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14499                // TODO: http://b/22976637
14500                // Apps installed for "all" users use the device owner to verify the app
14501                UserHandle verifierUser = getUser();
14502                if (verifierUser == UserHandle.ALL) {
14503                    verifierUser = UserHandle.SYSTEM;
14504                }
14505
14506                /*
14507                 * Determine if we have any installed package verifiers. If we
14508                 * do, then we'll defer to them to verify the packages.
14509                 */
14510                final int requiredUid = mRequiredVerifierPackage == null ? -1
14511                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14512                                verifierUser.getIdentifier());
14513                if (!origin.existing && requiredUid != -1
14514                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14515                    final Intent verification = new Intent(
14516                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14517                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14518                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14519                            PACKAGE_MIME_TYPE);
14520                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14521
14522                    // Query all live verifiers based on current user state
14523                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14524                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14525
14526                    if (DEBUG_VERIFY) {
14527                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14528                                + verification.toString() + " with " + pkgLite.verifiers.length
14529                                + " optional verifiers");
14530                    }
14531
14532                    final int verificationId = mPendingVerificationToken++;
14533
14534                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14535
14536                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14537                            installerPackageName);
14538
14539                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14540                            installFlags);
14541
14542                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14543                            pkgLite.packageName);
14544
14545                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14546                            pkgLite.versionCode);
14547
14548                    if (verificationInfo != null) {
14549                        if (verificationInfo.originatingUri != null) {
14550                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14551                                    verificationInfo.originatingUri);
14552                        }
14553                        if (verificationInfo.referrer != null) {
14554                            verification.putExtra(Intent.EXTRA_REFERRER,
14555                                    verificationInfo.referrer);
14556                        }
14557                        if (verificationInfo.originatingUid >= 0) {
14558                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14559                                    verificationInfo.originatingUid);
14560                        }
14561                        if (verificationInfo.installerUid >= 0) {
14562                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14563                                    verificationInfo.installerUid);
14564                        }
14565                    }
14566
14567                    final PackageVerificationState verificationState = new PackageVerificationState(
14568                            requiredUid, args);
14569
14570                    mPendingVerification.append(verificationId, verificationState);
14571
14572                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14573                            receivers, verificationState);
14574
14575                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14576                    final long idleDuration = getVerificationTimeout();
14577
14578                    /*
14579                     * If any sufficient verifiers were listed in the package
14580                     * manifest, attempt to ask them.
14581                     */
14582                    if (sufficientVerifiers != null) {
14583                        final int N = sufficientVerifiers.size();
14584                        if (N == 0) {
14585                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14586                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14587                        } else {
14588                            for (int i = 0; i < N; i++) {
14589                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14590                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14591                                        verifierComponent.getPackageName(), idleDuration,
14592                                        verifierUser.getIdentifier(), false, "package verifier");
14593
14594                                final Intent sufficientIntent = new Intent(verification);
14595                                sufficientIntent.setComponent(verifierComponent);
14596                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14597                            }
14598                        }
14599                    }
14600
14601                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14602                            mRequiredVerifierPackage, receivers);
14603                    if (ret == PackageManager.INSTALL_SUCCEEDED
14604                            && mRequiredVerifierPackage != null) {
14605                        Trace.asyncTraceBegin(
14606                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14607                        /*
14608                         * Send the intent to the required verification agent,
14609                         * but only start the verification timeout after the
14610                         * target BroadcastReceivers have run.
14611                         */
14612                        verification.setComponent(requiredVerifierComponent);
14613                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14614                                mRequiredVerifierPackage, idleDuration,
14615                                verifierUser.getIdentifier(), false, "package verifier");
14616                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14617                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14618                                new BroadcastReceiver() {
14619                                    @Override
14620                                    public void onReceive(Context context, Intent intent) {
14621                                        final Message msg = mHandler
14622                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14623                                        msg.arg1 = verificationId;
14624                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14625                                    }
14626                                }, null, 0, null, null);
14627
14628                        /*
14629                         * We don't want the copy to proceed until verification
14630                         * succeeds, so null out this field.
14631                         */
14632                        mArgs = null;
14633                    }
14634                } else {
14635                    /*
14636                     * No package verification is enabled, so immediately start
14637                     * the remote call to initiate copy using temporary file.
14638                     */
14639                    ret = args.copyApk(mContainerService, true);
14640                }
14641            }
14642
14643            mRet = ret;
14644        }
14645
14646        @Override
14647        void handleReturnCode() {
14648            // If mArgs is null, then MCS couldn't be reached. When it
14649            // reconnects, it will try again to install. At that point, this
14650            // will succeed.
14651            if (mArgs != null) {
14652                processPendingInstall(mArgs, mRet);
14653            }
14654        }
14655
14656        @Override
14657        void handleServiceError() {
14658            mArgs = createInstallArgs(this);
14659            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14660        }
14661
14662        public boolean isForwardLocked() {
14663            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14664        }
14665    }
14666
14667    /**
14668     * Used during creation of InstallArgs
14669     *
14670     * @param installFlags package installation flags
14671     * @return true if should be installed on external storage
14672     */
14673    private static boolean installOnExternalAsec(int installFlags) {
14674        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14675            return false;
14676        }
14677        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14678            return true;
14679        }
14680        return false;
14681    }
14682
14683    /**
14684     * Used during creation of InstallArgs
14685     *
14686     * @param installFlags package installation flags
14687     * @return true if should be installed as forward locked
14688     */
14689    private static boolean installForwardLocked(int installFlags) {
14690        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14691    }
14692
14693    private InstallArgs createInstallArgs(InstallParams params) {
14694        if (params.move != null) {
14695            return new MoveInstallArgs(params);
14696        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14697            return new AsecInstallArgs(params);
14698        } else {
14699            return new FileInstallArgs(params);
14700        }
14701    }
14702
14703    /**
14704     * Create args that describe an existing installed package. Typically used
14705     * when cleaning up old installs, or used as a move source.
14706     */
14707    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14708            String resourcePath, String[] instructionSets) {
14709        final boolean isInAsec;
14710        if (installOnExternalAsec(installFlags)) {
14711            /* Apps on SD card are always in ASEC containers. */
14712            isInAsec = true;
14713        } else if (installForwardLocked(installFlags)
14714                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14715            /*
14716             * Forward-locked apps are only in ASEC containers if they're the
14717             * new style
14718             */
14719            isInAsec = true;
14720        } else {
14721            isInAsec = false;
14722        }
14723
14724        if (isInAsec) {
14725            return new AsecInstallArgs(codePath, instructionSets,
14726                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14727        } else {
14728            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14729        }
14730    }
14731
14732    static abstract class InstallArgs {
14733        /** @see InstallParams#origin */
14734        final OriginInfo origin;
14735        /** @see InstallParams#move */
14736        final MoveInfo move;
14737
14738        final IPackageInstallObserver2 observer;
14739        // Always refers to PackageManager flags only
14740        final int installFlags;
14741        final String installerPackageName;
14742        final String volumeUuid;
14743        final UserHandle user;
14744        final String abiOverride;
14745        final String[] installGrantPermissions;
14746        /** If non-null, drop an async trace when the install completes */
14747        final String traceMethod;
14748        final int traceCookie;
14749        final Certificate[][] certificates;
14750        final int installReason;
14751
14752        // The list of instruction sets supported by this app. This is currently
14753        // only used during the rmdex() phase to clean up resources. We can get rid of this
14754        // if we move dex files under the common app path.
14755        /* nullable */ String[] instructionSets;
14756
14757        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14758                int installFlags, String installerPackageName, String volumeUuid,
14759                UserHandle user, String[] instructionSets,
14760                String abiOverride, String[] installGrantPermissions,
14761                String traceMethod, int traceCookie, Certificate[][] certificates,
14762                int installReason) {
14763            this.origin = origin;
14764            this.move = move;
14765            this.installFlags = installFlags;
14766            this.observer = observer;
14767            this.installerPackageName = installerPackageName;
14768            this.volumeUuid = volumeUuid;
14769            this.user = user;
14770            this.instructionSets = instructionSets;
14771            this.abiOverride = abiOverride;
14772            this.installGrantPermissions = installGrantPermissions;
14773            this.traceMethod = traceMethod;
14774            this.traceCookie = traceCookie;
14775            this.certificates = certificates;
14776            this.installReason = installReason;
14777        }
14778
14779        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14780        abstract int doPreInstall(int status);
14781
14782        /**
14783         * Rename package into final resting place. All paths on the given
14784         * scanned package should be updated to reflect the rename.
14785         */
14786        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14787        abstract int doPostInstall(int status, int uid);
14788
14789        /** @see PackageSettingBase#codePathString */
14790        abstract String getCodePath();
14791        /** @see PackageSettingBase#resourcePathString */
14792        abstract String getResourcePath();
14793
14794        // Need installer lock especially for dex file removal.
14795        abstract void cleanUpResourcesLI();
14796        abstract boolean doPostDeleteLI(boolean delete);
14797
14798        /**
14799         * Called before the source arguments are copied. This is used mostly
14800         * for MoveParams when it needs to read the source file to put it in the
14801         * destination.
14802         */
14803        int doPreCopy() {
14804            return PackageManager.INSTALL_SUCCEEDED;
14805        }
14806
14807        /**
14808         * Called after the source arguments are copied. This is used mostly for
14809         * MoveParams when it needs to read the source file to put it in the
14810         * destination.
14811         */
14812        int doPostCopy(int uid) {
14813            return PackageManager.INSTALL_SUCCEEDED;
14814        }
14815
14816        protected boolean isFwdLocked() {
14817            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14818        }
14819
14820        protected boolean isExternalAsec() {
14821            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14822        }
14823
14824        protected boolean isEphemeral() {
14825            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14826        }
14827
14828        UserHandle getUser() {
14829            return user;
14830        }
14831    }
14832
14833    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14834        if (!allCodePaths.isEmpty()) {
14835            if (instructionSets == null) {
14836                throw new IllegalStateException("instructionSet == null");
14837            }
14838            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14839            for (String codePath : allCodePaths) {
14840                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14841                    try {
14842                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14843                    } catch (InstallerException ignored) {
14844                    }
14845                }
14846            }
14847        }
14848    }
14849
14850    /**
14851     * Logic to handle installation of non-ASEC applications, including copying
14852     * and renaming logic.
14853     */
14854    class FileInstallArgs extends InstallArgs {
14855        private File codeFile;
14856        private File resourceFile;
14857
14858        // Example topology:
14859        // /data/app/com.example/base.apk
14860        // /data/app/com.example/split_foo.apk
14861        // /data/app/com.example/lib/arm/libfoo.so
14862        // /data/app/com.example/lib/arm64/libfoo.so
14863        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14864
14865        /** New install */
14866        FileInstallArgs(InstallParams params) {
14867            super(params.origin, params.move, params.observer, params.installFlags,
14868                    params.installerPackageName, params.volumeUuid,
14869                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14870                    params.grantedRuntimePermissions,
14871                    params.traceMethod, params.traceCookie, params.certificates,
14872                    params.installReason);
14873            if (isFwdLocked()) {
14874                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14875            }
14876        }
14877
14878        /** Existing install */
14879        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14880            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14881                    null, null, null, 0, null /*certificates*/,
14882                    PackageManager.INSTALL_REASON_UNKNOWN);
14883            this.codeFile = (codePath != null) ? new File(codePath) : null;
14884            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14885        }
14886
14887        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14888            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14889            try {
14890                return doCopyApk(imcs, temp);
14891            } finally {
14892                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14893            }
14894        }
14895
14896        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14897            if (origin.staged) {
14898                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14899                codeFile = origin.file;
14900                resourceFile = origin.file;
14901                return PackageManager.INSTALL_SUCCEEDED;
14902            }
14903
14904            try {
14905                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14906                final File tempDir =
14907                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14908                codeFile = tempDir;
14909                resourceFile = tempDir;
14910            } catch (IOException e) {
14911                Slog.w(TAG, "Failed to create copy file: " + e);
14912                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14913            }
14914
14915            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14916                @Override
14917                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14918                    if (!FileUtils.isValidExtFilename(name)) {
14919                        throw new IllegalArgumentException("Invalid filename: " + name);
14920                    }
14921                    try {
14922                        final File file = new File(codeFile, name);
14923                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14924                                O_RDWR | O_CREAT, 0644);
14925                        Os.chmod(file.getAbsolutePath(), 0644);
14926                        return new ParcelFileDescriptor(fd);
14927                    } catch (ErrnoException e) {
14928                        throw new RemoteException("Failed to open: " + e.getMessage());
14929                    }
14930                }
14931            };
14932
14933            int ret = PackageManager.INSTALL_SUCCEEDED;
14934            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14935            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14936                Slog.e(TAG, "Failed to copy package");
14937                return ret;
14938            }
14939
14940            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14941            NativeLibraryHelper.Handle handle = null;
14942            try {
14943                handle = NativeLibraryHelper.Handle.create(codeFile);
14944                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14945                        abiOverride);
14946            } catch (IOException e) {
14947                Slog.e(TAG, "Copying native libraries failed", e);
14948                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14949            } finally {
14950                IoUtils.closeQuietly(handle);
14951            }
14952
14953            return ret;
14954        }
14955
14956        int doPreInstall(int status) {
14957            if (status != PackageManager.INSTALL_SUCCEEDED) {
14958                cleanUp();
14959            }
14960            return status;
14961        }
14962
14963        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14964            if (status != PackageManager.INSTALL_SUCCEEDED) {
14965                cleanUp();
14966                return false;
14967            }
14968
14969            final File targetDir = codeFile.getParentFile();
14970            final File beforeCodeFile = codeFile;
14971            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14972
14973            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14974            try {
14975                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14976            } catch (ErrnoException e) {
14977                Slog.w(TAG, "Failed to rename", e);
14978                return false;
14979            }
14980
14981            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14982                Slog.w(TAG, "Failed to restorecon");
14983                return false;
14984            }
14985
14986            // Reflect the rename internally
14987            codeFile = afterCodeFile;
14988            resourceFile = afterCodeFile;
14989
14990            // Reflect the rename in scanned details
14991            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14992            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14993                    afterCodeFile, pkg.baseCodePath));
14994            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14995                    afterCodeFile, pkg.splitCodePaths));
14996
14997            // Reflect the rename in app info
14998            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14999            pkg.setApplicationInfoCodePath(pkg.codePath);
15000            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15001            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15002            pkg.setApplicationInfoResourcePath(pkg.codePath);
15003            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15004            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15005
15006            return true;
15007        }
15008
15009        int doPostInstall(int status, int uid) {
15010            if (status != PackageManager.INSTALL_SUCCEEDED) {
15011                cleanUp();
15012            }
15013            return status;
15014        }
15015
15016        @Override
15017        String getCodePath() {
15018            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15019        }
15020
15021        @Override
15022        String getResourcePath() {
15023            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15024        }
15025
15026        private boolean cleanUp() {
15027            if (codeFile == null || !codeFile.exists()) {
15028                return false;
15029            }
15030
15031            removeCodePathLI(codeFile);
15032
15033            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15034                resourceFile.delete();
15035            }
15036
15037            return true;
15038        }
15039
15040        void cleanUpResourcesLI() {
15041            // Try enumerating all code paths before deleting
15042            List<String> allCodePaths = Collections.EMPTY_LIST;
15043            if (codeFile != null && codeFile.exists()) {
15044                try {
15045                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15046                    allCodePaths = pkg.getAllCodePaths();
15047                } catch (PackageParserException e) {
15048                    // Ignored; we tried our best
15049                }
15050            }
15051
15052            cleanUp();
15053            removeDexFiles(allCodePaths, instructionSets);
15054        }
15055
15056        boolean doPostDeleteLI(boolean delete) {
15057            // XXX err, shouldn't we respect the delete flag?
15058            cleanUpResourcesLI();
15059            return true;
15060        }
15061    }
15062
15063    private boolean isAsecExternal(String cid) {
15064        final String asecPath = PackageHelper.getSdFilesystem(cid);
15065        return !asecPath.startsWith(mAsecInternalPath);
15066    }
15067
15068    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15069            PackageManagerException {
15070        if (copyRet < 0) {
15071            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15072                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15073                throw new PackageManagerException(copyRet, message);
15074            }
15075        }
15076    }
15077
15078    /**
15079     * Extract the StorageManagerService "container ID" from the full code path of an
15080     * .apk.
15081     */
15082    static String cidFromCodePath(String fullCodePath) {
15083        int eidx = fullCodePath.lastIndexOf("/");
15084        String subStr1 = fullCodePath.substring(0, eidx);
15085        int sidx = subStr1.lastIndexOf("/");
15086        return subStr1.substring(sidx+1, eidx);
15087    }
15088
15089    /**
15090     * Logic to handle installation of ASEC applications, including copying and
15091     * renaming logic.
15092     */
15093    class AsecInstallArgs extends InstallArgs {
15094        static final String RES_FILE_NAME = "pkg.apk";
15095        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15096
15097        String cid;
15098        String packagePath;
15099        String resourcePath;
15100
15101        /** New install */
15102        AsecInstallArgs(InstallParams params) {
15103            super(params.origin, params.move, params.observer, params.installFlags,
15104                    params.installerPackageName, params.volumeUuid,
15105                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15106                    params.grantedRuntimePermissions,
15107                    params.traceMethod, params.traceCookie, params.certificates,
15108                    params.installReason);
15109        }
15110
15111        /** Existing install */
15112        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15113                        boolean isExternal, boolean isForwardLocked) {
15114            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15115                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15116                    instructionSets, null, null, null, 0, null /*certificates*/,
15117                    PackageManager.INSTALL_REASON_UNKNOWN);
15118            // Hackily pretend we're still looking at a full code path
15119            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15120                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15121            }
15122
15123            // Extract cid from fullCodePath
15124            int eidx = fullCodePath.lastIndexOf("/");
15125            String subStr1 = fullCodePath.substring(0, eidx);
15126            int sidx = subStr1.lastIndexOf("/");
15127            cid = subStr1.substring(sidx+1, eidx);
15128            setMountPath(subStr1);
15129        }
15130
15131        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15132            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15133                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15134                    instructionSets, null, null, null, 0, null /*certificates*/,
15135                    PackageManager.INSTALL_REASON_UNKNOWN);
15136            this.cid = cid;
15137            setMountPath(PackageHelper.getSdDir(cid));
15138        }
15139
15140        void createCopyFile() {
15141            cid = mInstallerService.allocateExternalStageCidLegacy();
15142        }
15143
15144        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15145            if (origin.staged && origin.cid != null) {
15146                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15147                cid = origin.cid;
15148                setMountPath(PackageHelper.getSdDir(cid));
15149                return PackageManager.INSTALL_SUCCEEDED;
15150            }
15151
15152            if (temp) {
15153                createCopyFile();
15154            } else {
15155                /*
15156                 * Pre-emptively destroy the container since it's destroyed if
15157                 * copying fails due to it existing anyway.
15158                 */
15159                PackageHelper.destroySdDir(cid);
15160            }
15161
15162            final String newMountPath = imcs.copyPackageToContainer(
15163                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15164                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15165
15166            if (newMountPath != null) {
15167                setMountPath(newMountPath);
15168                return PackageManager.INSTALL_SUCCEEDED;
15169            } else {
15170                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15171            }
15172        }
15173
15174        @Override
15175        String getCodePath() {
15176            return packagePath;
15177        }
15178
15179        @Override
15180        String getResourcePath() {
15181            return resourcePath;
15182        }
15183
15184        int doPreInstall(int status) {
15185            if (status != PackageManager.INSTALL_SUCCEEDED) {
15186                // Destroy container
15187                PackageHelper.destroySdDir(cid);
15188            } else {
15189                boolean mounted = PackageHelper.isContainerMounted(cid);
15190                if (!mounted) {
15191                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15192                            Process.SYSTEM_UID);
15193                    if (newMountPath != null) {
15194                        setMountPath(newMountPath);
15195                    } else {
15196                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15197                    }
15198                }
15199            }
15200            return status;
15201        }
15202
15203        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15204            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15205            String newMountPath = null;
15206            if (PackageHelper.isContainerMounted(cid)) {
15207                // Unmount the container
15208                if (!PackageHelper.unMountSdDir(cid)) {
15209                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15210                    return false;
15211                }
15212            }
15213            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15214                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15215                        " which might be stale. Will try to clean up.");
15216                // Clean up the stale container and proceed to recreate.
15217                if (!PackageHelper.destroySdDir(newCacheId)) {
15218                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15219                    return false;
15220                }
15221                // Successfully cleaned up stale container. Try to rename again.
15222                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15223                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15224                            + " inspite of cleaning it up.");
15225                    return false;
15226                }
15227            }
15228            if (!PackageHelper.isContainerMounted(newCacheId)) {
15229                Slog.w(TAG, "Mounting container " + newCacheId);
15230                newMountPath = PackageHelper.mountSdDir(newCacheId,
15231                        getEncryptKey(), Process.SYSTEM_UID);
15232            } else {
15233                newMountPath = PackageHelper.getSdDir(newCacheId);
15234            }
15235            if (newMountPath == null) {
15236                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15237                return false;
15238            }
15239            Log.i(TAG, "Succesfully renamed " + cid +
15240                    " to " + newCacheId +
15241                    " at new path: " + newMountPath);
15242            cid = newCacheId;
15243
15244            final File beforeCodeFile = new File(packagePath);
15245            setMountPath(newMountPath);
15246            final File afterCodeFile = new File(packagePath);
15247
15248            // Reflect the rename in scanned details
15249            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15250            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15251                    afterCodeFile, pkg.baseCodePath));
15252            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15253                    afterCodeFile, pkg.splitCodePaths));
15254
15255            // Reflect the rename in app info
15256            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15257            pkg.setApplicationInfoCodePath(pkg.codePath);
15258            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15259            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15260            pkg.setApplicationInfoResourcePath(pkg.codePath);
15261            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15262            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15263
15264            return true;
15265        }
15266
15267        private void setMountPath(String mountPath) {
15268            final File mountFile = new File(mountPath);
15269
15270            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15271            if (monolithicFile.exists()) {
15272                packagePath = monolithicFile.getAbsolutePath();
15273                if (isFwdLocked()) {
15274                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15275                } else {
15276                    resourcePath = packagePath;
15277                }
15278            } else {
15279                packagePath = mountFile.getAbsolutePath();
15280                resourcePath = packagePath;
15281            }
15282        }
15283
15284        int doPostInstall(int status, int uid) {
15285            if (status != PackageManager.INSTALL_SUCCEEDED) {
15286                cleanUp();
15287            } else {
15288                final int groupOwner;
15289                final String protectedFile;
15290                if (isFwdLocked()) {
15291                    groupOwner = UserHandle.getSharedAppGid(uid);
15292                    protectedFile = RES_FILE_NAME;
15293                } else {
15294                    groupOwner = -1;
15295                    protectedFile = null;
15296                }
15297
15298                if (uid < Process.FIRST_APPLICATION_UID
15299                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15300                    Slog.e(TAG, "Failed to finalize " + cid);
15301                    PackageHelper.destroySdDir(cid);
15302                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15303                }
15304
15305                boolean mounted = PackageHelper.isContainerMounted(cid);
15306                if (!mounted) {
15307                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15308                }
15309            }
15310            return status;
15311        }
15312
15313        private void cleanUp() {
15314            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15315
15316            // Destroy secure container
15317            PackageHelper.destroySdDir(cid);
15318        }
15319
15320        private List<String> getAllCodePaths() {
15321            final File codeFile = new File(getCodePath());
15322            if (codeFile != null && codeFile.exists()) {
15323                try {
15324                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15325                    return pkg.getAllCodePaths();
15326                } catch (PackageParserException e) {
15327                    // Ignored; we tried our best
15328                }
15329            }
15330            return Collections.EMPTY_LIST;
15331        }
15332
15333        void cleanUpResourcesLI() {
15334            // Enumerate all code paths before deleting
15335            cleanUpResourcesLI(getAllCodePaths());
15336        }
15337
15338        private void cleanUpResourcesLI(List<String> allCodePaths) {
15339            cleanUp();
15340            removeDexFiles(allCodePaths, instructionSets);
15341        }
15342
15343        String getPackageName() {
15344            return getAsecPackageName(cid);
15345        }
15346
15347        boolean doPostDeleteLI(boolean delete) {
15348            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15349            final List<String> allCodePaths = getAllCodePaths();
15350            boolean mounted = PackageHelper.isContainerMounted(cid);
15351            if (mounted) {
15352                // Unmount first
15353                if (PackageHelper.unMountSdDir(cid)) {
15354                    mounted = false;
15355                }
15356            }
15357            if (!mounted && delete) {
15358                cleanUpResourcesLI(allCodePaths);
15359            }
15360            return !mounted;
15361        }
15362
15363        @Override
15364        int doPreCopy() {
15365            if (isFwdLocked()) {
15366                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15367                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15368                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15369                }
15370            }
15371
15372            return PackageManager.INSTALL_SUCCEEDED;
15373        }
15374
15375        @Override
15376        int doPostCopy(int uid) {
15377            if (isFwdLocked()) {
15378                if (uid < Process.FIRST_APPLICATION_UID
15379                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15380                                RES_FILE_NAME)) {
15381                    Slog.e(TAG, "Failed to finalize " + cid);
15382                    PackageHelper.destroySdDir(cid);
15383                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15384                }
15385            }
15386
15387            return PackageManager.INSTALL_SUCCEEDED;
15388        }
15389    }
15390
15391    /**
15392     * Logic to handle movement of existing installed applications.
15393     */
15394    class MoveInstallArgs extends InstallArgs {
15395        private File codeFile;
15396        private File resourceFile;
15397
15398        /** New install */
15399        MoveInstallArgs(InstallParams params) {
15400            super(params.origin, params.move, params.observer, params.installFlags,
15401                    params.installerPackageName, params.volumeUuid,
15402                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15403                    params.grantedRuntimePermissions,
15404                    params.traceMethod, params.traceCookie, params.certificates,
15405                    params.installReason);
15406        }
15407
15408        int copyApk(IMediaContainerService imcs, boolean temp) {
15409            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15410                    + move.fromUuid + " to " + move.toUuid);
15411            synchronized (mInstaller) {
15412                try {
15413                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15414                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15415                } catch (InstallerException e) {
15416                    Slog.w(TAG, "Failed to move app", e);
15417                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15418                }
15419            }
15420
15421            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15422            resourceFile = codeFile;
15423            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15424
15425            return PackageManager.INSTALL_SUCCEEDED;
15426        }
15427
15428        int doPreInstall(int status) {
15429            if (status != PackageManager.INSTALL_SUCCEEDED) {
15430                cleanUp(move.toUuid);
15431            }
15432            return status;
15433        }
15434
15435        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15436            if (status != PackageManager.INSTALL_SUCCEEDED) {
15437                cleanUp(move.toUuid);
15438                return false;
15439            }
15440
15441            // Reflect the move in app info
15442            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15443            pkg.setApplicationInfoCodePath(pkg.codePath);
15444            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15445            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15446            pkg.setApplicationInfoResourcePath(pkg.codePath);
15447            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15448            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15449
15450            return true;
15451        }
15452
15453        int doPostInstall(int status, int uid) {
15454            if (status == PackageManager.INSTALL_SUCCEEDED) {
15455                cleanUp(move.fromUuid);
15456            } else {
15457                cleanUp(move.toUuid);
15458            }
15459            return status;
15460        }
15461
15462        @Override
15463        String getCodePath() {
15464            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15465        }
15466
15467        @Override
15468        String getResourcePath() {
15469            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15470        }
15471
15472        private boolean cleanUp(String volumeUuid) {
15473            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15474                    move.dataAppName);
15475            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15476            final int[] userIds = sUserManager.getUserIds();
15477            synchronized (mInstallLock) {
15478                // Clean up both app data and code
15479                // All package moves are frozen until finished
15480                for (int userId : userIds) {
15481                    try {
15482                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15483                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15484                    } catch (InstallerException e) {
15485                        Slog.w(TAG, String.valueOf(e));
15486                    }
15487                }
15488                removeCodePathLI(codeFile);
15489            }
15490            return true;
15491        }
15492
15493        void cleanUpResourcesLI() {
15494            throw new UnsupportedOperationException();
15495        }
15496
15497        boolean doPostDeleteLI(boolean delete) {
15498            throw new UnsupportedOperationException();
15499        }
15500    }
15501
15502    static String getAsecPackageName(String packageCid) {
15503        int idx = packageCid.lastIndexOf("-");
15504        if (idx == -1) {
15505            return packageCid;
15506        }
15507        return packageCid.substring(0, idx);
15508    }
15509
15510    // Utility method used to create code paths based on package name and available index.
15511    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15512        String idxStr = "";
15513        int idx = 1;
15514        // Fall back to default value of idx=1 if prefix is not
15515        // part of oldCodePath
15516        if (oldCodePath != null) {
15517            String subStr = oldCodePath;
15518            // Drop the suffix right away
15519            if (suffix != null && subStr.endsWith(suffix)) {
15520                subStr = subStr.substring(0, subStr.length() - suffix.length());
15521            }
15522            // If oldCodePath already contains prefix find out the
15523            // ending index to either increment or decrement.
15524            int sidx = subStr.lastIndexOf(prefix);
15525            if (sidx != -1) {
15526                subStr = subStr.substring(sidx + prefix.length());
15527                if (subStr != null) {
15528                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15529                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15530                    }
15531                    try {
15532                        idx = Integer.parseInt(subStr);
15533                        if (idx <= 1) {
15534                            idx++;
15535                        } else {
15536                            idx--;
15537                        }
15538                    } catch(NumberFormatException e) {
15539                    }
15540                }
15541            }
15542        }
15543        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15544        return prefix + idxStr;
15545    }
15546
15547    private File getNextCodePath(File targetDir, String packageName) {
15548        File result;
15549        SecureRandom random = new SecureRandom();
15550        byte[] bytes = new byte[16];
15551        do {
15552            random.nextBytes(bytes);
15553            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15554            result = new File(targetDir, packageName + "-" + suffix);
15555        } while (result.exists());
15556        return result;
15557    }
15558
15559    // Utility method that returns the relative package path with respect
15560    // to the installation directory. Like say for /data/data/com.test-1.apk
15561    // string com.test-1 is returned.
15562    static String deriveCodePathName(String codePath) {
15563        if (codePath == null) {
15564            return null;
15565        }
15566        final File codeFile = new File(codePath);
15567        final String name = codeFile.getName();
15568        if (codeFile.isDirectory()) {
15569            return name;
15570        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15571            final int lastDot = name.lastIndexOf('.');
15572            return name.substring(0, lastDot);
15573        } else {
15574            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15575            return null;
15576        }
15577    }
15578
15579    static class PackageInstalledInfo {
15580        String name;
15581        int uid;
15582        // The set of users that originally had this package installed.
15583        int[] origUsers;
15584        // The set of users that now have this package installed.
15585        int[] newUsers;
15586        PackageParser.Package pkg;
15587        int returnCode;
15588        String returnMsg;
15589        PackageRemovedInfo removedInfo;
15590        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15591
15592        public void setError(int code, String msg) {
15593            setReturnCode(code);
15594            setReturnMessage(msg);
15595            Slog.w(TAG, msg);
15596        }
15597
15598        public void setError(String msg, PackageParserException e) {
15599            setReturnCode(e.error);
15600            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15601            Slog.w(TAG, msg, e);
15602        }
15603
15604        public void setError(String msg, PackageManagerException e) {
15605            returnCode = e.error;
15606            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15607            Slog.w(TAG, msg, e);
15608        }
15609
15610        public void setReturnCode(int returnCode) {
15611            this.returnCode = returnCode;
15612            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15613            for (int i = 0; i < childCount; i++) {
15614                addedChildPackages.valueAt(i).returnCode = returnCode;
15615            }
15616        }
15617
15618        private void setReturnMessage(String returnMsg) {
15619            this.returnMsg = returnMsg;
15620            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15621            for (int i = 0; i < childCount; i++) {
15622                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15623            }
15624        }
15625
15626        // In some error cases we want to convey more info back to the observer
15627        String origPackage;
15628        String origPermission;
15629    }
15630
15631    /*
15632     * Install a non-existing package.
15633     */
15634    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15635            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15636            PackageInstalledInfo res, int installReason) {
15637        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15638
15639        // Remember this for later, in case we need to rollback this install
15640        String pkgName = pkg.packageName;
15641
15642        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15643
15644        synchronized(mPackages) {
15645            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15646            if (renamedPackage != null) {
15647                // A package with the same name is already installed, though
15648                // it has been renamed to an older name.  The package we
15649                // are trying to install should be installed as an update to
15650                // the existing one, but that has not been requested, so bail.
15651                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15652                        + " without first uninstalling package running as "
15653                        + renamedPackage);
15654                return;
15655            }
15656            if (mPackages.containsKey(pkgName)) {
15657                // Don't allow installation over an existing package with the same name.
15658                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15659                        + " without first uninstalling.");
15660                return;
15661            }
15662        }
15663
15664        try {
15665            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15666                    System.currentTimeMillis(), user);
15667
15668            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15669
15670            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15671                prepareAppDataAfterInstallLIF(newPackage);
15672
15673            } else {
15674                // Remove package from internal structures, but keep around any
15675                // data that might have already existed
15676                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15677                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15678            }
15679        } catch (PackageManagerException e) {
15680            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15681        }
15682
15683        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15684    }
15685
15686    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15687        // Can't rotate keys during boot or if sharedUser.
15688        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15689                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15690            return false;
15691        }
15692        // app is using upgradeKeySets; make sure all are valid
15693        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15694        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15695        for (int i = 0; i < upgradeKeySets.length; i++) {
15696            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15697                Slog.wtf(TAG, "Package "
15698                         + (oldPs.name != null ? oldPs.name : "<null>")
15699                         + " contains upgrade-key-set reference to unknown key-set: "
15700                         + upgradeKeySets[i]
15701                         + " reverting to signatures check.");
15702                return false;
15703            }
15704        }
15705        return true;
15706    }
15707
15708    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15709        // Upgrade keysets are being used.  Determine if new package has a superset of the
15710        // required keys.
15711        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15712        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15713        for (int i = 0; i < upgradeKeySets.length; i++) {
15714            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15715            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15716                return true;
15717            }
15718        }
15719        return false;
15720    }
15721
15722    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15723        try (DigestInputStream digestStream =
15724                new DigestInputStream(new FileInputStream(file), digest)) {
15725            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15726        }
15727    }
15728
15729    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15730            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15731            int installReason) {
15732        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15733
15734        final PackageParser.Package oldPackage;
15735        final String pkgName = pkg.packageName;
15736        final int[] allUsers;
15737        final int[] installedUsers;
15738
15739        synchronized(mPackages) {
15740            oldPackage = mPackages.get(pkgName);
15741            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15742
15743            // don't allow upgrade to target a release SDK from a pre-release SDK
15744            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15745                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15746            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15747                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15748            if (oldTargetsPreRelease
15749                    && !newTargetsPreRelease
15750                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15751                Slog.w(TAG, "Can't install package targeting released sdk");
15752                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15753                return;
15754            }
15755
15756            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15757
15758            // verify signatures are valid
15759            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15760                if (!checkUpgradeKeySetLP(ps, pkg)) {
15761                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15762                            "New package not signed by keys specified by upgrade-keysets: "
15763                                    + pkgName);
15764                    return;
15765                }
15766            } else {
15767                // default to original signature matching
15768                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15769                        != PackageManager.SIGNATURE_MATCH) {
15770                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15771                            "New package has a different signature: " + pkgName);
15772                    return;
15773                }
15774            }
15775
15776            // don't allow a system upgrade unless the upgrade hash matches
15777            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15778                byte[] digestBytes = null;
15779                try {
15780                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15781                    updateDigest(digest, new File(pkg.baseCodePath));
15782                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15783                        for (String path : pkg.splitCodePaths) {
15784                            updateDigest(digest, new File(path));
15785                        }
15786                    }
15787                    digestBytes = digest.digest();
15788                } catch (NoSuchAlgorithmException | IOException e) {
15789                    res.setError(INSTALL_FAILED_INVALID_APK,
15790                            "Could not compute hash: " + pkgName);
15791                    return;
15792                }
15793                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15794                    res.setError(INSTALL_FAILED_INVALID_APK,
15795                            "New package fails restrict-update check: " + pkgName);
15796                    return;
15797                }
15798                // retain upgrade restriction
15799                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15800            }
15801
15802            // Check for shared user id changes
15803            String invalidPackageName =
15804                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15805            if (invalidPackageName != null) {
15806                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15807                        "Package " + invalidPackageName + " tried to change user "
15808                                + oldPackage.mSharedUserId);
15809                return;
15810            }
15811
15812            // In case of rollback, remember per-user/profile install state
15813            allUsers = sUserManager.getUserIds();
15814            installedUsers = ps.queryInstalledUsers(allUsers, true);
15815
15816            // don't allow an upgrade from full to ephemeral
15817            if (isInstantApp) {
15818                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15819                    for (int currentUser : allUsers) {
15820                        if (!ps.getInstantApp(currentUser)) {
15821                            // can't downgrade from full to instant
15822                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15823                                    + " for user: " + currentUser);
15824                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15825                            return;
15826                        }
15827                    }
15828                } else if (!ps.getInstantApp(user.getIdentifier())) {
15829                    // can't downgrade from full to instant
15830                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15831                            + " for user: " + user.getIdentifier());
15832                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15833                    return;
15834                }
15835            }
15836        }
15837
15838        // Update what is removed
15839        res.removedInfo = new PackageRemovedInfo();
15840        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15841        res.removedInfo.removedPackage = oldPackage.packageName;
15842        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15843        res.removedInfo.isUpdate = true;
15844        res.removedInfo.origUsers = installedUsers;
15845        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15846        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15847        for (int i = 0; i < installedUsers.length; i++) {
15848            final int userId = installedUsers[i];
15849            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15850        }
15851
15852        final int childCount = (oldPackage.childPackages != null)
15853                ? oldPackage.childPackages.size() : 0;
15854        for (int i = 0; i < childCount; i++) {
15855            boolean childPackageUpdated = false;
15856            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15857            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15858            if (res.addedChildPackages != null) {
15859                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15860                if (childRes != null) {
15861                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15862                    childRes.removedInfo.removedPackage = childPkg.packageName;
15863                    childRes.removedInfo.isUpdate = true;
15864                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15865                    childPackageUpdated = true;
15866                }
15867            }
15868            if (!childPackageUpdated) {
15869                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15870                childRemovedRes.removedPackage = childPkg.packageName;
15871                childRemovedRes.isUpdate = false;
15872                childRemovedRes.dataRemoved = true;
15873                synchronized (mPackages) {
15874                    if (childPs != null) {
15875                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15876                    }
15877                }
15878                if (res.removedInfo.removedChildPackages == null) {
15879                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15880                }
15881                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15882            }
15883        }
15884
15885        boolean sysPkg = (isSystemApp(oldPackage));
15886        if (sysPkg) {
15887            // Set the system/privileged flags as needed
15888            final boolean privileged =
15889                    (oldPackage.applicationInfo.privateFlags
15890                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15891            final int systemPolicyFlags = policyFlags
15892                    | PackageParser.PARSE_IS_SYSTEM
15893                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15894
15895            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15896                    user, allUsers, installerPackageName, res, installReason);
15897        } else {
15898            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15899                    user, allUsers, installerPackageName, res, installReason);
15900        }
15901    }
15902
15903    public List<String> getPreviousCodePaths(String packageName) {
15904        final PackageSetting ps = mSettings.mPackages.get(packageName);
15905        final List<String> result = new ArrayList<String>();
15906        if (ps != null && ps.oldCodePaths != null) {
15907            result.addAll(ps.oldCodePaths);
15908        }
15909        return result;
15910    }
15911
15912    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15913            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15914            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15915            int installReason) {
15916        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15917                + deletedPackage);
15918
15919        String pkgName = deletedPackage.packageName;
15920        boolean deletedPkg = true;
15921        boolean addedPkg = false;
15922        boolean updatedSettings = false;
15923        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15924        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15925                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15926
15927        final long origUpdateTime = (pkg.mExtras != null)
15928                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15929
15930        // First delete the existing package while retaining the data directory
15931        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15932                res.removedInfo, true, pkg)) {
15933            // If the existing package wasn't successfully deleted
15934            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15935            deletedPkg = false;
15936        } else {
15937            // Successfully deleted the old package; proceed with replace.
15938
15939            // If deleted package lived in a container, give users a chance to
15940            // relinquish resources before killing.
15941            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15942                if (DEBUG_INSTALL) {
15943                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15944                }
15945                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15946                final ArrayList<String> pkgList = new ArrayList<String>(1);
15947                pkgList.add(deletedPackage.applicationInfo.packageName);
15948                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15949            }
15950
15951            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15952                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15953            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15954
15955            try {
15956                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15957                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15958                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15959                        installReason);
15960
15961                // Update the in-memory copy of the previous code paths.
15962                PackageSetting ps = mSettings.mPackages.get(pkgName);
15963                if (!killApp) {
15964                    if (ps.oldCodePaths == null) {
15965                        ps.oldCodePaths = new ArraySet<>();
15966                    }
15967                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15968                    if (deletedPackage.splitCodePaths != null) {
15969                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15970                    }
15971                } else {
15972                    ps.oldCodePaths = null;
15973                }
15974                if (ps.childPackageNames != null) {
15975                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15976                        final String childPkgName = ps.childPackageNames.get(i);
15977                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15978                        childPs.oldCodePaths = ps.oldCodePaths;
15979                    }
15980                }
15981                // set instant app status, but, only if it's explicitly specified
15982                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15983                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
15984                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
15985                prepareAppDataAfterInstallLIF(newPackage);
15986                addedPkg = true;
15987                mDexManager.notifyPackageUpdated(newPackage.packageName,
15988                        newPackage.baseCodePath, newPackage.splitCodePaths);
15989            } catch (PackageManagerException e) {
15990                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15991            }
15992        }
15993
15994        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15995            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15996
15997            // Revert all internal state mutations and added folders for the failed install
15998            if (addedPkg) {
15999                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16000                        res.removedInfo, true, null);
16001            }
16002
16003            // Restore the old package
16004            if (deletedPkg) {
16005                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16006                File restoreFile = new File(deletedPackage.codePath);
16007                // Parse old package
16008                boolean oldExternal = isExternal(deletedPackage);
16009                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16010                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16011                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16012                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16013                try {
16014                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16015                            null);
16016                } catch (PackageManagerException e) {
16017                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16018                            + e.getMessage());
16019                    return;
16020                }
16021
16022                synchronized (mPackages) {
16023                    // Ensure the installer package name up to date
16024                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16025
16026                    // Update permissions for restored package
16027                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16028
16029                    mSettings.writeLPr();
16030                }
16031
16032                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16033            }
16034        } else {
16035            synchronized (mPackages) {
16036                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16037                if (ps != null) {
16038                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16039                    if (res.removedInfo.removedChildPackages != null) {
16040                        final int childCount = res.removedInfo.removedChildPackages.size();
16041                        // Iterate in reverse as we may modify the collection
16042                        for (int i = childCount - 1; i >= 0; i--) {
16043                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16044                            if (res.addedChildPackages.containsKey(childPackageName)) {
16045                                res.removedInfo.removedChildPackages.removeAt(i);
16046                            } else {
16047                                PackageRemovedInfo childInfo = res.removedInfo
16048                                        .removedChildPackages.valueAt(i);
16049                                childInfo.removedForAllUsers = mPackages.get(
16050                                        childInfo.removedPackage) == null;
16051                            }
16052                        }
16053                    }
16054                }
16055            }
16056        }
16057    }
16058
16059    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16060            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16061            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16062            int installReason) {
16063        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16064                + ", old=" + deletedPackage);
16065
16066        final boolean disabledSystem;
16067
16068        // Remove existing system package
16069        removePackageLI(deletedPackage, true);
16070
16071        synchronized (mPackages) {
16072            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16073        }
16074        if (!disabledSystem) {
16075            // We didn't need to disable the .apk as a current system package,
16076            // which means we are replacing another update that is already
16077            // installed.  We need to make sure to delete the older one's .apk.
16078            res.removedInfo.args = createInstallArgsForExisting(0,
16079                    deletedPackage.applicationInfo.getCodePath(),
16080                    deletedPackage.applicationInfo.getResourcePath(),
16081                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16082        } else {
16083            res.removedInfo.args = null;
16084        }
16085
16086        // Successfully disabled the old package. Now proceed with re-installation
16087        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16088                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16089        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16090
16091        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16092        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16093                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16094
16095        PackageParser.Package newPackage = null;
16096        try {
16097            // Add the package to the internal data structures
16098            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16099
16100            // Set the update and install times
16101            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16102            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16103                    System.currentTimeMillis());
16104
16105            // Update the package dynamic state if succeeded
16106            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16107                // Now that the install succeeded make sure we remove data
16108                // directories for any child package the update removed.
16109                final int deletedChildCount = (deletedPackage.childPackages != null)
16110                        ? deletedPackage.childPackages.size() : 0;
16111                final int newChildCount = (newPackage.childPackages != null)
16112                        ? newPackage.childPackages.size() : 0;
16113                for (int i = 0; i < deletedChildCount; i++) {
16114                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16115                    boolean childPackageDeleted = true;
16116                    for (int j = 0; j < newChildCount; j++) {
16117                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16118                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16119                            childPackageDeleted = false;
16120                            break;
16121                        }
16122                    }
16123                    if (childPackageDeleted) {
16124                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16125                                deletedChildPkg.packageName);
16126                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16127                            PackageRemovedInfo removedChildRes = res.removedInfo
16128                                    .removedChildPackages.get(deletedChildPkg.packageName);
16129                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16130                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16131                        }
16132                    }
16133                }
16134
16135                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16136                        installReason);
16137                prepareAppDataAfterInstallLIF(newPackage);
16138
16139                mDexManager.notifyPackageUpdated(newPackage.packageName,
16140                            newPackage.baseCodePath, newPackage.splitCodePaths);
16141            }
16142        } catch (PackageManagerException e) {
16143            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16144            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16145        }
16146
16147        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16148            // Re installation failed. Restore old information
16149            // Remove new pkg information
16150            if (newPackage != null) {
16151                removeInstalledPackageLI(newPackage, true);
16152            }
16153            // Add back the old system package
16154            try {
16155                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16156            } catch (PackageManagerException e) {
16157                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16158            }
16159
16160            synchronized (mPackages) {
16161                if (disabledSystem) {
16162                    enableSystemPackageLPw(deletedPackage);
16163                }
16164
16165                // Ensure the installer package name up to date
16166                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16167
16168                // Update permissions for restored package
16169                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16170
16171                mSettings.writeLPr();
16172            }
16173
16174            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16175                    + " after failed upgrade");
16176        }
16177    }
16178
16179    /**
16180     * Checks whether the parent or any of the child packages have a change shared
16181     * user. For a package to be a valid update the shred users of the parent and
16182     * the children should match. We may later support changing child shared users.
16183     * @param oldPkg The updated package.
16184     * @param newPkg The update package.
16185     * @return The shared user that change between the versions.
16186     */
16187    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16188            PackageParser.Package newPkg) {
16189        // Check parent shared user
16190        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16191            return newPkg.packageName;
16192        }
16193        // Check child shared users
16194        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16195        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16196        for (int i = 0; i < newChildCount; i++) {
16197            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16198            // If this child was present, did it have the same shared user?
16199            for (int j = 0; j < oldChildCount; j++) {
16200                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16201                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16202                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16203                    return newChildPkg.packageName;
16204                }
16205            }
16206        }
16207        return null;
16208    }
16209
16210    private void removeNativeBinariesLI(PackageSetting ps) {
16211        // Remove the lib path for the parent package
16212        if (ps != null) {
16213            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16214            // Remove the lib path for the child packages
16215            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16216            for (int i = 0; i < childCount; i++) {
16217                PackageSetting childPs = null;
16218                synchronized (mPackages) {
16219                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16220                }
16221                if (childPs != null) {
16222                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16223                            .legacyNativeLibraryPathString);
16224                }
16225            }
16226        }
16227    }
16228
16229    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16230        // Enable the parent package
16231        mSettings.enableSystemPackageLPw(pkg.packageName);
16232        // Enable the child packages
16233        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16234        for (int i = 0; i < childCount; i++) {
16235            PackageParser.Package childPkg = pkg.childPackages.get(i);
16236            mSettings.enableSystemPackageLPw(childPkg.packageName);
16237        }
16238    }
16239
16240    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16241            PackageParser.Package newPkg) {
16242        // Disable the parent package (parent always replaced)
16243        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16244        // Disable the child packages
16245        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16246        for (int i = 0; i < childCount; i++) {
16247            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16248            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16249            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16250        }
16251        return disabled;
16252    }
16253
16254    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16255            String installerPackageName) {
16256        // Enable the parent package
16257        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16258        // Enable the child packages
16259        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16260        for (int i = 0; i < childCount; i++) {
16261            PackageParser.Package childPkg = pkg.childPackages.get(i);
16262            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16263        }
16264    }
16265
16266    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16267        // Collect all used permissions in the UID
16268        ArraySet<String> usedPermissions = new ArraySet<>();
16269        final int packageCount = su.packages.size();
16270        for (int i = 0; i < packageCount; i++) {
16271            PackageSetting ps = su.packages.valueAt(i);
16272            if (ps.pkg == null) {
16273                continue;
16274            }
16275            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16276            for (int j = 0; j < requestedPermCount; j++) {
16277                String permission = ps.pkg.requestedPermissions.get(j);
16278                BasePermission bp = mSettings.mPermissions.get(permission);
16279                if (bp != null) {
16280                    usedPermissions.add(permission);
16281                }
16282            }
16283        }
16284
16285        PermissionsState permissionsState = su.getPermissionsState();
16286        // Prune install permissions
16287        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16288        final int installPermCount = installPermStates.size();
16289        for (int i = installPermCount - 1; i >= 0;  i--) {
16290            PermissionState permissionState = installPermStates.get(i);
16291            if (!usedPermissions.contains(permissionState.getName())) {
16292                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16293                if (bp != null) {
16294                    permissionsState.revokeInstallPermission(bp);
16295                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16296                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16297                }
16298            }
16299        }
16300
16301        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16302
16303        // Prune runtime permissions
16304        for (int userId : allUserIds) {
16305            List<PermissionState> runtimePermStates = permissionsState
16306                    .getRuntimePermissionStates(userId);
16307            final int runtimePermCount = runtimePermStates.size();
16308            for (int i = runtimePermCount - 1; i >= 0; i--) {
16309                PermissionState permissionState = runtimePermStates.get(i);
16310                if (!usedPermissions.contains(permissionState.getName())) {
16311                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16312                    if (bp != null) {
16313                        permissionsState.revokeRuntimePermission(bp, userId);
16314                        permissionsState.updatePermissionFlags(bp, userId,
16315                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16316                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16317                                runtimePermissionChangedUserIds, userId);
16318                    }
16319                }
16320            }
16321        }
16322
16323        return runtimePermissionChangedUserIds;
16324    }
16325
16326    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16327            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16328        // Update the parent package setting
16329        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16330                res, user, installReason);
16331        // Update the child packages setting
16332        final int childCount = (newPackage.childPackages != null)
16333                ? newPackage.childPackages.size() : 0;
16334        for (int i = 0; i < childCount; i++) {
16335            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16336            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16337            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16338                    childRes.origUsers, childRes, user, installReason);
16339        }
16340    }
16341
16342    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16343            String installerPackageName, int[] allUsers, int[] installedForUsers,
16344            PackageInstalledInfo res, UserHandle user, int installReason) {
16345        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16346
16347        String pkgName = newPackage.packageName;
16348        synchronized (mPackages) {
16349            //write settings. the installStatus will be incomplete at this stage.
16350            //note that the new package setting would have already been
16351            //added to mPackages. It hasn't been persisted yet.
16352            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16353            // TODO: Remove this write? It's also written at the end of this method
16354            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16355            mSettings.writeLPr();
16356            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16357        }
16358
16359        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16360        synchronized (mPackages) {
16361            updatePermissionsLPw(newPackage.packageName, newPackage,
16362                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16363                            ? UPDATE_PERMISSIONS_ALL : 0));
16364            // For system-bundled packages, we assume that installing an upgraded version
16365            // of the package implies that the user actually wants to run that new code,
16366            // so we enable the package.
16367            PackageSetting ps = mSettings.mPackages.get(pkgName);
16368            final int userId = user.getIdentifier();
16369            if (ps != null) {
16370                if (isSystemApp(newPackage)) {
16371                    if (DEBUG_INSTALL) {
16372                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16373                    }
16374                    // Enable system package for requested users
16375                    if (res.origUsers != null) {
16376                        for (int origUserId : res.origUsers) {
16377                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16378                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16379                                        origUserId, installerPackageName);
16380                            }
16381                        }
16382                    }
16383                    // Also convey the prior install/uninstall state
16384                    if (allUsers != null && installedForUsers != null) {
16385                        for (int currentUserId : allUsers) {
16386                            final boolean installed = ArrayUtils.contains(
16387                                    installedForUsers, currentUserId);
16388                            if (DEBUG_INSTALL) {
16389                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16390                            }
16391                            ps.setInstalled(installed, currentUserId);
16392                        }
16393                        // these install state changes will be persisted in the
16394                        // upcoming call to mSettings.writeLPr().
16395                    }
16396                }
16397                // It's implied that when a user requests installation, they want the app to be
16398                // installed and enabled.
16399                if (userId != UserHandle.USER_ALL) {
16400                    ps.setInstalled(true, userId);
16401                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16402                }
16403
16404                // When replacing an existing package, preserve the original install reason for all
16405                // users that had the package installed before.
16406                final Set<Integer> previousUserIds = new ArraySet<>();
16407                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16408                    final int installReasonCount = res.removedInfo.installReasons.size();
16409                    for (int i = 0; i < installReasonCount; i++) {
16410                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16411                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16412                        ps.setInstallReason(previousInstallReason, previousUserId);
16413                        previousUserIds.add(previousUserId);
16414                    }
16415                }
16416
16417                // Set install reason for users that are having the package newly installed.
16418                if (userId == UserHandle.USER_ALL) {
16419                    for (int currentUserId : sUserManager.getUserIds()) {
16420                        if (!previousUserIds.contains(currentUserId)) {
16421                            ps.setInstallReason(installReason, currentUserId);
16422                        }
16423                    }
16424                } else if (!previousUserIds.contains(userId)) {
16425                    ps.setInstallReason(installReason, userId);
16426                }
16427                mSettings.writeKernelMappingLPr(ps);
16428            }
16429            res.name = pkgName;
16430            res.uid = newPackage.applicationInfo.uid;
16431            res.pkg = newPackage;
16432            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16433            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16434            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16435            //to update install status
16436            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16437            mSettings.writeLPr();
16438            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16439        }
16440
16441        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16442    }
16443
16444    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16445        try {
16446            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16447            installPackageLI(args, res);
16448        } finally {
16449            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16450        }
16451    }
16452
16453    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16454        final int installFlags = args.installFlags;
16455        final String installerPackageName = args.installerPackageName;
16456        final String volumeUuid = args.volumeUuid;
16457        final File tmpPackageFile = new File(args.getCodePath());
16458        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16459        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16460                || (args.volumeUuid != null));
16461        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16462        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16463        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16464        boolean replace = false;
16465        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16466        if (args.move != null) {
16467            // moving a complete application; perform an initial scan on the new install location
16468            scanFlags |= SCAN_INITIAL;
16469        }
16470        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16471            scanFlags |= SCAN_DONT_KILL_APP;
16472        }
16473        if (instantApp) {
16474            scanFlags |= SCAN_AS_INSTANT_APP;
16475        }
16476        if (fullApp) {
16477            scanFlags |= SCAN_AS_FULL_APP;
16478        }
16479
16480        // Result object to be returned
16481        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16482
16483        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16484
16485        // Sanity check
16486        if (instantApp && (forwardLocked || onExternal)) {
16487            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16488                    + " external=" + onExternal);
16489            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16490            return;
16491        }
16492
16493        // Retrieve PackageSettings and parse package
16494        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16495                | PackageParser.PARSE_ENFORCE_CODE
16496                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16497                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16498                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16499                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16500        PackageParser pp = new PackageParser();
16501        pp.setSeparateProcesses(mSeparateProcesses);
16502        pp.setDisplayMetrics(mMetrics);
16503        pp.setCallback(mPackageParserCallback);
16504
16505        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16506        final PackageParser.Package pkg;
16507        try {
16508            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16509        } catch (PackageParserException e) {
16510            res.setError("Failed parse during installPackageLI", e);
16511            return;
16512        } finally {
16513            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16514        }
16515
16516        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16517        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16518            Slog.w(TAG, "Instant app package " + pkg.packageName
16519                    + " does not target O, this will be a fatal error.");
16520            // STOPSHIP: Make this a fatal error
16521            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16522        }
16523        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16524            Slog.w(TAG, "Instant app package " + pkg.packageName
16525                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16526            // STOPSHIP: Make this a fatal error
16527            pkg.applicationInfo.targetSandboxVersion = 2;
16528        }
16529
16530        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16531            // Static shared libraries have synthetic package names
16532            renameStaticSharedLibraryPackage(pkg);
16533
16534            // No static shared libs on external storage
16535            if (onExternal) {
16536                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16537                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16538                        "Packages declaring static-shared libs cannot be updated");
16539                return;
16540            }
16541        }
16542
16543        // If we are installing a clustered package add results for the children
16544        if (pkg.childPackages != null) {
16545            synchronized (mPackages) {
16546                final int childCount = pkg.childPackages.size();
16547                for (int i = 0; i < childCount; i++) {
16548                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16549                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16550                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16551                    childRes.pkg = childPkg;
16552                    childRes.name = childPkg.packageName;
16553                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16554                    if (childPs != null) {
16555                        childRes.origUsers = childPs.queryInstalledUsers(
16556                                sUserManager.getUserIds(), true);
16557                    }
16558                    if ((mPackages.containsKey(childPkg.packageName))) {
16559                        childRes.removedInfo = new PackageRemovedInfo();
16560                        childRes.removedInfo.removedPackage = childPkg.packageName;
16561                    }
16562                    if (res.addedChildPackages == null) {
16563                        res.addedChildPackages = new ArrayMap<>();
16564                    }
16565                    res.addedChildPackages.put(childPkg.packageName, childRes);
16566                }
16567            }
16568        }
16569
16570        // If package doesn't declare API override, mark that we have an install
16571        // time CPU ABI override.
16572        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16573            pkg.cpuAbiOverride = args.abiOverride;
16574        }
16575
16576        String pkgName = res.name = pkg.packageName;
16577        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16578            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16579                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16580                return;
16581            }
16582        }
16583
16584        try {
16585            // either use what we've been given or parse directly from the APK
16586            if (args.certificates != null) {
16587                try {
16588                    PackageParser.populateCertificates(pkg, args.certificates);
16589                } catch (PackageParserException e) {
16590                    // there was something wrong with the certificates we were given;
16591                    // try to pull them from the APK
16592                    PackageParser.collectCertificates(pkg, parseFlags);
16593                }
16594            } else {
16595                PackageParser.collectCertificates(pkg, parseFlags);
16596            }
16597        } catch (PackageParserException e) {
16598            res.setError("Failed collect during installPackageLI", e);
16599            return;
16600        }
16601
16602        // Get rid of all references to package scan path via parser.
16603        pp = null;
16604        String oldCodePath = null;
16605        boolean systemApp = false;
16606        synchronized (mPackages) {
16607            // Check if installing already existing package
16608            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16609                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16610                if (pkg.mOriginalPackages != null
16611                        && pkg.mOriginalPackages.contains(oldName)
16612                        && mPackages.containsKey(oldName)) {
16613                    // This package is derived from an original package,
16614                    // and this device has been updating from that original
16615                    // name.  We must continue using the original name, so
16616                    // rename the new package here.
16617                    pkg.setPackageName(oldName);
16618                    pkgName = pkg.packageName;
16619                    replace = true;
16620                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16621                            + oldName + " pkgName=" + pkgName);
16622                } else if (mPackages.containsKey(pkgName)) {
16623                    // This package, under its official name, already exists
16624                    // on the device; we should replace it.
16625                    replace = true;
16626                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16627                }
16628
16629                // Child packages are installed through the parent package
16630                if (pkg.parentPackage != null) {
16631                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16632                            "Package " + pkg.packageName + " is child of package "
16633                                    + pkg.parentPackage.parentPackage + ". Child packages "
16634                                    + "can be updated only through the parent package.");
16635                    return;
16636                }
16637
16638                if (replace) {
16639                    // Prevent apps opting out from runtime permissions
16640                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16641                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16642                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16643                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16644                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16645                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16646                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16647                                        + " doesn't support runtime permissions but the old"
16648                                        + " target SDK " + oldTargetSdk + " does.");
16649                        return;
16650                    }
16651
16652                    // Prevent installing of child packages
16653                    if (oldPackage.parentPackage != null) {
16654                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16655                                "Package " + pkg.packageName + " is child of package "
16656                                        + oldPackage.parentPackage + ". Child packages "
16657                                        + "can be updated only through the parent package.");
16658                        return;
16659                    }
16660                }
16661            }
16662
16663            PackageSetting ps = mSettings.mPackages.get(pkgName);
16664            if (ps != null) {
16665                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16666
16667                // Static shared libs have same package with different versions where
16668                // we internally use a synthetic package name to allow multiple versions
16669                // of the same package, therefore we need to compare signatures against
16670                // the package setting for the latest library version.
16671                PackageSetting signatureCheckPs = ps;
16672                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16673                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16674                    if (libraryEntry != null) {
16675                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16676                    }
16677                }
16678
16679                // Quick sanity check that we're signed correctly if updating;
16680                // we'll check this again later when scanning, but we want to
16681                // bail early here before tripping over redefined permissions.
16682                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16683                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16684                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16685                                + pkg.packageName + " upgrade keys do not match the "
16686                                + "previously installed version");
16687                        return;
16688                    }
16689                } else {
16690                    try {
16691                        verifySignaturesLP(signatureCheckPs, pkg);
16692                    } catch (PackageManagerException e) {
16693                        res.setError(e.error, e.getMessage());
16694                        return;
16695                    }
16696                }
16697
16698                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16699                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16700                    systemApp = (ps.pkg.applicationInfo.flags &
16701                            ApplicationInfo.FLAG_SYSTEM) != 0;
16702                }
16703                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16704            }
16705
16706            int N = pkg.permissions.size();
16707            for (int i = N-1; i >= 0; i--) {
16708                PackageParser.Permission perm = pkg.permissions.get(i);
16709                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16710
16711                // Don't allow anyone but the platform to define ephemeral permissions.
16712                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16713                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16714                    Slog.w(TAG, "Package " + pkg.packageName
16715                            + " attempting to delcare ephemeral permission "
16716                            + perm.info.name + "; Removing ephemeral.");
16717                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16718                }
16719                // Check whether the newly-scanned package wants to define an already-defined perm
16720                if (bp != null) {
16721                    // If the defining package is signed with our cert, it's okay.  This
16722                    // also includes the "updating the same package" case, of course.
16723                    // "updating same package" could also involve key-rotation.
16724                    final boolean sigsOk;
16725                    if (bp.sourcePackage.equals(pkg.packageName)
16726                            && (bp.packageSetting instanceof PackageSetting)
16727                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16728                                    scanFlags))) {
16729                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16730                    } else {
16731                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16732                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16733                    }
16734                    if (!sigsOk) {
16735                        // If the owning package is the system itself, we log but allow
16736                        // install to proceed; we fail the install on all other permission
16737                        // redefinitions.
16738                        if (!bp.sourcePackage.equals("android")) {
16739                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16740                                    + pkg.packageName + " attempting to redeclare permission "
16741                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16742                            res.origPermission = perm.info.name;
16743                            res.origPackage = bp.sourcePackage;
16744                            return;
16745                        } else {
16746                            Slog.w(TAG, "Package " + pkg.packageName
16747                                    + " attempting to redeclare system permission "
16748                                    + perm.info.name + "; ignoring new declaration");
16749                            pkg.permissions.remove(i);
16750                        }
16751                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16752                        // Prevent apps to change protection level to dangerous from any other
16753                        // type as this would allow a privilege escalation where an app adds a
16754                        // normal/signature permission in other app's group and later redefines
16755                        // it as dangerous leading to the group auto-grant.
16756                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16757                                == PermissionInfo.PROTECTION_DANGEROUS) {
16758                            if (bp != null && !bp.isRuntime()) {
16759                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16760                                        + "non-runtime permission " + perm.info.name
16761                                        + " to runtime; keeping old protection level");
16762                                perm.info.protectionLevel = bp.protectionLevel;
16763                            }
16764                        }
16765                    }
16766                }
16767            }
16768        }
16769
16770        if (systemApp) {
16771            if (onExternal) {
16772                // Abort update; system app can't be replaced with app on sdcard
16773                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16774                        "Cannot install updates to system apps on sdcard");
16775                return;
16776            } else if (instantApp) {
16777                // Abort update; system app can't be replaced with an instant app
16778                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16779                        "Cannot update a system app with an instant app");
16780                return;
16781            }
16782        }
16783
16784        if (args.move != null) {
16785            // We did an in-place move, so dex is ready to roll
16786            scanFlags |= SCAN_NO_DEX;
16787            scanFlags |= SCAN_MOVE;
16788
16789            synchronized (mPackages) {
16790                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16791                if (ps == null) {
16792                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16793                            "Missing settings for moved package " + pkgName);
16794                }
16795
16796                // We moved the entire application as-is, so bring over the
16797                // previously derived ABI information.
16798                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16799                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16800            }
16801
16802        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16803            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16804            scanFlags |= SCAN_NO_DEX;
16805
16806            try {
16807                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16808                    args.abiOverride : pkg.cpuAbiOverride);
16809                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16810                        true /*extractLibs*/, mAppLib32InstallDir);
16811            } catch (PackageManagerException pme) {
16812                Slog.e(TAG, "Error deriving application ABI", pme);
16813                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16814                return;
16815            }
16816
16817            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16818            // Do not run PackageDexOptimizer through the local performDexOpt
16819            // method because `pkg` may not be in `mPackages` yet.
16820            //
16821            // Also, don't fail application installs if the dexopt step fails.
16822            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16823                    null /* instructionSets */, false /* checkProfiles */,
16824                    getCompilerFilterForReason(REASON_INSTALL),
16825                    getOrCreateCompilerPackageStats(pkg),
16826                    mDexManager.isUsedByOtherApps(pkg.packageName));
16827            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16828
16829            // Notify BackgroundDexOptService that the package has been changed.
16830            // If this is an update of a package which used to fail to compile,
16831            // BDOS will remove it from its blacklist.
16832            // TODO: Layering violation
16833            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16834        }
16835
16836        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16837            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16838            return;
16839        }
16840
16841        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16842
16843        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16844                "installPackageLI")) {
16845            if (replace) {
16846                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16847                    // Static libs have a synthetic package name containing the version
16848                    // and cannot be updated as an update would get a new package name,
16849                    // unless this is the exact same version code which is useful for
16850                    // development.
16851                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16852                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16853                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16854                                + "static-shared libs cannot be updated");
16855                        return;
16856                    }
16857                }
16858                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16859                        installerPackageName, res, args.installReason);
16860            } else {
16861                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16862                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16863            }
16864        }
16865        synchronized (mPackages) {
16866            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16867            if (ps != null) {
16868                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16869                ps.setUpdateAvailable(false /*updateAvailable*/);
16870            }
16871
16872            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16873            for (int i = 0; i < childCount; i++) {
16874                PackageParser.Package childPkg = pkg.childPackages.get(i);
16875                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16876                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16877                if (childPs != null) {
16878                    childRes.newUsers = childPs.queryInstalledUsers(
16879                            sUserManager.getUserIds(), true);
16880                }
16881            }
16882
16883            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16884                updateSequenceNumberLP(pkgName, res.newUsers);
16885            }
16886        }
16887    }
16888
16889    private void startIntentFilterVerifications(int userId, boolean replacing,
16890            PackageParser.Package pkg) {
16891        if (mIntentFilterVerifierComponent == null) {
16892            Slog.w(TAG, "No IntentFilter verification will not be done as "
16893                    + "there is no IntentFilterVerifier available!");
16894            return;
16895        }
16896
16897        final int verifierUid = getPackageUid(
16898                mIntentFilterVerifierComponent.getPackageName(),
16899                MATCH_DEBUG_TRIAGED_MISSING,
16900                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16901
16902        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16903        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16904        mHandler.sendMessage(msg);
16905
16906        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16907        for (int i = 0; i < childCount; i++) {
16908            PackageParser.Package childPkg = pkg.childPackages.get(i);
16909            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16910            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16911            mHandler.sendMessage(msg);
16912        }
16913    }
16914
16915    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16916            PackageParser.Package pkg) {
16917        int size = pkg.activities.size();
16918        if (size == 0) {
16919            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16920                    "No activity, so no need to verify any IntentFilter!");
16921            return;
16922        }
16923
16924        final boolean hasDomainURLs = hasDomainURLs(pkg);
16925        if (!hasDomainURLs) {
16926            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16927                    "No domain URLs, so no need to verify any IntentFilter!");
16928            return;
16929        }
16930
16931        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16932                + " if any IntentFilter from the " + size
16933                + " Activities needs verification ...");
16934
16935        int count = 0;
16936        final String packageName = pkg.packageName;
16937
16938        synchronized (mPackages) {
16939            // If this is a new install and we see that we've already run verification for this
16940            // package, we have nothing to do: it means the state was restored from backup.
16941            if (!replacing) {
16942                IntentFilterVerificationInfo ivi =
16943                        mSettings.getIntentFilterVerificationLPr(packageName);
16944                if (ivi != null) {
16945                    if (DEBUG_DOMAIN_VERIFICATION) {
16946                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16947                                + ivi.getStatusString());
16948                    }
16949                    return;
16950                }
16951            }
16952
16953            // If any filters need to be verified, then all need to be.
16954            boolean needToVerify = false;
16955            for (PackageParser.Activity a : pkg.activities) {
16956                for (ActivityIntentInfo filter : a.intents) {
16957                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16958                        if (DEBUG_DOMAIN_VERIFICATION) {
16959                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16960                        }
16961                        needToVerify = true;
16962                        break;
16963                    }
16964                }
16965            }
16966
16967            if (needToVerify) {
16968                final int verificationId = mIntentFilterVerificationToken++;
16969                for (PackageParser.Activity a : pkg.activities) {
16970                    for (ActivityIntentInfo filter : a.intents) {
16971                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16972                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16973                                    "Verification needed for IntentFilter:" + filter.toString());
16974                            mIntentFilterVerifier.addOneIntentFilterVerification(
16975                                    verifierUid, userId, verificationId, filter, packageName);
16976                            count++;
16977                        }
16978                    }
16979                }
16980            }
16981        }
16982
16983        if (count > 0) {
16984            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16985                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16986                    +  " for userId:" + userId);
16987            mIntentFilterVerifier.startVerifications(userId);
16988        } else {
16989            if (DEBUG_DOMAIN_VERIFICATION) {
16990                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16991            }
16992        }
16993    }
16994
16995    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16996        final ComponentName cn  = filter.activity.getComponentName();
16997        final String packageName = cn.getPackageName();
16998
16999        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17000                packageName);
17001        if (ivi == null) {
17002            return true;
17003        }
17004        int status = ivi.getStatus();
17005        switch (status) {
17006            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17007            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17008                return true;
17009
17010            default:
17011                // Nothing to do
17012                return false;
17013        }
17014    }
17015
17016    private static boolean isMultiArch(ApplicationInfo info) {
17017        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17018    }
17019
17020    private static boolean isExternal(PackageParser.Package pkg) {
17021        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17022    }
17023
17024    private static boolean isExternal(PackageSetting ps) {
17025        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17026    }
17027
17028    private static boolean isSystemApp(PackageParser.Package pkg) {
17029        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17030    }
17031
17032    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17033        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17034    }
17035
17036    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17037        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17038    }
17039
17040    private static boolean isSystemApp(PackageSetting ps) {
17041        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17042    }
17043
17044    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17045        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17046    }
17047
17048    private int packageFlagsToInstallFlags(PackageSetting ps) {
17049        int installFlags = 0;
17050        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17051            // This existing package was an external ASEC install when we have
17052            // the external flag without a UUID
17053            installFlags |= PackageManager.INSTALL_EXTERNAL;
17054        }
17055        if (ps.isForwardLocked()) {
17056            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17057        }
17058        return installFlags;
17059    }
17060
17061    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17062        if (isExternal(pkg)) {
17063            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17064                return StorageManager.UUID_PRIMARY_PHYSICAL;
17065            } else {
17066                return pkg.volumeUuid;
17067            }
17068        } else {
17069            return StorageManager.UUID_PRIVATE_INTERNAL;
17070        }
17071    }
17072
17073    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17074        if (isExternal(pkg)) {
17075            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17076                return mSettings.getExternalVersion();
17077            } else {
17078                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17079            }
17080        } else {
17081            return mSettings.getInternalVersion();
17082        }
17083    }
17084
17085    private void deleteTempPackageFiles() {
17086        final FilenameFilter filter = new FilenameFilter() {
17087            public boolean accept(File dir, String name) {
17088                return name.startsWith("vmdl") && name.endsWith(".tmp");
17089            }
17090        };
17091        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17092            file.delete();
17093        }
17094    }
17095
17096    @Override
17097    public void deletePackageAsUser(String packageName, int versionCode,
17098            IPackageDeleteObserver observer, int userId, int flags) {
17099        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17100                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17101    }
17102
17103    @Override
17104    public void deletePackageVersioned(VersionedPackage versionedPackage,
17105            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17106        mContext.enforceCallingOrSelfPermission(
17107                android.Manifest.permission.DELETE_PACKAGES, null);
17108        Preconditions.checkNotNull(versionedPackage);
17109        Preconditions.checkNotNull(observer);
17110        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17111                PackageManager.VERSION_CODE_HIGHEST,
17112                Integer.MAX_VALUE, "versionCode must be >= -1");
17113
17114        final String packageName = versionedPackage.getPackageName();
17115        // TODO: We will change version code to long, so in the new API it is long
17116        final int versionCode = (int) versionedPackage.getVersionCode();
17117        final String internalPackageName;
17118        synchronized (mPackages) {
17119            // Normalize package name to handle renamed packages and static libs
17120            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17121                    // TODO: We will change version code to long, so in the new API it is long
17122                    (int) versionedPackage.getVersionCode());
17123        }
17124
17125        final int uid = Binder.getCallingUid();
17126        if (!isOrphaned(internalPackageName)
17127                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17128            try {
17129                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17130                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17131                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17132                observer.onUserActionRequired(intent);
17133            } catch (RemoteException re) {
17134            }
17135            return;
17136        }
17137        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17138        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17139        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17140            mContext.enforceCallingOrSelfPermission(
17141                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17142                    "deletePackage for user " + userId);
17143        }
17144
17145        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17146            try {
17147                observer.onPackageDeleted(packageName,
17148                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17149            } catch (RemoteException re) {
17150            }
17151            return;
17152        }
17153
17154        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17155            try {
17156                observer.onPackageDeleted(packageName,
17157                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17158            } catch (RemoteException re) {
17159            }
17160            return;
17161        }
17162
17163        if (DEBUG_REMOVE) {
17164            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17165                    + " deleteAllUsers: " + deleteAllUsers + " version="
17166                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17167                    ? "VERSION_CODE_HIGHEST" : versionCode));
17168        }
17169        // Queue up an async operation since the package deletion may take a little while.
17170        mHandler.post(new Runnable() {
17171            public void run() {
17172                mHandler.removeCallbacks(this);
17173                int returnCode;
17174                if (!deleteAllUsers) {
17175                    returnCode = deletePackageX(internalPackageName, versionCode,
17176                            userId, deleteFlags);
17177                } else {
17178                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17179                            internalPackageName, users);
17180                    // If nobody is blocking uninstall, proceed with delete for all users
17181                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17182                        returnCode = deletePackageX(internalPackageName, versionCode,
17183                                userId, deleteFlags);
17184                    } else {
17185                        // Otherwise uninstall individually for users with blockUninstalls=false
17186                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17187                        for (int userId : users) {
17188                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17189                                returnCode = deletePackageX(internalPackageName, versionCode,
17190                                        userId, userFlags);
17191                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17192                                    Slog.w(TAG, "Package delete failed for user " + userId
17193                                            + ", returnCode " + returnCode);
17194                                }
17195                            }
17196                        }
17197                        // The app has only been marked uninstalled for certain users.
17198                        // We still need to report that delete was blocked
17199                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17200                    }
17201                }
17202                try {
17203                    observer.onPackageDeleted(packageName, returnCode, null);
17204                } catch (RemoteException e) {
17205                    Log.i(TAG, "Observer no longer exists.");
17206                } //end catch
17207            } //end run
17208        });
17209    }
17210
17211    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17212        if (pkg.staticSharedLibName != null) {
17213            return pkg.manifestPackageName;
17214        }
17215        return pkg.packageName;
17216    }
17217
17218    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17219        // Handle renamed packages
17220        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17221        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17222
17223        // Is this a static library?
17224        SparseArray<SharedLibraryEntry> versionedLib =
17225                mStaticLibsByDeclaringPackage.get(packageName);
17226        if (versionedLib == null || versionedLib.size() <= 0) {
17227            return packageName;
17228        }
17229
17230        // Figure out which lib versions the caller can see
17231        SparseIntArray versionsCallerCanSee = null;
17232        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17233        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17234                && callingAppId != Process.ROOT_UID) {
17235            versionsCallerCanSee = new SparseIntArray();
17236            String libName = versionedLib.valueAt(0).info.getName();
17237            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17238            if (uidPackages != null) {
17239                for (String uidPackage : uidPackages) {
17240                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17241                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17242                    if (libIdx >= 0) {
17243                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17244                        versionsCallerCanSee.append(libVersion, libVersion);
17245                    }
17246                }
17247            }
17248        }
17249
17250        // Caller can see nothing - done
17251        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17252            return packageName;
17253        }
17254
17255        // Find the version the caller can see and the app version code
17256        SharedLibraryEntry highestVersion = null;
17257        final int versionCount = versionedLib.size();
17258        for (int i = 0; i < versionCount; i++) {
17259            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17260            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17261                    libEntry.info.getVersion()) < 0) {
17262                continue;
17263            }
17264            // TODO: We will change version code to long, so in the new API it is long
17265            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17266            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17267                if (libVersionCode == versionCode) {
17268                    return libEntry.apk;
17269                }
17270            } else if (highestVersion == null) {
17271                highestVersion = libEntry;
17272            } else if (libVersionCode  > highestVersion.info
17273                    .getDeclaringPackage().getVersionCode()) {
17274                highestVersion = libEntry;
17275            }
17276        }
17277
17278        if (highestVersion != null) {
17279            return highestVersion.apk;
17280        }
17281
17282        return packageName;
17283    }
17284
17285    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17286        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17287              || callingUid == Process.SYSTEM_UID) {
17288            return true;
17289        }
17290        final int callingUserId = UserHandle.getUserId(callingUid);
17291        // If the caller installed the pkgName, then allow it to silently uninstall.
17292        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17293            return true;
17294        }
17295
17296        // Allow package verifier to silently uninstall.
17297        if (mRequiredVerifierPackage != null &&
17298                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17299            return true;
17300        }
17301
17302        // Allow package uninstaller to silently uninstall.
17303        if (mRequiredUninstallerPackage != null &&
17304                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17305            return true;
17306        }
17307
17308        // Allow storage manager to silently uninstall.
17309        if (mStorageManagerPackage != null &&
17310                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17311            return true;
17312        }
17313        return false;
17314    }
17315
17316    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17317        int[] result = EMPTY_INT_ARRAY;
17318        for (int userId : userIds) {
17319            if (getBlockUninstallForUser(packageName, userId)) {
17320                result = ArrayUtils.appendInt(result, userId);
17321            }
17322        }
17323        return result;
17324    }
17325
17326    @Override
17327    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17328        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17329    }
17330
17331    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17332        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17333                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17334        try {
17335            if (dpm != null) {
17336                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17337                        /* callingUserOnly =*/ false);
17338                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17339                        : deviceOwnerComponentName.getPackageName();
17340                // Does the package contains the device owner?
17341                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17342                // this check is probably not needed, since DO should be registered as a device
17343                // admin on some user too. (Original bug for this: b/17657954)
17344                if (packageName.equals(deviceOwnerPackageName)) {
17345                    return true;
17346                }
17347                // Does it contain a device admin for any user?
17348                int[] users;
17349                if (userId == UserHandle.USER_ALL) {
17350                    users = sUserManager.getUserIds();
17351                } else {
17352                    users = new int[]{userId};
17353                }
17354                for (int i = 0; i < users.length; ++i) {
17355                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17356                        return true;
17357                    }
17358                }
17359            }
17360        } catch (RemoteException e) {
17361        }
17362        return false;
17363    }
17364
17365    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17366        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17367    }
17368
17369    /**
17370     *  This method is an internal method that could be get invoked either
17371     *  to delete an installed package or to clean up a failed installation.
17372     *  After deleting an installed package, a broadcast is sent to notify any
17373     *  listeners that the package has been removed. For cleaning up a failed
17374     *  installation, the broadcast is not necessary since the package's
17375     *  installation wouldn't have sent the initial broadcast either
17376     *  The key steps in deleting a package are
17377     *  deleting the package information in internal structures like mPackages,
17378     *  deleting the packages base directories through installd
17379     *  updating mSettings to reflect current status
17380     *  persisting settings for later use
17381     *  sending a broadcast if necessary
17382     */
17383    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17384        final PackageRemovedInfo info = new PackageRemovedInfo();
17385        final boolean res;
17386
17387        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17388                ? UserHandle.USER_ALL : userId;
17389
17390        if (isPackageDeviceAdmin(packageName, removeUser)) {
17391            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17392            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17393        }
17394
17395        PackageSetting uninstalledPs = null;
17396        PackageParser.Package pkg = null;
17397
17398        // for the uninstall-updates case and restricted profiles, remember the per-
17399        // user handle installed state
17400        int[] allUsers;
17401        synchronized (mPackages) {
17402            uninstalledPs = mSettings.mPackages.get(packageName);
17403            if (uninstalledPs == null) {
17404                Slog.w(TAG, "Not removing non-existent package " + packageName);
17405                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17406            }
17407
17408            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17409                    && uninstalledPs.versionCode != versionCode) {
17410                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17411                        + uninstalledPs.versionCode + " != " + versionCode);
17412                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17413            }
17414
17415            // Static shared libs can be declared by any package, so let us not
17416            // allow removing a package if it provides a lib others depend on.
17417            pkg = mPackages.get(packageName);
17418            if (pkg != null && pkg.staticSharedLibName != null) {
17419                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17420                        pkg.staticSharedLibVersion);
17421                if (libEntry != null) {
17422                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17423                            libEntry.info, 0, userId);
17424                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17425                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17426                                + " hosting lib " + libEntry.info.getName() + " version "
17427                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17428                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17429                    }
17430                }
17431            }
17432
17433            allUsers = sUserManager.getUserIds();
17434            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17435        }
17436
17437        final int freezeUser;
17438        if (isUpdatedSystemApp(uninstalledPs)
17439                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17440            // We're downgrading a system app, which will apply to all users, so
17441            // freeze them all during the downgrade
17442            freezeUser = UserHandle.USER_ALL;
17443        } else {
17444            freezeUser = removeUser;
17445        }
17446
17447        synchronized (mInstallLock) {
17448            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17449            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17450                    deleteFlags, "deletePackageX")) {
17451                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17452                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17453            }
17454            synchronized (mPackages) {
17455                if (res) {
17456                    if (pkg != null) {
17457                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17458                    }
17459                    updateSequenceNumberLP(packageName, info.removedUsers);
17460                }
17461            }
17462        }
17463
17464        if (res) {
17465            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17466            info.sendPackageRemovedBroadcasts(killApp);
17467            info.sendSystemPackageUpdatedBroadcasts();
17468            info.sendSystemPackageAppearedBroadcasts();
17469        }
17470        // Force a gc here.
17471        Runtime.getRuntime().gc();
17472        // Delete the resources here after sending the broadcast to let
17473        // other processes clean up before deleting resources.
17474        if (info.args != null) {
17475            synchronized (mInstallLock) {
17476                info.args.doPostDeleteLI(true);
17477            }
17478        }
17479
17480        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17481    }
17482
17483    class PackageRemovedInfo {
17484        String removedPackage;
17485        int uid = -1;
17486        int removedAppId = -1;
17487        int[] origUsers;
17488        int[] removedUsers = null;
17489        SparseArray<Integer> installReasons;
17490        boolean isRemovedPackageSystemUpdate = false;
17491        boolean isUpdate;
17492        boolean dataRemoved;
17493        boolean removedForAllUsers;
17494        boolean isStaticSharedLib;
17495        // Clean up resources deleted packages.
17496        InstallArgs args = null;
17497        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17498        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17499
17500        void sendPackageRemovedBroadcasts(boolean killApp) {
17501            sendPackageRemovedBroadcastInternal(killApp);
17502            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17503            for (int i = 0; i < childCount; i++) {
17504                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17505                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17506            }
17507        }
17508
17509        void sendSystemPackageUpdatedBroadcasts() {
17510            if (isRemovedPackageSystemUpdate) {
17511                sendSystemPackageUpdatedBroadcastsInternal();
17512                final int childCount = (removedChildPackages != null)
17513                        ? removedChildPackages.size() : 0;
17514                for (int i = 0; i < childCount; i++) {
17515                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17516                    if (childInfo.isRemovedPackageSystemUpdate) {
17517                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17518                    }
17519                }
17520            }
17521        }
17522
17523        void sendSystemPackageAppearedBroadcasts() {
17524            final int packageCount = (appearedChildPackages != null)
17525                    ? appearedChildPackages.size() : 0;
17526            for (int i = 0; i < packageCount; i++) {
17527                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17528                sendPackageAddedForNewUsers(installedInfo.name, true,
17529                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17530            }
17531        }
17532
17533        private void sendSystemPackageUpdatedBroadcastsInternal() {
17534            Bundle extras = new Bundle(2);
17535            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17536            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17537            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17538                    extras, 0, null, null, null);
17539            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17540                    extras, 0, null, null, null);
17541            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17542                    null, 0, removedPackage, null, null);
17543        }
17544
17545        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17546            // Don't send static shared library removal broadcasts as these
17547            // libs are visible only the the apps that depend on them an one
17548            // cannot remove the library if it has a dependency.
17549            if (isStaticSharedLib) {
17550                return;
17551            }
17552            Bundle extras = new Bundle(2);
17553            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17554            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17555            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17556            if (isUpdate || isRemovedPackageSystemUpdate) {
17557                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17558            }
17559            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17560            if (removedPackage != null) {
17561                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17562                        extras, 0, null, null, removedUsers);
17563                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17564                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17565                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17566                            null, null, removedUsers);
17567                }
17568            }
17569            if (removedAppId >= 0) {
17570                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17571                        removedUsers);
17572            }
17573        }
17574    }
17575
17576    /*
17577     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17578     * flag is not set, the data directory is removed as well.
17579     * make sure this flag is set for partially installed apps. If not its meaningless to
17580     * delete a partially installed application.
17581     */
17582    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17583            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17584        String packageName = ps.name;
17585        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17586        // Retrieve object to delete permissions for shared user later on
17587        final PackageParser.Package deletedPkg;
17588        final PackageSetting deletedPs;
17589        // reader
17590        synchronized (mPackages) {
17591            deletedPkg = mPackages.get(packageName);
17592            deletedPs = mSettings.mPackages.get(packageName);
17593            if (outInfo != null) {
17594                outInfo.removedPackage = packageName;
17595                outInfo.isStaticSharedLib = deletedPkg != null
17596                        && deletedPkg.staticSharedLibName != null;
17597                outInfo.removedUsers = deletedPs != null
17598                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17599                        : null;
17600            }
17601        }
17602
17603        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17604
17605        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17606            final PackageParser.Package resolvedPkg;
17607            if (deletedPkg != null) {
17608                resolvedPkg = deletedPkg;
17609            } else {
17610                // We don't have a parsed package when it lives on an ejected
17611                // adopted storage device, so fake something together
17612                resolvedPkg = new PackageParser.Package(ps.name);
17613                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17614            }
17615            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17616                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17617            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17618            if (outInfo != null) {
17619                outInfo.dataRemoved = true;
17620            }
17621            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17622        }
17623
17624        int removedAppId = -1;
17625
17626        // writer
17627        synchronized (mPackages) {
17628            boolean installedStateChanged = false;
17629            if (deletedPs != null) {
17630                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17631                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17632                    clearDefaultBrowserIfNeeded(packageName);
17633                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17634                    removedAppId = mSettings.removePackageLPw(packageName);
17635                    if (outInfo != null) {
17636                        outInfo.removedAppId = removedAppId;
17637                    }
17638                    updatePermissionsLPw(deletedPs.name, null, 0);
17639                    if (deletedPs.sharedUser != null) {
17640                        // Remove permissions associated with package. Since runtime
17641                        // permissions are per user we have to kill the removed package
17642                        // or packages running under the shared user of the removed
17643                        // package if revoking the permissions requested only by the removed
17644                        // package is successful and this causes a change in gids.
17645                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17646                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17647                                    userId);
17648                            if (userIdToKill == UserHandle.USER_ALL
17649                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17650                                // If gids changed for this user, kill all affected packages.
17651                                mHandler.post(new Runnable() {
17652                                    @Override
17653                                    public void run() {
17654                                        // This has to happen with no lock held.
17655                                        killApplication(deletedPs.name, deletedPs.appId,
17656                                                KILL_APP_REASON_GIDS_CHANGED);
17657                                    }
17658                                });
17659                                break;
17660                            }
17661                        }
17662                    }
17663                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17664                }
17665                // make sure to preserve per-user disabled state if this removal was just
17666                // a downgrade of a system app to the factory package
17667                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17668                    if (DEBUG_REMOVE) {
17669                        Slog.d(TAG, "Propagating install state across downgrade");
17670                    }
17671                    for (int userId : allUserHandles) {
17672                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17673                        if (DEBUG_REMOVE) {
17674                            Slog.d(TAG, "    user " + userId + " => " + installed);
17675                        }
17676                        if (installed != ps.getInstalled(userId)) {
17677                            installedStateChanged = true;
17678                        }
17679                        ps.setInstalled(installed, userId);
17680                    }
17681                }
17682            }
17683            // can downgrade to reader
17684            if (writeSettings) {
17685                // Save settings now
17686                mSettings.writeLPr();
17687            }
17688            if (installedStateChanged) {
17689                mSettings.writeKernelMappingLPr(ps);
17690            }
17691        }
17692        if (removedAppId != -1) {
17693            // A user ID was deleted here. Go through all users and remove it
17694            // from KeyStore.
17695            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17696        }
17697    }
17698
17699    static boolean locationIsPrivileged(File path) {
17700        try {
17701            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17702                    .getCanonicalPath();
17703            return path.getCanonicalPath().startsWith(privilegedAppDir);
17704        } catch (IOException e) {
17705            Slog.e(TAG, "Unable to access code path " + path);
17706        }
17707        return false;
17708    }
17709
17710    /*
17711     * Tries to delete system package.
17712     */
17713    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17714            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17715            boolean writeSettings) {
17716        if (deletedPs.parentPackageName != null) {
17717            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17718            return false;
17719        }
17720
17721        final boolean applyUserRestrictions
17722                = (allUserHandles != null) && (outInfo.origUsers != null);
17723        final PackageSetting disabledPs;
17724        // Confirm if the system package has been updated
17725        // An updated system app can be deleted. This will also have to restore
17726        // the system pkg from system partition
17727        // reader
17728        synchronized (mPackages) {
17729            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17730        }
17731
17732        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17733                + " disabledPs=" + disabledPs);
17734
17735        if (disabledPs == null) {
17736            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17737            return false;
17738        } else if (DEBUG_REMOVE) {
17739            Slog.d(TAG, "Deleting system pkg from data partition");
17740        }
17741
17742        if (DEBUG_REMOVE) {
17743            if (applyUserRestrictions) {
17744                Slog.d(TAG, "Remembering install states:");
17745                for (int userId : allUserHandles) {
17746                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17747                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17748                }
17749            }
17750        }
17751
17752        // Delete the updated package
17753        outInfo.isRemovedPackageSystemUpdate = true;
17754        if (outInfo.removedChildPackages != null) {
17755            final int childCount = (deletedPs.childPackageNames != null)
17756                    ? deletedPs.childPackageNames.size() : 0;
17757            for (int i = 0; i < childCount; i++) {
17758                String childPackageName = deletedPs.childPackageNames.get(i);
17759                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17760                        .contains(childPackageName)) {
17761                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17762                            childPackageName);
17763                    if (childInfo != null) {
17764                        childInfo.isRemovedPackageSystemUpdate = true;
17765                    }
17766                }
17767            }
17768        }
17769
17770        if (disabledPs.versionCode < deletedPs.versionCode) {
17771            // Delete data for downgrades
17772            flags &= ~PackageManager.DELETE_KEEP_DATA;
17773        } else {
17774            // Preserve data by setting flag
17775            flags |= PackageManager.DELETE_KEEP_DATA;
17776        }
17777
17778        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17779                outInfo, writeSettings, disabledPs.pkg);
17780        if (!ret) {
17781            return false;
17782        }
17783
17784        // writer
17785        synchronized (mPackages) {
17786            // Reinstate the old system package
17787            enableSystemPackageLPw(disabledPs.pkg);
17788            // Remove any native libraries from the upgraded package.
17789            removeNativeBinariesLI(deletedPs);
17790        }
17791
17792        // Install the system package
17793        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17794        int parseFlags = mDefParseFlags
17795                | PackageParser.PARSE_MUST_BE_APK
17796                | PackageParser.PARSE_IS_SYSTEM
17797                | PackageParser.PARSE_IS_SYSTEM_DIR;
17798        if (locationIsPrivileged(disabledPs.codePath)) {
17799            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17800        }
17801
17802        final PackageParser.Package newPkg;
17803        try {
17804            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17805                0 /* currentTime */, null);
17806        } catch (PackageManagerException e) {
17807            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17808                    + e.getMessage());
17809            return false;
17810        }
17811
17812        try {
17813            // update shared libraries for the newly re-installed system package
17814            updateSharedLibrariesLPr(newPkg, null);
17815        } catch (PackageManagerException e) {
17816            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17817        }
17818
17819        prepareAppDataAfterInstallLIF(newPkg);
17820
17821        // writer
17822        synchronized (mPackages) {
17823            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17824
17825            // Propagate the permissions state as we do not want to drop on the floor
17826            // runtime permissions. The update permissions method below will take
17827            // care of removing obsolete permissions and grant install permissions.
17828            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17829            updatePermissionsLPw(newPkg.packageName, newPkg,
17830                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17831
17832            if (applyUserRestrictions) {
17833                boolean installedStateChanged = false;
17834                if (DEBUG_REMOVE) {
17835                    Slog.d(TAG, "Propagating install state across reinstall");
17836                }
17837                for (int userId : allUserHandles) {
17838                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17839                    if (DEBUG_REMOVE) {
17840                        Slog.d(TAG, "    user " + userId + " => " + installed);
17841                    }
17842                    if (installed != ps.getInstalled(userId)) {
17843                        installedStateChanged = true;
17844                    }
17845                    ps.setInstalled(installed, userId);
17846
17847                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17848                }
17849                // Regardless of writeSettings we need to ensure that this restriction
17850                // state propagation is persisted
17851                mSettings.writeAllUsersPackageRestrictionsLPr();
17852                if (installedStateChanged) {
17853                    mSettings.writeKernelMappingLPr(ps);
17854                }
17855            }
17856            // can downgrade to reader here
17857            if (writeSettings) {
17858                mSettings.writeLPr();
17859            }
17860        }
17861        return true;
17862    }
17863
17864    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17865            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17866            PackageRemovedInfo outInfo, boolean writeSettings,
17867            PackageParser.Package replacingPackage) {
17868        synchronized (mPackages) {
17869            if (outInfo != null) {
17870                outInfo.uid = ps.appId;
17871            }
17872
17873            if (outInfo != null && outInfo.removedChildPackages != null) {
17874                final int childCount = (ps.childPackageNames != null)
17875                        ? ps.childPackageNames.size() : 0;
17876                for (int i = 0; i < childCount; i++) {
17877                    String childPackageName = ps.childPackageNames.get(i);
17878                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17879                    if (childPs == null) {
17880                        return false;
17881                    }
17882                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17883                            childPackageName);
17884                    if (childInfo != null) {
17885                        childInfo.uid = childPs.appId;
17886                    }
17887                }
17888            }
17889        }
17890
17891        // Delete package data from internal structures and also remove data if flag is set
17892        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17893
17894        // Delete the child packages data
17895        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17896        for (int i = 0; i < childCount; i++) {
17897            PackageSetting childPs;
17898            synchronized (mPackages) {
17899                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17900            }
17901            if (childPs != null) {
17902                PackageRemovedInfo childOutInfo = (outInfo != null
17903                        && outInfo.removedChildPackages != null)
17904                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17905                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17906                        && (replacingPackage != null
17907                        && !replacingPackage.hasChildPackage(childPs.name))
17908                        ? flags & ~DELETE_KEEP_DATA : flags;
17909                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17910                        deleteFlags, writeSettings);
17911            }
17912        }
17913
17914        // Delete application code and resources only for parent packages
17915        if (ps.parentPackageName == null) {
17916            if (deleteCodeAndResources && (outInfo != null)) {
17917                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17918                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17919                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17920            }
17921        }
17922
17923        return true;
17924    }
17925
17926    @Override
17927    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17928            int userId) {
17929        mContext.enforceCallingOrSelfPermission(
17930                android.Manifest.permission.DELETE_PACKAGES, null);
17931        synchronized (mPackages) {
17932            PackageSetting ps = mSettings.mPackages.get(packageName);
17933            if (ps == null) {
17934                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17935                return false;
17936            }
17937            // Cannot block uninstall of static shared libs as they are
17938            // considered a part of the using app (emulating static linking).
17939            // Also static libs are installed always on internal storage.
17940            PackageParser.Package pkg = mPackages.get(packageName);
17941            if (pkg != null && pkg.staticSharedLibName != null) {
17942                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17943                        + " providing static shared library: " + pkg.staticSharedLibName);
17944                return false;
17945            }
17946            if (!ps.getInstalled(userId)) {
17947                // Can't block uninstall for an app that is not installed or enabled.
17948                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17949                return false;
17950            }
17951            ps.setBlockUninstall(blockUninstall, userId);
17952            mSettings.writePackageRestrictionsLPr(userId);
17953        }
17954        return true;
17955    }
17956
17957    @Override
17958    public boolean getBlockUninstallForUser(String packageName, int userId) {
17959        synchronized (mPackages) {
17960            PackageSetting ps = mSettings.mPackages.get(packageName);
17961            if (ps == null) {
17962                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17963                return false;
17964            }
17965            return ps.getBlockUninstall(userId);
17966        }
17967    }
17968
17969    @Override
17970    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17971        int callingUid = Binder.getCallingUid();
17972        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17973            throw new SecurityException(
17974                    "setRequiredForSystemUser can only be run by the system or root");
17975        }
17976        synchronized (mPackages) {
17977            PackageSetting ps = mSettings.mPackages.get(packageName);
17978            if (ps == null) {
17979                Log.w(TAG, "Package doesn't exist: " + packageName);
17980                return false;
17981            }
17982            if (systemUserApp) {
17983                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17984            } else {
17985                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17986            }
17987            mSettings.writeLPr();
17988        }
17989        return true;
17990    }
17991
17992    /*
17993     * This method handles package deletion in general
17994     */
17995    private boolean deletePackageLIF(String packageName, UserHandle user,
17996            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17997            PackageRemovedInfo outInfo, boolean writeSettings,
17998            PackageParser.Package replacingPackage) {
17999        if (packageName == null) {
18000            Slog.w(TAG, "Attempt to delete null packageName.");
18001            return false;
18002        }
18003
18004        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18005
18006        PackageSetting ps;
18007        synchronized (mPackages) {
18008            ps = mSettings.mPackages.get(packageName);
18009            if (ps == null) {
18010                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18011                return false;
18012            }
18013
18014            if (ps.parentPackageName != null && (!isSystemApp(ps)
18015                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18016                if (DEBUG_REMOVE) {
18017                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18018                            + ((user == null) ? UserHandle.USER_ALL : user));
18019                }
18020                final int removedUserId = (user != null) ? user.getIdentifier()
18021                        : UserHandle.USER_ALL;
18022                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18023                    return false;
18024                }
18025                markPackageUninstalledForUserLPw(ps, user);
18026                scheduleWritePackageRestrictionsLocked(user);
18027                return true;
18028            }
18029        }
18030
18031        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18032                && user.getIdentifier() != UserHandle.USER_ALL)) {
18033            // The caller is asking that the package only be deleted for a single
18034            // user.  To do this, we just mark its uninstalled state and delete
18035            // its data. If this is a system app, we only allow this to happen if
18036            // they have set the special DELETE_SYSTEM_APP which requests different
18037            // semantics than normal for uninstalling system apps.
18038            markPackageUninstalledForUserLPw(ps, user);
18039
18040            if (!isSystemApp(ps)) {
18041                // Do not uninstall the APK if an app should be cached
18042                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18043                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18044                    // Other user still have this package installed, so all
18045                    // we need to do is clear this user's data and save that
18046                    // it is uninstalled.
18047                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18048                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18049                        return false;
18050                    }
18051                    scheduleWritePackageRestrictionsLocked(user);
18052                    return true;
18053                } else {
18054                    // We need to set it back to 'installed' so the uninstall
18055                    // broadcasts will be sent correctly.
18056                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18057                    ps.setInstalled(true, user.getIdentifier());
18058                    mSettings.writeKernelMappingLPr(ps);
18059                }
18060            } else {
18061                // This is a system app, so we assume that the
18062                // other users still have this package installed, so all
18063                // we need to do is clear this user's data and save that
18064                // it is uninstalled.
18065                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18066                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18067                    return false;
18068                }
18069                scheduleWritePackageRestrictionsLocked(user);
18070                return true;
18071            }
18072        }
18073
18074        // If we are deleting a composite package for all users, keep track
18075        // of result for each child.
18076        if (ps.childPackageNames != null && outInfo != null) {
18077            synchronized (mPackages) {
18078                final int childCount = ps.childPackageNames.size();
18079                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18080                for (int i = 0; i < childCount; i++) {
18081                    String childPackageName = ps.childPackageNames.get(i);
18082                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18083                    childInfo.removedPackage = childPackageName;
18084                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18085                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18086                    if (childPs != null) {
18087                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18088                    }
18089                }
18090            }
18091        }
18092
18093        boolean ret = false;
18094        if (isSystemApp(ps)) {
18095            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18096            // When an updated system application is deleted we delete the existing resources
18097            // as well and fall back to existing code in system partition
18098            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18099        } else {
18100            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18101            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18102                    outInfo, writeSettings, replacingPackage);
18103        }
18104
18105        // Take a note whether we deleted the package for all users
18106        if (outInfo != null) {
18107            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18108            if (outInfo.removedChildPackages != null) {
18109                synchronized (mPackages) {
18110                    final int childCount = outInfo.removedChildPackages.size();
18111                    for (int i = 0; i < childCount; i++) {
18112                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18113                        if (childInfo != null) {
18114                            childInfo.removedForAllUsers = mPackages.get(
18115                                    childInfo.removedPackage) == null;
18116                        }
18117                    }
18118                }
18119            }
18120            // If we uninstalled an update to a system app there may be some
18121            // child packages that appeared as they are declared in the system
18122            // app but were not declared in the update.
18123            if (isSystemApp(ps)) {
18124                synchronized (mPackages) {
18125                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18126                    final int childCount = (updatedPs.childPackageNames != null)
18127                            ? updatedPs.childPackageNames.size() : 0;
18128                    for (int i = 0; i < childCount; i++) {
18129                        String childPackageName = updatedPs.childPackageNames.get(i);
18130                        if (outInfo.removedChildPackages == null
18131                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18132                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18133                            if (childPs == null) {
18134                                continue;
18135                            }
18136                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18137                            installRes.name = childPackageName;
18138                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18139                            installRes.pkg = mPackages.get(childPackageName);
18140                            installRes.uid = childPs.pkg.applicationInfo.uid;
18141                            if (outInfo.appearedChildPackages == null) {
18142                                outInfo.appearedChildPackages = new ArrayMap<>();
18143                            }
18144                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18145                        }
18146                    }
18147                }
18148            }
18149        }
18150
18151        return ret;
18152    }
18153
18154    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18155        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18156                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18157        for (int nextUserId : userIds) {
18158            if (DEBUG_REMOVE) {
18159                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18160            }
18161            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18162                    false /*installed*/,
18163                    true /*stopped*/,
18164                    true /*notLaunched*/,
18165                    false /*hidden*/,
18166                    false /*suspended*/,
18167                    false /*instantApp*/,
18168                    null /*lastDisableAppCaller*/,
18169                    null /*enabledComponents*/,
18170                    null /*disabledComponents*/,
18171                    false /*blockUninstall*/,
18172                    ps.readUserState(nextUserId).domainVerificationStatus,
18173                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18174        }
18175        mSettings.writeKernelMappingLPr(ps);
18176    }
18177
18178    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18179            PackageRemovedInfo outInfo) {
18180        final PackageParser.Package pkg;
18181        synchronized (mPackages) {
18182            pkg = mPackages.get(ps.name);
18183        }
18184
18185        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18186                : new int[] {userId};
18187        for (int nextUserId : userIds) {
18188            if (DEBUG_REMOVE) {
18189                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18190                        + nextUserId);
18191            }
18192
18193            destroyAppDataLIF(pkg, userId,
18194                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18195            destroyAppProfilesLIF(pkg, userId);
18196            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18197            schedulePackageCleaning(ps.name, nextUserId, false);
18198            synchronized (mPackages) {
18199                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18200                    scheduleWritePackageRestrictionsLocked(nextUserId);
18201                }
18202                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18203            }
18204        }
18205
18206        if (outInfo != null) {
18207            outInfo.removedPackage = ps.name;
18208            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18209            outInfo.removedAppId = ps.appId;
18210            outInfo.removedUsers = userIds;
18211        }
18212
18213        return true;
18214    }
18215
18216    private final class ClearStorageConnection implements ServiceConnection {
18217        IMediaContainerService mContainerService;
18218
18219        @Override
18220        public void onServiceConnected(ComponentName name, IBinder service) {
18221            synchronized (this) {
18222                mContainerService = IMediaContainerService.Stub
18223                        .asInterface(Binder.allowBlocking(service));
18224                notifyAll();
18225            }
18226        }
18227
18228        @Override
18229        public void onServiceDisconnected(ComponentName name) {
18230        }
18231    }
18232
18233    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18234        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18235
18236        final boolean mounted;
18237        if (Environment.isExternalStorageEmulated()) {
18238            mounted = true;
18239        } else {
18240            final String status = Environment.getExternalStorageState();
18241
18242            mounted = status.equals(Environment.MEDIA_MOUNTED)
18243                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18244        }
18245
18246        if (!mounted) {
18247            return;
18248        }
18249
18250        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18251        int[] users;
18252        if (userId == UserHandle.USER_ALL) {
18253            users = sUserManager.getUserIds();
18254        } else {
18255            users = new int[] { userId };
18256        }
18257        final ClearStorageConnection conn = new ClearStorageConnection();
18258        if (mContext.bindServiceAsUser(
18259                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18260            try {
18261                for (int curUser : users) {
18262                    long timeout = SystemClock.uptimeMillis() + 5000;
18263                    synchronized (conn) {
18264                        long now;
18265                        while (conn.mContainerService == null &&
18266                                (now = SystemClock.uptimeMillis()) < timeout) {
18267                            try {
18268                                conn.wait(timeout - now);
18269                            } catch (InterruptedException e) {
18270                            }
18271                        }
18272                    }
18273                    if (conn.mContainerService == null) {
18274                        return;
18275                    }
18276
18277                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18278                    clearDirectory(conn.mContainerService,
18279                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18280                    if (allData) {
18281                        clearDirectory(conn.mContainerService,
18282                                userEnv.buildExternalStorageAppDataDirs(packageName));
18283                        clearDirectory(conn.mContainerService,
18284                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18285                    }
18286                }
18287            } finally {
18288                mContext.unbindService(conn);
18289            }
18290        }
18291    }
18292
18293    @Override
18294    public void clearApplicationProfileData(String packageName) {
18295        enforceSystemOrRoot("Only the system can clear all profile data");
18296
18297        final PackageParser.Package pkg;
18298        synchronized (mPackages) {
18299            pkg = mPackages.get(packageName);
18300        }
18301
18302        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18303            synchronized (mInstallLock) {
18304                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18305            }
18306        }
18307    }
18308
18309    @Override
18310    public void clearApplicationUserData(final String packageName,
18311            final IPackageDataObserver observer, final int userId) {
18312        mContext.enforceCallingOrSelfPermission(
18313                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18314
18315        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18316                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18317
18318        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18319            throw new SecurityException("Cannot clear data for a protected package: "
18320                    + packageName);
18321        }
18322        // Queue up an async operation since the package deletion may take a little while.
18323        mHandler.post(new Runnable() {
18324            public void run() {
18325                mHandler.removeCallbacks(this);
18326                final boolean succeeded;
18327                try (PackageFreezer freezer = freezePackage(packageName,
18328                        "clearApplicationUserData")) {
18329                    synchronized (mInstallLock) {
18330                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18331                    }
18332                    clearExternalStorageDataSync(packageName, userId, true);
18333                    synchronized (mPackages) {
18334                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18335                                packageName, userId);
18336                    }
18337                }
18338                if (succeeded) {
18339                    // invoke DeviceStorageMonitor's update method to clear any notifications
18340                    DeviceStorageMonitorInternal dsm = LocalServices
18341                            .getService(DeviceStorageMonitorInternal.class);
18342                    if (dsm != null) {
18343                        dsm.checkMemory();
18344                    }
18345                }
18346                if(observer != null) {
18347                    try {
18348                        observer.onRemoveCompleted(packageName, succeeded);
18349                    } catch (RemoteException e) {
18350                        Log.i(TAG, "Observer no longer exists.");
18351                    }
18352                } //end if observer
18353            } //end run
18354        });
18355    }
18356
18357    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18358        if (packageName == null) {
18359            Slog.w(TAG, "Attempt to delete null packageName.");
18360            return false;
18361        }
18362
18363        // Try finding details about the requested package
18364        PackageParser.Package pkg;
18365        synchronized (mPackages) {
18366            pkg = mPackages.get(packageName);
18367            if (pkg == null) {
18368                final PackageSetting ps = mSettings.mPackages.get(packageName);
18369                if (ps != null) {
18370                    pkg = ps.pkg;
18371                }
18372            }
18373
18374            if (pkg == null) {
18375                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18376                return false;
18377            }
18378
18379            PackageSetting ps = (PackageSetting) pkg.mExtras;
18380            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18381        }
18382
18383        clearAppDataLIF(pkg, userId,
18384                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18385
18386        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18387        removeKeystoreDataIfNeeded(userId, appId);
18388
18389        UserManagerInternal umInternal = getUserManagerInternal();
18390        final int flags;
18391        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18392            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18393        } else if (umInternal.isUserRunning(userId)) {
18394            flags = StorageManager.FLAG_STORAGE_DE;
18395        } else {
18396            flags = 0;
18397        }
18398        prepareAppDataContentsLIF(pkg, userId, flags);
18399
18400        return true;
18401    }
18402
18403    /**
18404     * Reverts user permission state changes (permissions and flags) in
18405     * all packages for a given user.
18406     *
18407     * @param userId The device user for which to do a reset.
18408     */
18409    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18410        final int packageCount = mPackages.size();
18411        for (int i = 0; i < packageCount; i++) {
18412            PackageParser.Package pkg = mPackages.valueAt(i);
18413            PackageSetting ps = (PackageSetting) pkg.mExtras;
18414            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18415        }
18416    }
18417
18418    private void resetNetworkPolicies(int userId) {
18419        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18420    }
18421
18422    /**
18423     * Reverts user permission state changes (permissions and flags).
18424     *
18425     * @param ps The package for which to reset.
18426     * @param userId The device user for which to do a reset.
18427     */
18428    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18429            final PackageSetting ps, final int userId) {
18430        if (ps.pkg == null) {
18431            return;
18432        }
18433
18434        // These are flags that can change base on user actions.
18435        final int userSettableMask = FLAG_PERMISSION_USER_SET
18436                | FLAG_PERMISSION_USER_FIXED
18437                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18438                | FLAG_PERMISSION_REVIEW_REQUIRED;
18439
18440        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18441                | FLAG_PERMISSION_POLICY_FIXED;
18442
18443        boolean writeInstallPermissions = false;
18444        boolean writeRuntimePermissions = false;
18445
18446        final int permissionCount = ps.pkg.requestedPermissions.size();
18447        for (int i = 0; i < permissionCount; i++) {
18448            String permission = ps.pkg.requestedPermissions.get(i);
18449
18450            BasePermission bp = mSettings.mPermissions.get(permission);
18451            if (bp == null) {
18452                continue;
18453            }
18454
18455            // If shared user we just reset the state to which only this app contributed.
18456            if (ps.sharedUser != null) {
18457                boolean used = false;
18458                final int packageCount = ps.sharedUser.packages.size();
18459                for (int j = 0; j < packageCount; j++) {
18460                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18461                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18462                            && pkg.pkg.requestedPermissions.contains(permission)) {
18463                        used = true;
18464                        break;
18465                    }
18466                }
18467                if (used) {
18468                    continue;
18469                }
18470            }
18471
18472            PermissionsState permissionsState = ps.getPermissionsState();
18473
18474            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18475
18476            // Always clear the user settable flags.
18477            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18478                    bp.name) != null;
18479            // If permission review is enabled and this is a legacy app, mark the
18480            // permission as requiring a review as this is the initial state.
18481            int flags = 0;
18482            if (mPermissionReviewRequired
18483                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18484                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18485            }
18486            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18487                if (hasInstallState) {
18488                    writeInstallPermissions = true;
18489                } else {
18490                    writeRuntimePermissions = true;
18491                }
18492            }
18493
18494            // Below is only runtime permission handling.
18495            if (!bp.isRuntime()) {
18496                continue;
18497            }
18498
18499            // Never clobber system or policy.
18500            if ((oldFlags & policyOrSystemFlags) != 0) {
18501                continue;
18502            }
18503
18504            // If this permission was granted by default, make sure it is.
18505            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18506                if (permissionsState.grantRuntimePermission(bp, userId)
18507                        != PERMISSION_OPERATION_FAILURE) {
18508                    writeRuntimePermissions = true;
18509                }
18510            // If permission review is enabled the permissions for a legacy apps
18511            // are represented as constantly granted runtime ones, so don't revoke.
18512            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18513                // Otherwise, reset the permission.
18514                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18515                switch (revokeResult) {
18516                    case PERMISSION_OPERATION_SUCCESS:
18517                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18518                        writeRuntimePermissions = true;
18519                        final int appId = ps.appId;
18520                        mHandler.post(new Runnable() {
18521                            @Override
18522                            public void run() {
18523                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18524                            }
18525                        });
18526                    } break;
18527                }
18528            }
18529        }
18530
18531        // Synchronously write as we are taking permissions away.
18532        if (writeRuntimePermissions) {
18533            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18534        }
18535
18536        // Synchronously write as we are taking permissions away.
18537        if (writeInstallPermissions) {
18538            mSettings.writeLPr();
18539        }
18540    }
18541
18542    /**
18543     * Remove entries from the keystore daemon. Will only remove it if the
18544     * {@code appId} is valid.
18545     */
18546    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18547        if (appId < 0) {
18548            return;
18549        }
18550
18551        final KeyStore keyStore = KeyStore.getInstance();
18552        if (keyStore != null) {
18553            if (userId == UserHandle.USER_ALL) {
18554                for (final int individual : sUserManager.getUserIds()) {
18555                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18556                }
18557            } else {
18558                keyStore.clearUid(UserHandle.getUid(userId, appId));
18559            }
18560        } else {
18561            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18562        }
18563    }
18564
18565    @Override
18566    public void deleteApplicationCacheFiles(final String packageName,
18567            final IPackageDataObserver observer) {
18568        final int userId = UserHandle.getCallingUserId();
18569        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18570    }
18571
18572    @Override
18573    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18574            final IPackageDataObserver observer) {
18575        mContext.enforceCallingOrSelfPermission(
18576                android.Manifest.permission.DELETE_CACHE_FILES, null);
18577        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18578                /* requireFullPermission= */ true, /* checkShell= */ false,
18579                "delete application cache files");
18580
18581        final PackageParser.Package pkg;
18582        synchronized (mPackages) {
18583            pkg = mPackages.get(packageName);
18584        }
18585
18586        // Queue up an async operation since the package deletion may take a little while.
18587        mHandler.post(new Runnable() {
18588            public void run() {
18589                synchronized (mInstallLock) {
18590                    final int flags = StorageManager.FLAG_STORAGE_DE
18591                            | StorageManager.FLAG_STORAGE_CE;
18592                    // We're only clearing cache files, so we don't care if the
18593                    // app is unfrozen and still able to run
18594                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18595                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18596                }
18597                clearExternalStorageDataSync(packageName, userId, false);
18598                if (observer != null) {
18599                    try {
18600                        observer.onRemoveCompleted(packageName, true);
18601                    } catch (RemoteException e) {
18602                        Log.i(TAG, "Observer no longer exists.");
18603                    }
18604                }
18605            }
18606        });
18607    }
18608
18609    @Override
18610    public void getPackageSizeInfo(final String packageName, int userHandle,
18611            final IPackageStatsObserver observer) {
18612        throw new UnsupportedOperationException(
18613                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18614    }
18615
18616    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18617        final PackageSetting ps;
18618        synchronized (mPackages) {
18619            ps = mSettings.mPackages.get(packageName);
18620            if (ps == null) {
18621                Slog.w(TAG, "Failed to find settings for " + packageName);
18622                return false;
18623            }
18624        }
18625
18626        final String[] packageNames = { packageName };
18627        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18628        final String[] codePaths = { ps.codePathString };
18629
18630        try {
18631            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18632                    ps.appId, ceDataInodes, codePaths, stats);
18633
18634            // For now, ignore code size of packages on system partition
18635            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18636                stats.codeSize = 0;
18637            }
18638
18639            // External clients expect these to be tracked separately
18640            stats.dataSize -= stats.cacheSize;
18641
18642        } catch (InstallerException e) {
18643            Slog.w(TAG, String.valueOf(e));
18644            return false;
18645        }
18646
18647        return true;
18648    }
18649
18650    private int getUidTargetSdkVersionLockedLPr(int uid) {
18651        Object obj = mSettings.getUserIdLPr(uid);
18652        if (obj instanceof SharedUserSetting) {
18653            final SharedUserSetting sus = (SharedUserSetting) obj;
18654            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18655            final Iterator<PackageSetting> it = sus.packages.iterator();
18656            while (it.hasNext()) {
18657                final PackageSetting ps = it.next();
18658                if (ps.pkg != null) {
18659                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18660                    if (v < vers) vers = v;
18661                }
18662            }
18663            return vers;
18664        } else if (obj instanceof PackageSetting) {
18665            final PackageSetting ps = (PackageSetting) obj;
18666            if (ps.pkg != null) {
18667                return ps.pkg.applicationInfo.targetSdkVersion;
18668            }
18669        }
18670        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18671    }
18672
18673    @Override
18674    public void addPreferredActivity(IntentFilter filter, int match,
18675            ComponentName[] set, ComponentName activity, int userId) {
18676        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18677                "Adding preferred");
18678    }
18679
18680    private void addPreferredActivityInternal(IntentFilter filter, int match,
18681            ComponentName[] set, ComponentName activity, boolean always, int userId,
18682            String opname) {
18683        // writer
18684        int callingUid = Binder.getCallingUid();
18685        enforceCrossUserPermission(callingUid, userId,
18686                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18687        if (filter.countActions() == 0) {
18688            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18689            return;
18690        }
18691        synchronized (mPackages) {
18692            if (mContext.checkCallingOrSelfPermission(
18693                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18694                    != PackageManager.PERMISSION_GRANTED) {
18695                if (getUidTargetSdkVersionLockedLPr(callingUid)
18696                        < Build.VERSION_CODES.FROYO) {
18697                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18698                            + callingUid);
18699                    return;
18700                }
18701                mContext.enforceCallingOrSelfPermission(
18702                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18703            }
18704
18705            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18706            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18707                    + userId + ":");
18708            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18709            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18710            scheduleWritePackageRestrictionsLocked(userId);
18711            postPreferredActivityChangedBroadcast(userId);
18712        }
18713    }
18714
18715    private void postPreferredActivityChangedBroadcast(int userId) {
18716        mHandler.post(() -> {
18717            final IActivityManager am = ActivityManager.getService();
18718            if (am == null) {
18719                return;
18720            }
18721
18722            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18723            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18724            try {
18725                am.broadcastIntent(null, intent, null, null,
18726                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18727                        null, false, false, userId);
18728            } catch (RemoteException e) {
18729            }
18730        });
18731    }
18732
18733    @Override
18734    public void replacePreferredActivity(IntentFilter filter, int match,
18735            ComponentName[] set, ComponentName activity, int userId) {
18736        if (filter.countActions() != 1) {
18737            throw new IllegalArgumentException(
18738                    "replacePreferredActivity expects filter to have only 1 action.");
18739        }
18740        if (filter.countDataAuthorities() != 0
18741                || filter.countDataPaths() != 0
18742                || filter.countDataSchemes() > 1
18743                || filter.countDataTypes() != 0) {
18744            throw new IllegalArgumentException(
18745                    "replacePreferredActivity expects filter to have no data authorities, " +
18746                    "paths, or types; and at most one scheme.");
18747        }
18748
18749        final int callingUid = Binder.getCallingUid();
18750        enforceCrossUserPermission(callingUid, userId,
18751                true /* requireFullPermission */, false /* checkShell */,
18752                "replace preferred activity");
18753        synchronized (mPackages) {
18754            if (mContext.checkCallingOrSelfPermission(
18755                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18756                    != PackageManager.PERMISSION_GRANTED) {
18757                if (getUidTargetSdkVersionLockedLPr(callingUid)
18758                        < Build.VERSION_CODES.FROYO) {
18759                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18760                            + Binder.getCallingUid());
18761                    return;
18762                }
18763                mContext.enforceCallingOrSelfPermission(
18764                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18765            }
18766
18767            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18768            if (pir != null) {
18769                // Get all of the existing entries that exactly match this filter.
18770                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18771                if (existing != null && existing.size() == 1) {
18772                    PreferredActivity cur = existing.get(0);
18773                    if (DEBUG_PREFERRED) {
18774                        Slog.i(TAG, "Checking replace of preferred:");
18775                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18776                        if (!cur.mPref.mAlways) {
18777                            Slog.i(TAG, "  -- CUR; not mAlways!");
18778                        } else {
18779                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18780                            Slog.i(TAG, "  -- CUR: mSet="
18781                                    + Arrays.toString(cur.mPref.mSetComponents));
18782                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18783                            Slog.i(TAG, "  -- NEW: mMatch="
18784                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18785                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18786                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18787                        }
18788                    }
18789                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18790                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18791                            && cur.mPref.sameSet(set)) {
18792                        // Setting the preferred activity to what it happens to be already
18793                        if (DEBUG_PREFERRED) {
18794                            Slog.i(TAG, "Replacing with same preferred activity "
18795                                    + cur.mPref.mShortComponent + " for user "
18796                                    + userId + ":");
18797                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18798                        }
18799                        return;
18800                    }
18801                }
18802
18803                if (existing != null) {
18804                    if (DEBUG_PREFERRED) {
18805                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18806                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18807                    }
18808                    for (int i = 0; i < existing.size(); i++) {
18809                        PreferredActivity pa = existing.get(i);
18810                        if (DEBUG_PREFERRED) {
18811                            Slog.i(TAG, "Removing existing preferred activity "
18812                                    + pa.mPref.mComponent + ":");
18813                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18814                        }
18815                        pir.removeFilter(pa);
18816                    }
18817                }
18818            }
18819            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18820                    "Replacing preferred");
18821        }
18822    }
18823
18824    @Override
18825    public void clearPackagePreferredActivities(String packageName) {
18826        final int uid = Binder.getCallingUid();
18827        // writer
18828        synchronized (mPackages) {
18829            PackageParser.Package pkg = mPackages.get(packageName);
18830            if (pkg == null || pkg.applicationInfo.uid != uid) {
18831                if (mContext.checkCallingOrSelfPermission(
18832                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18833                        != PackageManager.PERMISSION_GRANTED) {
18834                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18835                            < Build.VERSION_CODES.FROYO) {
18836                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18837                                + Binder.getCallingUid());
18838                        return;
18839                    }
18840                    mContext.enforceCallingOrSelfPermission(
18841                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18842                }
18843            }
18844
18845            int user = UserHandle.getCallingUserId();
18846            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18847                scheduleWritePackageRestrictionsLocked(user);
18848            }
18849        }
18850    }
18851
18852    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18853    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18854        ArrayList<PreferredActivity> removed = null;
18855        boolean changed = false;
18856        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18857            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18858            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18859            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18860                continue;
18861            }
18862            Iterator<PreferredActivity> it = pir.filterIterator();
18863            while (it.hasNext()) {
18864                PreferredActivity pa = it.next();
18865                // Mark entry for removal only if it matches the package name
18866                // and the entry is of type "always".
18867                if (packageName == null ||
18868                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18869                                && pa.mPref.mAlways)) {
18870                    if (removed == null) {
18871                        removed = new ArrayList<PreferredActivity>();
18872                    }
18873                    removed.add(pa);
18874                }
18875            }
18876            if (removed != null) {
18877                for (int j=0; j<removed.size(); j++) {
18878                    PreferredActivity pa = removed.get(j);
18879                    pir.removeFilter(pa);
18880                }
18881                changed = true;
18882            }
18883        }
18884        if (changed) {
18885            postPreferredActivityChangedBroadcast(userId);
18886        }
18887        return changed;
18888    }
18889
18890    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18891    private void clearIntentFilterVerificationsLPw(int userId) {
18892        final int packageCount = mPackages.size();
18893        for (int i = 0; i < packageCount; i++) {
18894            PackageParser.Package pkg = mPackages.valueAt(i);
18895            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18896        }
18897    }
18898
18899    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18900    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18901        if (userId == UserHandle.USER_ALL) {
18902            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18903                    sUserManager.getUserIds())) {
18904                for (int oneUserId : sUserManager.getUserIds()) {
18905                    scheduleWritePackageRestrictionsLocked(oneUserId);
18906                }
18907            }
18908        } else {
18909            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18910                scheduleWritePackageRestrictionsLocked(userId);
18911            }
18912        }
18913    }
18914
18915    void clearDefaultBrowserIfNeeded(String packageName) {
18916        for (int oneUserId : sUserManager.getUserIds()) {
18917            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18918            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18919            if (packageName.equals(defaultBrowserPackageName)) {
18920                setDefaultBrowserPackageName(null, oneUserId);
18921            }
18922        }
18923    }
18924
18925    @Override
18926    public void resetApplicationPreferences(int userId) {
18927        mContext.enforceCallingOrSelfPermission(
18928                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18929        final long identity = Binder.clearCallingIdentity();
18930        // writer
18931        try {
18932            synchronized (mPackages) {
18933                clearPackagePreferredActivitiesLPw(null, userId);
18934                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18935                // TODO: We have to reset the default SMS and Phone. This requires
18936                // significant refactoring to keep all default apps in the package
18937                // manager (cleaner but more work) or have the services provide
18938                // callbacks to the package manager to request a default app reset.
18939                applyFactoryDefaultBrowserLPw(userId);
18940                clearIntentFilterVerificationsLPw(userId);
18941                primeDomainVerificationsLPw(userId);
18942                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18943                scheduleWritePackageRestrictionsLocked(userId);
18944            }
18945            resetNetworkPolicies(userId);
18946        } finally {
18947            Binder.restoreCallingIdentity(identity);
18948        }
18949    }
18950
18951    @Override
18952    public int getPreferredActivities(List<IntentFilter> outFilters,
18953            List<ComponentName> outActivities, String packageName) {
18954
18955        int num = 0;
18956        final int userId = UserHandle.getCallingUserId();
18957        // reader
18958        synchronized (mPackages) {
18959            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18960            if (pir != null) {
18961                final Iterator<PreferredActivity> it = pir.filterIterator();
18962                while (it.hasNext()) {
18963                    final PreferredActivity pa = it.next();
18964                    if (packageName == null
18965                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18966                                    && pa.mPref.mAlways)) {
18967                        if (outFilters != null) {
18968                            outFilters.add(new IntentFilter(pa));
18969                        }
18970                        if (outActivities != null) {
18971                            outActivities.add(pa.mPref.mComponent);
18972                        }
18973                    }
18974                }
18975            }
18976        }
18977
18978        return num;
18979    }
18980
18981    @Override
18982    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18983            int userId) {
18984        int callingUid = Binder.getCallingUid();
18985        if (callingUid != Process.SYSTEM_UID) {
18986            throw new SecurityException(
18987                    "addPersistentPreferredActivity can only be run by the system");
18988        }
18989        if (filter.countActions() == 0) {
18990            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18991            return;
18992        }
18993        synchronized (mPackages) {
18994            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18995                    ":");
18996            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18997            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18998                    new PersistentPreferredActivity(filter, activity));
18999            scheduleWritePackageRestrictionsLocked(userId);
19000            postPreferredActivityChangedBroadcast(userId);
19001        }
19002    }
19003
19004    @Override
19005    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19006        int callingUid = Binder.getCallingUid();
19007        if (callingUid != Process.SYSTEM_UID) {
19008            throw new SecurityException(
19009                    "clearPackagePersistentPreferredActivities can only be run by the system");
19010        }
19011        ArrayList<PersistentPreferredActivity> removed = null;
19012        boolean changed = false;
19013        synchronized (mPackages) {
19014            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19015                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19016                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19017                        .valueAt(i);
19018                if (userId != thisUserId) {
19019                    continue;
19020                }
19021                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19022                while (it.hasNext()) {
19023                    PersistentPreferredActivity ppa = it.next();
19024                    // Mark entry for removal only if it matches the package name.
19025                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19026                        if (removed == null) {
19027                            removed = new ArrayList<PersistentPreferredActivity>();
19028                        }
19029                        removed.add(ppa);
19030                    }
19031                }
19032                if (removed != null) {
19033                    for (int j=0; j<removed.size(); j++) {
19034                        PersistentPreferredActivity ppa = removed.get(j);
19035                        ppir.removeFilter(ppa);
19036                    }
19037                    changed = true;
19038                }
19039            }
19040
19041            if (changed) {
19042                scheduleWritePackageRestrictionsLocked(userId);
19043                postPreferredActivityChangedBroadcast(userId);
19044            }
19045        }
19046    }
19047
19048    /**
19049     * Common machinery for picking apart a restored XML blob and passing
19050     * it to a caller-supplied functor to be applied to the running system.
19051     */
19052    private void restoreFromXml(XmlPullParser parser, int userId,
19053            String expectedStartTag, BlobXmlRestorer functor)
19054            throws IOException, XmlPullParserException {
19055        int type;
19056        while ((type = parser.next()) != XmlPullParser.START_TAG
19057                && type != XmlPullParser.END_DOCUMENT) {
19058        }
19059        if (type != XmlPullParser.START_TAG) {
19060            // oops didn't find a start tag?!
19061            if (DEBUG_BACKUP) {
19062                Slog.e(TAG, "Didn't find start tag during restore");
19063            }
19064            return;
19065        }
19066Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19067        // this is supposed to be TAG_PREFERRED_BACKUP
19068        if (!expectedStartTag.equals(parser.getName())) {
19069            if (DEBUG_BACKUP) {
19070                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19071            }
19072            return;
19073        }
19074
19075        // skip interfering stuff, then we're aligned with the backing implementation
19076        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19077Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19078        functor.apply(parser, userId);
19079    }
19080
19081    private interface BlobXmlRestorer {
19082        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19083    }
19084
19085    /**
19086     * Non-Binder method, support for the backup/restore mechanism: write the
19087     * full set of preferred activities in its canonical XML format.  Returns the
19088     * XML output as a byte array, or null if there is none.
19089     */
19090    @Override
19091    public byte[] getPreferredActivityBackup(int userId) {
19092        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19093            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19094        }
19095
19096        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19097        try {
19098            final XmlSerializer serializer = new FastXmlSerializer();
19099            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19100            serializer.startDocument(null, true);
19101            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19102
19103            synchronized (mPackages) {
19104                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19105            }
19106
19107            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19108            serializer.endDocument();
19109            serializer.flush();
19110        } catch (Exception e) {
19111            if (DEBUG_BACKUP) {
19112                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19113            }
19114            return null;
19115        }
19116
19117        return dataStream.toByteArray();
19118    }
19119
19120    @Override
19121    public void restorePreferredActivities(byte[] backup, int userId) {
19122        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19123            throw new SecurityException("Only the system may call restorePreferredActivities()");
19124        }
19125
19126        try {
19127            final XmlPullParser parser = Xml.newPullParser();
19128            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19129            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19130                    new BlobXmlRestorer() {
19131                        @Override
19132                        public void apply(XmlPullParser parser, int userId)
19133                                throws XmlPullParserException, IOException {
19134                            synchronized (mPackages) {
19135                                mSettings.readPreferredActivitiesLPw(parser, userId);
19136                            }
19137                        }
19138                    } );
19139        } catch (Exception e) {
19140            if (DEBUG_BACKUP) {
19141                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19142            }
19143        }
19144    }
19145
19146    /**
19147     * Non-Binder method, support for the backup/restore mechanism: write the
19148     * default browser (etc) settings in its canonical XML format.  Returns the default
19149     * browser XML representation as a byte array, or null if there is none.
19150     */
19151    @Override
19152    public byte[] getDefaultAppsBackup(int userId) {
19153        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19154            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19155        }
19156
19157        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19158        try {
19159            final XmlSerializer serializer = new FastXmlSerializer();
19160            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19161            serializer.startDocument(null, true);
19162            serializer.startTag(null, TAG_DEFAULT_APPS);
19163
19164            synchronized (mPackages) {
19165                mSettings.writeDefaultAppsLPr(serializer, userId);
19166            }
19167
19168            serializer.endTag(null, TAG_DEFAULT_APPS);
19169            serializer.endDocument();
19170            serializer.flush();
19171        } catch (Exception e) {
19172            if (DEBUG_BACKUP) {
19173                Slog.e(TAG, "Unable to write default apps for backup", e);
19174            }
19175            return null;
19176        }
19177
19178        return dataStream.toByteArray();
19179    }
19180
19181    @Override
19182    public void restoreDefaultApps(byte[] backup, int userId) {
19183        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19184            throw new SecurityException("Only the system may call restoreDefaultApps()");
19185        }
19186
19187        try {
19188            final XmlPullParser parser = Xml.newPullParser();
19189            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19190            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19191                    new BlobXmlRestorer() {
19192                        @Override
19193                        public void apply(XmlPullParser parser, int userId)
19194                                throws XmlPullParserException, IOException {
19195                            synchronized (mPackages) {
19196                                mSettings.readDefaultAppsLPw(parser, userId);
19197                            }
19198                        }
19199                    } );
19200        } catch (Exception e) {
19201            if (DEBUG_BACKUP) {
19202                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19203            }
19204        }
19205    }
19206
19207    @Override
19208    public byte[] getIntentFilterVerificationBackup(int userId) {
19209        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19210            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19211        }
19212
19213        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19214        try {
19215            final XmlSerializer serializer = new FastXmlSerializer();
19216            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19217            serializer.startDocument(null, true);
19218            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19219
19220            synchronized (mPackages) {
19221                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19222            }
19223
19224            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19225            serializer.endDocument();
19226            serializer.flush();
19227        } catch (Exception e) {
19228            if (DEBUG_BACKUP) {
19229                Slog.e(TAG, "Unable to write default apps for backup", e);
19230            }
19231            return null;
19232        }
19233
19234        return dataStream.toByteArray();
19235    }
19236
19237    @Override
19238    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19239        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19240            throw new SecurityException("Only the system may call restorePreferredActivities()");
19241        }
19242
19243        try {
19244            final XmlPullParser parser = Xml.newPullParser();
19245            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19246            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19247                    new BlobXmlRestorer() {
19248                        @Override
19249                        public void apply(XmlPullParser parser, int userId)
19250                                throws XmlPullParserException, IOException {
19251                            synchronized (mPackages) {
19252                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19253                                mSettings.writeLPr();
19254                            }
19255                        }
19256                    } );
19257        } catch (Exception e) {
19258            if (DEBUG_BACKUP) {
19259                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19260            }
19261        }
19262    }
19263
19264    @Override
19265    public byte[] getPermissionGrantBackup(int userId) {
19266        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19267            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19268        }
19269
19270        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19271        try {
19272            final XmlSerializer serializer = new FastXmlSerializer();
19273            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19274            serializer.startDocument(null, true);
19275            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19276
19277            synchronized (mPackages) {
19278                serializeRuntimePermissionGrantsLPr(serializer, userId);
19279            }
19280
19281            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19282            serializer.endDocument();
19283            serializer.flush();
19284        } catch (Exception e) {
19285            if (DEBUG_BACKUP) {
19286                Slog.e(TAG, "Unable to write default apps for backup", e);
19287            }
19288            return null;
19289        }
19290
19291        return dataStream.toByteArray();
19292    }
19293
19294    @Override
19295    public void restorePermissionGrants(byte[] backup, int userId) {
19296        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19297            throw new SecurityException("Only the system may call restorePermissionGrants()");
19298        }
19299
19300        try {
19301            final XmlPullParser parser = Xml.newPullParser();
19302            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19303            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19304                    new BlobXmlRestorer() {
19305                        @Override
19306                        public void apply(XmlPullParser parser, int userId)
19307                                throws XmlPullParserException, IOException {
19308                            synchronized (mPackages) {
19309                                processRestoredPermissionGrantsLPr(parser, userId);
19310                            }
19311                        }
19312                    } );
19313        } catch (Exception e) {
19314            if (DEBUG_BACKUP) {
19315                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19316            }
19317        }
19318    }
19319
19320    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19321            throws IOException {
19322        serializer.startTag(null, TAG_ALL_GRANTS);
19323
19324        final int N = mSettings.mPackages.size();
19325        for (int i = 0; i < N; i++) {
19326            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19327            boolean pkgGrantsKnown = false;
19328
19329            PermissionsState packagePerms = ps.getPermissionsState();
19330
19331            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19332                final int grantFlags = state.getFlags();
19333                // only look at grants that are not system/policy fixed
19334                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19335                    final boolean isGranted = state.isGranted();
19336                    // And only back up the user-twiddled state bits
19337                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19338                        final String packageName = mSettings.mPackages.keyAt(i);
19339                        if (!pkgGrantsKnown) {
19340                            serializer.startTag(null, TAG_GRANT);
19341                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19342                            pkgGrantsKnown = true;
19343                        }
19344
19345                        final boolean userSet =
19346                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19347                        final boolean userFixed =
19348                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19349                        final boolean revoke =
19350                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19351
19352                        serializer.startTag(null, TAG_PERMISSION);
19353                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19354                        if (isGranted) {
19355                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19356                        }
19357                        if (userSet) {
19358                            serializer.attribute(null, ATTR_USER_SET, "true");
19359                        }
19360                        if (userFixed) {
19361                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19362                        }
19363                        if (revoke) {
19364                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19365                        }
19366                        serializer.endTag(null, TAG_PERMISSION);
19367                    }
19368                }
19369            }
19370
19371            if (pkgGrantsKnown) {
19372                serializer.endTag(null, TAG_GRANT);
19373            }
19374        }
19375
19376        serializer.endTag(null, TAG_ALL_GRANTS);
19377    }
19378
19379    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19380            throws XmlPullParserException, IOException {
19381        String pkgName = null;
19382        int outerDepth = parser.getDepth();
19383        int type;
19384        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19385                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19386            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19387                continue;
19388            }
19389
19390            final String tagName = parser.getName();
19391            if (tagName.equals(TAG_GRANT)) {
19392                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19393                if (DEBUG_BACKUP) {
19394                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19395                }
19396            } else if (tagName.equals(TAG_PERMISSION)) {
19397
19398                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19399                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19400
19401                int newFlagSet = 0;
19402                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19403                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19404                }
19405                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19406                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19407                }
19408                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19409                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19410                }
19411                if (DEBUG_BACKUP) {
19412                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19413                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19414                }
19415                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19416                if (ps != null) {
19417                    // Already installed so we apply the grant immediately
19418                    if (DEBUG_BACKUP) {
19419                        Slog.v(TAG, "        + already installed; applying");
19420                    }
19421                    PermissionsState perms = ps.getPermissionsState();
19422                    BasePermission bp = mSettings.mPermissions.get(permName);
19423                    if (bp != null) {
19424                        if (isGranted) {
19425                            perms.grantRuntimePermission(bp, userId);
19426                        }
19427                        if (newFlagSet != 0) {
19428                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19429                        }
19430                    }
19431                } else {
19432                    // Need to wait for post-restore install to apply the grant
19433                    if (DEBUG_BACKUP) {
19434                        Slog.v(TAG, "        - not yet installed; saving for later");
19435                    }
19436                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19437                            isGranted, newFlagSet, userId);
19438                }
19439            } else {
19440                PackageManagerService.reportSettingsProblem(Log.WARN,
19441                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19442                XmlUtils.skipCurrentTag(parser);
19443            }
19444        }
19445
19446        scheduleWriteSettingsLocked();
19447        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19448    }
19449
19450    @Override
19451    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19452            int sourceUserId, int targetUserId, int flags) {
19453        mContext.enforceCallingOrSelfPermission(
19454                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19455        int callingUid = Binder.getCallingUid();
19456        enforceOwnerRights(ownerPackage, callingUid);
19457        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19458        if (intentFilter.countActions() == 0) {
19459            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19460            return;
19461        }
19462        synchronized (mPackages) {
19463            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19464                    ownerPackage, targetUserId, flags);
19465            CrossProfileIntentResolver resolver =
19466                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19467            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19468            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19469            if (existing != null) {
19470                int size = existing.size();
19471                for (int i = 0; i < size; i++) {
19472                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19473                        return;
19474                    }
19475                }
19476            }
19477            resolver.addFilter(newFilter);
19478            scheduleWritePackageRestrictionsLocked(sourceUserId);
19479        }
19480    }
19481
19482    @Override
19483    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19484        mContext.enforceCallingOrSelfPermission(
19485                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19486        int callingUid = Binder.getCallingUid();
19487        enforceOwnerRights(ownerPackage, callingUid);
19488        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19489        synchronized (mPackages) {
19490            CrossProfileIntentResolver resolver =
19491                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19492            ArraySet<CrossProfileIntentFilter> set =
19493                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19494            for (CrossProfileIntentFilter filter : set) {
19495                if (filter.getOwnerPackage().equals(ownerPackage)) {
19496                    resolver.removeFilter(filter);
19497                }
19498            }
19499            scheduleWritePackageRestrictionsLocked(sourceUserId);
19500        }
19501    }
19502
19503    // Enforcing that callingUid is owning pkg on userId
19504    private void enforceOwnerRights(String pkg, int callingUid) {
19505        // The system owns everything.
19506        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19507            return;
19508        }
19509        int callingUserId = UserHandle.getUserId(callingUid);
19510        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19511        if (pi == null) {
19512            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19513                    + callingUserId);
19514        }
19515        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19516            throw new SecurityException("Calling uid " + callingUid
19517                    + " does not own package " + pkg);
19518        }
19519    }
19520
19521    @Override
19522    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19523        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19524    }
19525
19526    /**
19527     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19528     * then reports the most likely home activity or null if there are more than one.
19529     */
19530    public ComponentName getDefaultHomeActivity(int userId) {
19531        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19532        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19533        if (cn != null) {
19534            return cn;
19535        }
19536
19537        // Find the launcher with the highest priority and return that component if there are no
19538        // other home activity with the same priority.
19539        int lastPriority = Integer.MIN_VALUE;
19540        ComponentName lastComponent = null;
19541        final int size = allHomeCandidates.size();
19542        for (int i = 0; i < size; i++) {
19543            final ResolveInfo ri = allHomeCandidates.get(i);
19544            if (ri.priority > lastPriority) {
19545                lastComponent = ri.activityInfo.getComponentName();
19546                lastPriority = ri.priority;
19547            } else if (ri.priority == lastPriority) {
19548                // Two components found with same priority.
19549                lastComponent = null;
19550            }
19551        }
19552        return lastComponent;
19553    }
19554
19555    private Intent getHomeIntent() {
19556        Intent intent = new Intent(Intent.ACTION_MAIN);
19557        intent.addCategory(Intent.CATEGORY_HOME);
19558        intent.addCategory(Intent.CATEGORY_DEFAULT);
19559        return intent;
19560    }
19561
19562    private IntentFilter getHomeFilter() {
19563        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19564        filter.addCategory(Intent.CATEGORY_HOME);
19565        filter.addCategory(Intent.CATEGORY_DEFAULT);
19566        return filter;
19567    }
19568
19569    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19570            int userId) {
19571        Intent intent  = getHomeIntent();
19572        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19573                PackageManager.GET_META_DATA, userId);
19574        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19575                true, false, false, userId);
19576
19577        allHomeCandidates.clear();
19578        if (list != null) {
19579            for (ResolveInfo ri : list) {
19580                allHomeCandidates.add(ri);
19581            }
19582        }
19583        return (preferred == null || preferred.activityInfo == null)
19584                ? null
19585                : new ComponentName(preferred.activityInfo.packageName,
19586                        preferred.activityInfo.name);
19587    }
19588
19589    @Override
19590    public void setHomeActivity(ComponentName comp, int userId) {
19591        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19592        getHomeActivitiesAsUser(homeActivities, userId);
19593
19594        boolean found = false;
19595
19596        final int size = homeActivities.size();
19597        final ComponentName[] set = new ComponentName[size];
19598        for (int i = 0; i < size; i++) {
19599            final ResolveInfo candidate = homeActivities.get(i);
19600            final ActivityInfo info = candidate.activityInfo;
19601            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19602            set[i] = activityName;
19603            if (!found && activityName.equals(comp)) {
19604                found = true;
19605            }
19606        }
19607        if (!found) {
19608            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19609                    + userId);
19610        }
19611        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19612                set, comp, userId);
19613    }
19614
19615    private @Nullable String getSetupWizardPackageName() {
19616        final Intent intent = new Intent(Intent.ACTION_MAIN);
19617        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19618
19619        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19620                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19621                        | MATCH_DISABLED_COMPONENTS,
19622                UserHandle.myUserId());
19623        if (matches.size() == 1) {
19624            return matches.get(0).getComponentInfo().packageName;
19625        } else {
19626            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19627                    + ": matches=" + matches);
19628            return null;
19629        }
19630    }
19631
19632    private @Nullable String getStorageManagerPackageName() {
19633        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19634
19635        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19636                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19637                        | MATCH_DISABLED_COMPONENTS,
19638                UserHandle.myUserId());
19639        if (matches.size() == 1) {
19640            return matches.get(0).getComponentInfo().packageName;
19641        } else {
19642            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19643                    + matches.size() + ": matches=" + matches);
19644            return null;
19645        }
19646    }
19647
19648    @Override
19649    public void setApplicationEnabledSetting(String appPackageName,
19650            int newState, int flags, int userId, String callingPackage) {
19651        if (!sUserManager.exists(userId)) return;
19652        if (callingPackage == null) {
19653            callingPackage = Integer.toString(Binder.getCallingUid());
19654        }
19655        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19656    }
19657
19658    @Override
19659    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19660        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19661        synchronized (mPackages) {
19662            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19663            if (pkgSetting != null) {
19664                pkgSetting.setUpdateAvailable(updateAvailable);
19665            }
19666        }
19667    }
19668
19669    @Override
19670    public void setComponentEnabledSetting(ComponentName componentName,
19671            int newState, int flags, int userId) {
19672        if (!sUserManager.exists(userId)) return;
19673        setEnabledSetting(componentName.getPackageName(),
19674                componentName.getClassName(), newState, flags, userId, null);
19675    }
19676
19677    private void setEnabledSetting(final String packageName, String className, int newState,
19678            final int flags, int userId, String callingPackage) {
19679        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19680              || newState == COMPONENT_ENABLED_STATE_ENABLED
19681              || newState == COMPONENT_ENABLED_STATE_DISABLED
19682              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19683              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19684            throw new IllegalArgumentException("Invalid new component state: "
19685                    + newState);
19686        }
19687        PackageSetting pkgSetting;
19688        final int uid = Binder.getCallingUid();
19689        final int permission;
19690        if (uid == Process.SYSTEM_UID) {
19691            permission = PackageManager.PERMISSION_GRANTED;
19692        } else {
19693            permission = mContext.checkCallingOrSelfPermission(
19694                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19695        }
19696        enforceCrossUserPermission(uid, userId,
19697                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19698        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19699        boolean sendNow = false;
19700        boolean isApp = (className == null);
19701        String componentName = isApp ? packageName : className;
19702        int packageUid = -1;
19703        ArrayList<String> components;
19704
19705        // writer
19706        synchronized (mPackages) {
19707            pkgSetting = mSettings.mPackages.get(packageName);
19708            if (pkgSetting == null) {
19709                if (className == null) {
19710                    throw new IllegalArgumentException("Unknown package: " + packageName);
19711                }
19712                throw new IllegalArgumentException(
19713                        "Unknown component: " + packageName + "/" + className);
19714            }
19715        }
19716
19717        // Limit who can change which apps
19718        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19719            // Don't allow apps that don't have permission to modify other apps
19720            if (!allowedByPermission) {
19721                throw new SecurityException(
19722                        "Permission Denial: attempt to change component state from pid="
19723                        + Binder.getCallingPid()
19724                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19725            }
19726            // Don't allow changing protected packages.
19727            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19728                throw new SecurityException("Cannot disable a protected package: " + packageName);
19729            }
19730        }
19731
19732        synchronized (mPackages) {
19733            if (uid == Process.SHELL_UID
19734                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19735                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19736                // unless it is a test package.
19737                int oldState = pkgSetting.getEnabled(userId);
19738                if (className == null
19739                    &&
19740                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19741                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19742                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19743                    &&
19744                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19745                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19746                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19747                    // ok
19748                } else {
19749                    throw new SecurityException(
19750                            "Shell cannot change component state for " + packageName + "/"
19751                            + className + " to " + newState);
19752                }
19753            }
19754            if (className == null) {
19755                // We're dealing with an application/package level state change
19756                if (pkgSetting.getEnabled(userId) == newState) {
19757                    // Nothing to do
19758                    return;
19759                }
19760                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19761                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19762                    // Don't care about who enables an app.
19763                    callingPackage = null;
19764                }
19765                pkgSetting.setEnabled(newState, userId, callingPackage);
19766                // pkgSetting.pkg.mSetEnabled = newState;
19767            } else {
19768                // We're dealing with a component level state change
19769                // First, verify that this is a valid class name.
19770                PackageParser.Package pkg = pkgSetting.pkg;
19771                if (pkg == null || !pkg.hasComponentClassName(className)) {
19772                    if (pkg != null &&
19773                            pkg.applicationInfo.targetSdkVersion >=
19774                                    Build.VERSION_CODES.JELLY_BEAN) {
19775                        throw new IllegalArgumentException("Component class " + className
19776                                + " does not exist in " + packageName);
19777                    } else {
19778                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19779                                + className + " does not exist in " + packageName);
19780                    }
19781                }
19782                switch (newState) {
19783                case COMPONENT_ENABLED_STATE_ENABLED:
19784                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19785                        return;
19786                    }
19787                    break;
19788                case COMPONENT_ENABLED_STATE_DISABLED:
19789                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19790                        return;
19791                    }
19792                    break;
19793                case COMPONENT_ENABLED_STATE_DEFAULT:
19794                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19795                        return;
19796                    }
19797                    break;
19798                default:
19799                    Slog.e(TAG, "Invalid new component state: " + newState);
19800                    return;
19801                }
19802            }
19803            scheduleWritePackageRestrictionsLocked(userId);
19804            updateSequenceNumberLP(packageName, new int[] { userId });
19805            components = mPendingBroadcasts.get(userId, packageName);
19806            final boolean newPackage = components == null;
19807            if (newPackage) {
19808                components = new ArrayList<String>();
19809            }
19810            if (!components.contains(componentName)) {
19811                components.add(componentName);
19812            }
19813            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19814                sendNow = true;
19815                // Purge entry from pending broadcast list if another one exists already
19816                // since we are sending one right away.
19817                mPendingBroadcasts.remove(userId, packageName);
19818            } else {
19819                if (newPackage) {
19820                    mPendingBroadcasts.put(userId, packageName, components);
19821                }
19822                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19823                    // Schedule a message
19824                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19825                }
19826            }
19827        }
19828
19829        long callingId = Binder.clearCallingIdentity();
19830        try {
19831            if (sendNow) {
19832                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19833                sendPackageChangedBroadcast(packageName,
19834                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19835            }
19836        } finally {
19837            Binder.restoreCallingIdentity(callingId);
19838        }
19839    }
19840
19841    @Override
19842    public void flushPackageRestrictionsAsUser(int userId) {
19843        if (!sUserManager.exists(userId)) {
19844            return;
19845        }
19846        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19847                false /* checkShell */, "flushPackageRestrictions");
19848        synchronized (mPackages) {
19849            mSettings.writePackageRestrictionsLPr(userId);
19850            mDirtyUsers.remove(userId);
19851            if (mDirtyUsers.isEmpty()) {
19852                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19853            }
19854        }
19855    }
19856
19857    private void sendPackageChangedBroadcast(String packageName,
19858            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19859        if (DEBUG_INSTALL)
19860            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19861                    + componentNames);
19862        Bundle extras = new Bundle(4);
19863        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19864        String nameList[] = new String[componentNames.size()];
19865        componentNames.toArray(nameList);
19866        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19867        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19868        extras.putInt(Intent.EXTRA_UID, packageUid);
19869        // If this is not reporting a change of the overall package, then only send it
19870        // to registered receivers.  We don't want to launch a swath of apps for every
19871        // little component state change.
19872        final int flags = !componentNames.contains(packageName)
19873                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19874        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19875                new int[] {UserHandle.getUserId(packageUid)});
19876    }
19877
19878    @Override
19879    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19880        if (!sUserManager.exists(userId)) return;
19881        final int uid = Binder.getCallingUid();
19882        final int permission = mContext.checkCallingOrSelfPermission(
19883                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19884        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19885        enforceCrossUserPermission(uid, userId,
19886                true /* requireFullPermission */, true /* checkShell */, "stop package");
19887        // writer
19888        synchronized (mPackages) {
19889            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19890                    allowedByPermission, uid, userId)) {
19891                scheduleWritePackageRestrictionsLocked(userId);
19892            }
19893        }
19894    }
19895
19896    @Override
19897    public String getInstallerPackageName(String packageName) {
19898        // reader
19899        synchronized (mPackages) {
19900            return mSettings.getInstallerPackageNameLPr(packageName);
19901        }
19902    }
19903
19904    public boolean isOrphaned(String packageName) {
19905        // reader
19906        synchronized (mPackages) {
19907            return mSettings.isOrphaned(packageName);
19908        }
19909    }
19910
19911    @Override
19912    public int getApplicationEnabledSetting(String packageName, int userId) {
19913        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19914        int uid = Binder.getCallingUid();
19915        enforceCrossUserPermission(uid, userId,
19916                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19917        // reader
19918        synchronized (mPackages) {
19919            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19920        }
19921    }
19922
19923    @Override
19924    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19925        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19926        int uid = Binder.getCallingUid();
19927        enforceCrossUserPermission(uid, userId,
19928                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19929        // reader
19930        synchronized (mPackages) {
19931            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19932        }
19933    }
19934
19935    @Override
19936    public void enterSafeMode() {
19937        enforceSystemOrRoot("Only the system can request entering safe mode");
19938
19939        if (!mSystemReady) {
19940            mSafeMode = true;
19941        }
19942    }
19943
19944    @Override
19945    public void systemReady() {
19946        mSystemReady = true;
19947
19948        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19949        // disabled after already being started.
19950        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19951                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19952
19953        // Read the compatibilty setting when the system is ready.
19954        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19955                mContext.getContentResolver(),
19956                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19957        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19958        if (DEBUG_SETTINGS) {
19959            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19960        }
19961
19962        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19963
19964        synchronized (mPackages) {
19965            // Verify that all of the preferred activity components actually
19966            // exist.  It is possible for applications to be updated and at
19967            // that point remove a previously declared activity component that
19968            // had been set as a preferred activity.  We try to clean this up
19969            // the next time we encounter that preferred activity, but it is
19970            // possible for the user flow to never be able to return to that
19971            // situation so here we do a sanity check to make sure we haven't
19972            // left any junk around.
19973            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
19974            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19975                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19976                removed.clear();
19977                for (PreferredActivity pa : pir.filterSet()) {
19978                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19979                        removed.add(pa);
19980                    }
19981                }
19982                if (removed.size() > 0) {
19983                    for (int r=0; r<removed.size(); r++) {
19984                        PreferredActivity pa = removed.get(r);
19985                        Slog.w(TAG, "Removing dangling preferred activity: "
19986                                + pa.mPref.mComponent);
19987                        pir.removeFilter(pa);
19988                    }
19989                    mSettings.writePackageRestrictionsLPr(
19990                            mSettings.mPreferredActivities.keyAt(i));
19991                }
19992            }
19993
19994            for (int userId : UserManagerService.getInstance().getUserIds()) {
19995                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
19996                    grantPermissionsUserIds = ArrayUtils.appendInt(
19997                            grantPermissionsUserIds, userId);
19998                }
19999            }
20000        }
20001        sUserManager.systemReady();
20002
20003        // If we upgraded grant all default permissions before kicking off.
20004        for (int userId : grantPermissionsUserIds) {
20005            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20006        }
20007
20008        // If we did not grant default permissions, we preload from this the
20009        // default permission exceptions lazily to ensure we don't hit the
20010        // disk on a new user creation.
20011        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20012            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20013        }
20014
20015        // Kick off any messages waiting for system ready
20016        if (mPostSystemReadyMessages != null) {
20017            for (Message msg : mPostSystemReadyMessages) {
20018                msg.sendToTarget();
20019            }
20020            mPostSystemReadyMessages = null;
20021        }
20022
20023        // Watch for external volumes that come and go over time
20024        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20025        storage.registerListener(mStorageListener);
20026
20027        mInstallerService.systemReady();
20028        mPackageDexOptimizer.systemReady();
20029
20030        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20031                StorageManagerInternal.class);
20032        StorageManagerInternal.addExternalStoragePolicy(
20033                new StorageManagerInternal.ExternalStorageMountPolicy() {
20034            @Override
20035            public int getMountMode(int uid, String packageName) {
20036                if (Process.isIsolated(uid)) {
20037                    return Zygote.MOUNT_EXTERNAL_NONE;
20038                }
20039                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20040                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20041                }
20042                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20043                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20044                }
20045                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20046                    return Zygote.MOUNT_EXTERNAL_READ;
20047                }
20048                return Zygote.MOUNT_EXTERNAL_WRITE;
20049            }
20050
20051            @Override
20052            public boolean hasExternalStorage(int uid, String packageName) {
20053                return true;
20054            }
20055        });
20056
20057        // Now that we're mostly running, clean up stale users and apps
20058        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20059        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20060
20061        if (mPrivappPermissionsViolations != null) {
20062            Slog.wtf(TAG,"Signature|privileged permissions not in "
20063                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20064            mPrivappPermissionsViolations = null;
20065        }
20066    }
20067
20068    public void waitForAppDataPrepared() {
20069        if (mPrepareAppDataFuture == null) {
20070            return;
20071        }
20072        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20073        mPrepareAppDataFuture = null;
20074    }
20075
20076    @Override
20077    public boolean isSafeMode() {
20078        return mSafeMode;
20079    }
20080
20081    @Override
20082    public boolean hasSystemUidErrors() {
20083        return mHasSystemUidErrors;
20084    }
20085
20086    static String arrayToString(int[] array) {
20087        StringBuffer buf = new StringBuffer(128);
20088        buf.append('[');
20089        if (array != null) {
20090            for (int i=0; i<array.length; i++) {
20091                if (i > 0) buf.append(", ");
20092                buf.append(array[i]);
20093            }
20094        }
20095        buf.append(']');
20096        return buf.toString();
20097    }
20098
20099    static class DumpState {
20100        public static final int DUMP_LIBS = 1 << 0;
20101        public static final int DUMP_FEATURES = 1 << 1;
20102        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20103        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20104        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20105        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20106        public static final int DUMP_PERMISSIONS = 1 << 6;
20107        public static final int DUMP_PACKAGES = 1 << 7;
20108        public static final int DUMP_SHARED_USERS = 1 << 8;
20109        public static final int DUMP_MESSAGES = 1 << 9;
20110        public static final int DUMP_PROVIDERS = 1 << 10;
20111        public static final int DUMP_VERIFIERS = 1 << 11;
20112        public static final int DUMP_PREFERRED = 1 << 12;
20113        public static final int DUMP_PREFERRED_XML = 1 << 13;
20114        public static final int DUMP_KEYSETS = 1 << 14;
20115        public static final int DUMP_VERSION = 1 << 15;
20116        public static final int DUMP_INSTALLS = 1 << 16;
20117        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20118        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20119        public static final int DUMP_FROZEN = 1 << 19;
20120        public static final int DUMP_DEXOPT = 1 << 20;
20121        public static final int DUMP_COMPILER_STATS = 1 << 21;
20122        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20123
20124        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20125
20126        private int mTypes;
20127
20128        private int mOptions;
20129
20130        private boolean mTitlePrinted;
20131
20132        private SharedUserSetting mSharedUser;
20133
20134        public boolean isDumping(int type) {
20135            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20136                return true;
20137            }
20138
20139            return (mTypes & type) != 0;
20140        }
20141
20142        public void setDump(int type) {
20143            mTypes |= type;
20144        }
20145
20146        public boolean isOptionEnabled(int option) {
20147            return (mOptions & option) != 0;
20148        }
20149
20150        public void setOptionEnabled(int option) {
20151            mOptions |= option;
20152        }
20153
20154        public boolean onTitlePrinted() {
20155            final boolean printed = mTitlePrinted;
20156            mTitlePrinted = true;
20157            return printed;
20158        }
20159
20160        public boolean getTitlePrinted() {
20161            return mTitlePrinted;
20162        }
20163
20164        public void setTitlePrinted(boolean enabled) {
20165            mTitlePrinted = enabled;
20166        }
20167
20168        public SharedUserSetting getSharedUser() {
20169            return mSharedUser;
20170        }
20171
20172        public void setSharedUser(SharedUserSetting user) {
20173            mSharedUser = user;
20174        }
20175    }
20176
20177    @Override
20178    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20179            FileDescriptor err, String[] args, ShellCallback callback,
20180            ResultReceiver resultReceiver) {
20181        (new PackageManagerShellCommand(this)).exec(
20182                this, in, out, err, args, callback, resultReceiver);
20183    }
20184
20185    @Override
20186    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20187        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20188                != PackageManager.PERMISSION_GRANTED) {
20189            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20190                    + Binder.getCallingPid()
20191                    + ", uid=" + Binder.getCallingUid()
20192                    + " without permission "
20193                    + android.Manifest.permission.DUMP);
20194            return;
20195        }
20196
20197        DumpState dumpState = new DumpState();
20198        boolean fullPreferred = false;
20199        boolean checkin = false;
20200
20201        String packageName = null;
20202        ArraySet<String> permissionNames = null;
20203
20204        int opti = 0;
20205        while (opti < args.length) {
20206            String opt = args[opti];
20207            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20208                break;
20209            }
20210            opti++;
20211
20212            if ("-a".equals(opt)) {
20213                // Right now we only know how to print all.
20214            } else if ("-h".equals(opt)) {
20215                pw.println("Package manager dump options:");
20216                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20217                pw.println("    --checkin: dump for a checkin");
20218                pw.println("    -f: print details of intent filters");
20219                pw.println("    -h: print this help");
20220                pw.println("  cmd may be one of:");
20221                pw.println("    l[ibraries]: list known shared libraries");
20222                pw.println("    f[eatures]: list device features");
20223                pw.println("    k[eysets]: print known keysets");
20224                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20225                pw.println("    perm[issions]: dump permissions");
20226                pw.println("    permission [name ...]: dump declaration and use of given permission");
20227                pw.println("    pref[erred]: print preferred package settings");
20228                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20229                pw.println("    prov[iders]: dump content providers");
20230                pw.println("    p[ackages]: dump installed packages");
20231                pw.println("    s[hared-users]: dump shared user IDs");
20232                pw.println("    m[essages]: print collected runtime messages");
20233                pw.println("    v[erifiers]: print package verifier info");
20234                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20235                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20236                pw.println("    version: print database version info");
20237                pw.println("    write: write current settings now");
20238                pw.println("    installs: details about install sessions");
20239                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20240                pw.println("    dexopt: dump dexopt state");
20241                pw.println("    compiler-stats: dump compiler statistics");
20242                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20243                pw.println("    <package.name>: info about given package");
20244                return;
20245            } else if ("--checkin".equals(opt)) {
20246                checkin = true;
20247            } else if ("-f".equals(opt)) {
20248                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20249            } else if ("--proto".equals(opt)) {
20250                dumpProto(fd);
20251                return;
20252            } else {
20253                pw.println("Unknown argument: " + opt + "; use -h for help");
20254            }
20255        }
20256
20257        // Is the caller requesting to dump a particular piece of data?
20258        if (opti < args.length) {
20259            String cmd = args[opti];
20260            opti++;
20261            // Is this a package name?
20262            if ("android".equals(cmd) || cmd.contains(".")) {
20263                packageName = cmd;
20264                // When dumping a single package, we always dump all of its
20265                // filter information since the amount of data will be reasonable.
20266                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20267            } else if ("check-permission".equals(cmd)) {
20268                if (opti >= args.length) {
20269                    pw.println("Error: check-permission missing permission argument");
20270                    return;
20271                }
20272                String perm = args[opti];
20273                opti++;
20274                if (opti >= args.length) {
20275                    pw.println("Error: check-permission missing package argument");
20276                    return;
20277                }
20278
20279                String pkg = args[opti];
20280                opti++;
20281                int user = UserHandle.getUserId(Binder.getCallingUid());
20282                if (opti < args.length) {
20283                    try {
20284                        user = Integer.parseInt(args[opti]);
20285                    } catch (NumberFormatException e) {
20286                        pw.println("Error: check-permission user argument is not a number: "
20287                                + args[opti]);
20288                        return;
20289                    }
20290                }
20291
20292                // Normalize package name to handle renamed packages and static libs
20293                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20294
20295                pw.println(checkPermission(perm, pkg, user));
20296                return;
20297            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20298                dumpState.setDump(DumpState.DUMP_LIBS);
20299            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20300                dumpState.setDump(DumpState.DUMP_FEATURES);
20301            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20302                if (opti >= args.length) {
20303                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20304                            | DumpState.DUMP_SERVICE_RESOLVERS
20305                            | DumpState.DUMP_RECEIVER_RESOLVERS
20306                            | DumpState.DUMP_CONTENT_RESOLVERS);
20307                } else {
20308                    while (opti < args.length) {
20309                        String name = args[opti];
20310                        if ("a".equals(name) || "activity".equals(name)) {
20311                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20312                        } else if ("s".equals(name) || "service".equals(name)) {
20313                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20314                        } else if ("r".equals(name) || "receiver".equals(name)) {
20315                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20316                        } else if ("c".equals(name) || "content".equals(name)) {
20317                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20318                        } else {
20319                            pw.println("Error: unknown resolver table type: " + name);
20320                            return;
20321                        }
20322                        opti++;
20323                    }
20324                }
20325            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20326                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20327            } else if ("permission".equals(cmd)) {
20328                if (opti >= args.length) {
20329                    pw.println("Error: permission requires permission name");
20330                    return;
20331                }
20332                permissionNames = new ArraySet<>();
20333                while (opti < args.length) {
20334                    permissionNames.add(args[opti]);
20335                    opti++;
20336                }
20337                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20338                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20339            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20340                dumpState.setDump(DumpState.DUMP_PREFERRED);
20341            } else if ("preferred-xml".equals(cmd)) {
20342                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20343                if (opti < args.length && "--full".equals(args[opti])) {
20344                    fullPreferred = true;
20345                    opti++;
20346                }
20347            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20348                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20349            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20350                dumpState.setDump(DumpState.DUMP_PACKAGES);
20351            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20352                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20353            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20354                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20355            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20356                dumpState.setDump(DumpState.DUMP_MESSAGES);
20357            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20358                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20359            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20360                    || "intent-filter-verifiers".equals(cmd)) {
20361                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20362            } else if ("version".equals(cmd)) {
20363                dumpState.setDump(DumpState.DUMP_VERSION);
20364            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20365                dumpState.setDump(DumpState.DUMP_KEYSETS);
20366            } else if ("installs".equals(cmd)) {
20367                dumpState.setDump(DumpState.DUMP_INSTALLS);
20368            } else if ("frozen".equals(cmd)) {
20369                dumpState.setDump(DumpState.DUMP_FROZEN);
20370            } else if ("dexopt".equals(cmd)) {
20371                dumpState.setDump(DumpState.DUMP_DEXOPT);
20372            } else if ("compiler-stats".equals(cmd)) {
20373                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20374            } else if ("enabled-overlays".equals(cmd)) {
20375                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20376            } else if ("write".equals(cmd)) {
20377                synchronized (mPackages) {
20378                    mSettings.writeLPr();
20379                    pw.println("Settings written.");
20380                    return;
20381                }
20382            }
20383        }
20384
20385        if (checkin) {
20386            pw.println("vers,1");
20387        }
20388
20389        // reader
20390        synchronized (mPackages) {
20391            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20392                if (!checkin) {
20393                    if (dumpState.onTitlePrinted())
20394                        pw.println();
20395                    pw.println("Database versions:");
20396                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20397                }
20398            }
20399
20400            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20401                if (!checkin) {
20402                    if (dumpState.onTitlePrinted())
20403                        pw.println();
20404                    pw.println("Verifiers:");
20405                    pw.print("  Required: ");
20406                    pw.print(mRequiredVerifierPackage);
20407                    pw.print(" (uid=");
20408                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20409                            UserHandle.USER_SYSTEM));
20410                    pw.println(")");
20411                } else if (mRequiredVerifierPackage != null) {
20412                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20413                    pw.print(",");
20414                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20415                            UserHandle.USER_SYSTEM));
20416                }
20417            }
20418
20419            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20420                    packageName == null) {
20421                if (mIntentFilterVerifierComponent != null) {
20422                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20423                    if (!checkin) {
20424                        if (dumpState.onTitlePrinted())
20425                            pw.println();
20426                        pw.println("Intent Filter Verifier:");
20427                        pw.print("  Using: ");
20428                        pw.print(verifierPackageName);
20429                        pw.print(" (uid=");
20430                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20431                                UserHandle.USER_SYSTEM));
20432                        pw.println(")");
20433                    } else if (verifierPackageName != null) {
20434                        pw.print("ifv,"); pw.print(verifierPackageName);
20435                        pw.print(",");
20436                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20437                                UserHandle.USER_SYSTEM));
20438                    }
20439                } else {
20440                    pw.println();
20441                    pw.println("No Intent Filter Verifier available!");
20442                }
20443            }
20444
20445            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20446                boolean printedHeader = false;
20447                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20448                while (it.hasNext()) {
20449                    String libName = it.next();
20450                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20451                    if (versionedLib == null) {
20452                        continue;
20453                    }
20454                    final int versionCount = versionedLib.size();
20455                    for (int i = 0; i < versionCount; i++) {
20456                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20457                        if (!checkin) {
20458                            if (!printedHeader) {
20459                                if (dumpState.onTitlePrinted())
20460                                    pw.println();
20461                                pw.println("Libraries:");
20462                                printedHeader = true;
20463                            }
20464                            pw.print("  ");
20465                        } else {
20466                            pw.print("lib,");
20467                        }
20468                        pw.print(libEntry.info.getName());
20469                        if (libEntry.info.isStatic()) {
20470                            pw.print(" version=" + libEntry.info.getVersion());
20471                        }
20472                        if (!checkin) {
20473                            pw.print(" -> ");
20474                        }
20475                        if (libEntry.path != null) {
20476                            pw.print(" (jar) ");
20477                            pw.print(libEntry.path);
20478                        } else {
20479                            pw.print(" (apk) ");
20480                            pw.print(libEntry.apk);
20481                        }
20482                        pw.println();
20483                    }
20484                }
20485            }
20486
20487            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20488                if (dumpState.onTitlePrinted())
20489                    pw.println();
20490                if (!checkin) {
20491                    pw.println("Features:");
20492                }
20493
20494                synchronized (mAvailableFeatures) {
20495                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20496                        if (checkin) {
20497                            pw.print("feat,");
20498                            pw.print(feat.name);
20499                            pw.print(",");
20500                            pw.println(feat.version);
20501                        } else {
20502                            pw.print("  ");
20503                            pw.print(feat.name);
20504                            if (feat.version > 0) {
20505                                pw.print(" version=");
20506                                pw.print(feat.version);
20507                            }
20508                            pw.println();
20509                        }
20510                    }
20511                }
20512            }
20513
20514            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20515                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20516                        : "Activity Resolver Table:", "  ", packageName,
20517                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20518                    dumpState.setTitlePrinted(true);
20519                }
20520            }
20521            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20522                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20523                        : "Receiver Resolver Table:", "  ", packageName,
20524                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20525                    dumpState.setTitlePrinted(true);
20526                }
20527            }
20528            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20529                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20530                        : "Service Resolver Table:", "  ", packageName,
20531                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20532                    dumpState.setTitlePrinted(true);
20533                }
20534            }
20535            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20536                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20537                        : "Provider Resolver Table:", "  ", packageName,
20538                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20539                    dumpState.setTitlePrinted(true);
20540                }
20541            }
20542
20543            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20544                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20545                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20546                    int user = mSettings.mPreferredActivities.keyAt(i);
20547                    if (pir.dump(pw,
20548                            dumpState.getTitlePrinted()
20549                                ? "\nPreferred Activities User " + user + ":"
20550                                : "Preferred Activities User " + user + ":", "  ",
20551                            packageName, true, false)) {
20552                        dumpState.setTitlePrinted(true);
20553                    }
20554                }
20555            }
20556
20557            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20558                pw.flush();
20559                FileOutputStream fout = new FileOutputStream(fd);
20560                BufferedOutputStream str = new BufferedOutputStream(fout);
20561                XmlSerializer serializer = new FastXmlSerializer();
20562                try {
20563                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20564                    serializer.startDocument(null, true);
20565                    serializer.setFeature(
20566                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20567                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20568                    serializer.endDocument();
20569                    serializer.flush();
20570                } catch (IllegalArgumentException e) {
20571                    pw.println("Failed writing: " + e);
20572                } catch (IllegalStateException e) {
20573                    pw.println("Failed writing: " + e);
20574                } catch (IOException e) {
20575                    pw.println("Failed writing: " + e);
20576                }
20577            }
20578
20579            if (!checkin
20580                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20581                    && packageName == null) {
20582                pw.println();
20583                int count = mSettings.mPackages.size();
20584                if (count == 0) {
20585                    pw.println("No applications!");
20586                    pw.println();
20587                } else {
20588                    final String prefix = "  ";
20589                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20590                    if (allPackageSettings.size() == 0) {
20591                        pw.println("No domain preferred apps!");
20592                        pw.println();
20593                    } else {
20594                        pw.println("App verification status:");
20595                        pw.println();
20596                        count = 0;
20597                        for (PackageSetting ps : allPackageSettings) {
20598                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20599                            if (ivi == null || ivi.getPackageName() == null) continue;
20600                            pw.println(prefix + "Package: " + ivi.getPackageName());
20601                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20602                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20603                            pw.println();
20604                            count++;
20605                        }
20606                        if (count == 0) {
20607                            pw.println(prefix + "No app verification established.");
20608                            pw.println();
20609                        }
20610                        for (int userId : sUserManager.getUserIds()) {
20611                            pw.println("App linkages for user " + userId + ":");
20612                            pw.println();
20613                            count = 0;
20614                            for (PackageSetting ps : allPackageSettings) {
20615                                final long status = ps.getDomainVerificationStatusForUser(userId);
20616                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20617                                        && !DEBUG_DOMAIN_VERIFICATION) {
20618                                    continue;
20619                                }
20620                                pw.println(prefix + "Package: " + ps.name);
20621                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20622                                String statusStr = IntentFilterVerificationInfo.
20623                                        getStatusStringFromValue(status);
20624                                pw.println(prefix + "Status:  " + statusStr);
20625                                pw.println();
20626                                count++;
20627                            }
20628                            if (count == 0) {
20629                                pw.println(prefix + "No configured app linkages.");
20630                                pw.println();
20631                            }
20632                        }
20633                    }
20634                }
20635            }
20636
20637            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20638                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20639                if (packageName == null && permissionNames == null) {
20640                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20641                        if (iperm == 0) {
20642                            if (dumpState.onTitlePrinted())
20643                                pw.println();
20644                            pw.println("AppOp Permissions:");
20645                        }
20646                        pw.print("  AppOp Permission ");
20647                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20648                        pw.println(":");
20649                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20650                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20651                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20652                        }
20653                    }
20654                }
20655            }
20656
20657            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20658                boolean printedSomething = false;
20659                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20660                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20661                        continue;
20662                    }
20663                    if (!printedSomething) {
20664                        if (dumpState.onTitlePrinted())
20665                            pw.println();
20666                        pw.println("Registered ContentProviders:");
20667                        printedSomething = true;
20668                    }
20669                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20670                    pw.print("    "); pw.println(p.toString());
20671                }
20672                printedSomething = false;
20673                for (Map.Entry<String, PackageParser.Provider> entry :
20674                        mProvidersByAuthority.entrySet()) {
20675                    PackageParser.Provider p = entry.getValue();
20676                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20677                        continue;
20678                    }
20679                    if (!printedSomething) {
20680                        if (dumpState.onTitlePrinted())
20681                            pw.println();
20682                        pw.println("ContentProvider Authorities:");
20683                        printedSomething = true;
20684                    }
20685                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20686                    pw.print("    "); pw.println(p.toString());
20687                    if (p.info != null && p.info.applicationInfo != null) {
20688                        final String appInfo = p.info.applicationInfo.toString();
20689                        pw.print("      applicationInfo="); pw.println(appInfo);
20690                    }
20691                }
20692            }
20693
20694            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20695                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20696            }
20697
20698            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20699                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20700            }
20701
20702            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20703                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20704            }
20705
20706            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20707                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20708            }
20709
20710            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20711                // XXX should handle packageName != null by dumping only install data that
20712                // the given package is involved with.
20713                if (dumpState.onTitlePrinted()) pw.println();
20714                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20715            }
20716
20717            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20718                // XXX should handle packageName != null by dumping only install data that
20719                // the given package is involved with.
20720                if (dumpState.onTitlePrinted()) pw.println();
20721
20722                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20723                ipw.println();
20724                ipw.println("Frozen packages:");
20725                ipw.increaseIndent();
20726                if (mFrozenPackages.size() == 0) {
20727                    ipw.println("(none)");
20728                } else {
20729                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20730                        ipw.println(mFrozenPackages.valueAt(i));
20731                    }
20732                }
20733                ipw.decreaseIndent();
20734            }
20735
20736            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20737                if (dumpState.onTitlePrinted()) pw.println();
20738                dumpDexoptStateLPr(pw, packageName);
20739            }
20740
20741            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20742                if (dumpState.onTitlePrinted()) pw.println();
20743                dumpCompilerStatsLPr(pw, packageName);
20744            }
20745
20746            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20747                if (dumpState.onTitlePrinted()) pw.println();
20748                dumpEnabledOverlaysLPr(pw);
20749            }
20750
20751            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20752                if (dumpState.onTitlePrinted()) pw.println();
20753                mSettings.dumpReadMessagesLPr(pw, dumpState);
20754
20755                pw.println();
20756                pw.println("Package warning messages:");
20757                BufferedReader in = null;
20758                String line = null;
20759                try {
20760                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20761                    while ((line = in.readLine()) != null) {
20762                        if (line.contains("ignored: updated version")) continue;
20763                        pw.println(line);
20764                    }
20765                } catch (IOException ignored) {
20766                } finally {
20767                    IoUtils.closeQuietly(in);
20768                }
20769            }
20770
20771            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20772                BufferedReader in = null;
20773                String line = null;
20774                try {
20775                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20776                    while ((line = in.readLine()) != null) {
20777                        if (line.contains("ignored: updated version")) continue;
20778                        pw.print("msg,");
20779                        pw.println(line);
20780                    }
20781                } catch (IOException ignored) {
20782                } finally {
20783                    IoUtils.closeQuietly(in);
20784                }
20785            }
20786        }
20787    }
20788
20789    private void dumpProto(FileDescriptor fd) {
20790        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20791
20792        synchronized (mPackages) {
20793            final long requiredVerifierPackageToken =
20794                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20795            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20796            proto.write(
20797                    PackageServiceDumpProto.PackageShortProto.UID,
20798                    getPackageUid(
20799                            mRequiredVerifierPackage,
20800                            MATCH_DEBUG_TRIAGED_MISSING,
20801                            UserHandle.USER_SYSTEM));
20802            proto.end(requiredVerifierPackageToken);
20803
20804            if (mIntentFilterVerifierComponent != null) {
20805                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20806                final long verifierPackageToken =
20807                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20808                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20809                proto.write(
20810                        PackageServiceDumpProto.PackageShortProto.UID,
20811                        getPackageUid(
20812                                verifierPackageName,
20813                                MATCH_DEBUG_TRIAGED_MISSING,
20814                                UserHandle.USER_SYSTEM));
20815                proto.end(verifierPackageToken);
20816            }
20817
20818            dumpSharedLibrariesProto(proto);
20819            dumpFeaturesProto(proto);
20820            mSettings.dumpPackagesProto(proto);
20821            mSettings.dumpSharedUsersProto(proto);
20822            dumpMessagesProto(proto);
20823        }
20824        proto.flush();
20825    }
20826
20827    private void dumpMessagesProto(ProtoOutputStream proto) {
20828        BufferedReader in = null;
20829        String line = null;
20830        try {
20831            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20832            while ((line = in.readLine()) != null) {
20833                if (line.contains("ignored: updated version")) continue;
20834                proto.write(PackageServiceDumpProto.MESSAGES, line);
20835            }
20836        } catch (IOException ignored) {
20837        } finally {
20838            IoUtils.closeQuietly(in);
20839        }
20840    }
20841
20842    private void dumpFeaturesProto(ProtoOutputStream proto) {
20843        synchronized (mAvailableFeatures) {
20844            final int count = mAvailableFeatures.size();
20845            for (int i = 0; i < count; i++) {
20846                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
20847                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
20848                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
20849                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
20850                proto.end(featureToken);
20851            }
20852        }
20853    }
20854
20855    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20856        final int count = mSharedLibraries.size();
20857        for (int i = 0; i < count; i++) {
20858            final String libName = mSharedLibraries.keyAt(i);
20859            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20860            if (versionedLib == null) {
20861                continue;
20862            }
20863            final int versionCount = versionedLib.size();
20864            for (int j = 0; j < versionCount; j++) {
20865                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20866                final long sharedLibraryToken =
20867                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20868                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20869                final boolean isJar = (libEntry.path != null);
20870                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20871                if (isJar) {
20872                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20873                } else {
20874                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20875                }
20876                proto.end(sharedLibraryToken);
20877            }
20878        }
20879    }
20880
20881    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20882        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20883        ipw.println();
20884        ipw.println("Dexopt state:");
20885        ipw.increaseIndent();
20886        Collection<PackageParser.Package> packages = null;
20887        if (packageName != null) {
20888            PackageParser.Package targetPackage = mPackages.get(packageName);
20889            if (targetPackage != null) {
20890                packages = Collections.singletonList(targetPackage);
20891            } else {
20892                ipw.println("Unable to find package: " + packageName);
20893                return;
20894            }
20895        } else {
20896            packages = mPackages.values();
20897        }
20898
20899        for (PackageParser.Package pkg : packages) {
20900            ipw.println("[" + pkg.packageName + "]");
20901            ipw.increaseIndent();
20902            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20903            ipw.decreaseIndent();
20904        }
20905    }
20906
20907    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20908        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20909        ipw.println();
20910        ipw.println("Compiler stats:");
20911        ipw.increaseIndent();
20912        Collection<PackageParser.Package> packages = null;
20913        if (packageName != null) {
20914            PackageParser.Package targetPackage = mPackages.get(packageName);
20915            if (targetPackage != null) {
20916                packages = Collections.singletonList(targetPackage);
20917            } else {
20918                ipw.println("Unable to find package: " + packageName);
20919                return;
20920            }
20921        } else {
20922            packages = mPackages.values();
20923        }
20924
20925        for (PackageParser.Package pkg : packages) {
20926            ipw.println("[" + pkg.packageName + "]");
20927            ipw.increaseIndent();
20928
20929            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20930            if (stats == null) {
20931                ipw.println("(No recorded stats)");
20932            } else {
20933                stats.dump(ipw);
20934            }
20935            ipw.decreaseIndent();
20936        }
20937    }
20938
20939    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
20940        pw.println("Enabled overlay paths:");
20941        final int N = mEnabledOverlayPaths.size();
20942        for (int i = 0; i < N; i++) {
20943            final int userId = mEnabledOverlayPaths.keyAt(i);
20944            pw.println(String.format("    User %d:", userId));
20945            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
20946                mEnabledOverlayPaths.valueAt(i);
20947            final int M = userSpecificOverlays.size();
20948            for (int j = 0; j < M; j++) {
20949                final String targetPackageName = userSpecificOverlays.keyAt(j);
20950                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
20951                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
20952            }
20953        }
20954    }
20955
20956    private String dumpDomainString(String packageName) {
20957        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20958                .getList();
20959        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20960
20961        ArraySet<String> result = new ArraySet<>();
20962        if (iviList.size() > 0) {
20963            for (IntentFilterVerificationInfo ivi : iviList) {
20964                for (String host : ivi.getDomains()) {
20965                    result.add(host);
20966                }
20967            }
20968        }
20969        if (filters != null && filters.size() > 0) {
20970            for (IntentFilter filter : filters) {
20971                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20972                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20973                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20974                    result.addAll(filter.getHostsList());
20975                }
20976            }
20977        }
20978
20979        StringBuilder sb = new StringBuilder(result.size() * 16);
20980        for (String domain : result) {
20981            if (sb.length() > 0) sb.append(" ");
20982            sb.append(domain);
20983        }
20984        return sb.toString();
20985    }
20986
20987    // ------- apps on sdcard specific code -------
20988    static final boolean DEBUG_SD_INSTALL = false;
20989
20990    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20991
20992    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20993
20994    private boolean mMediaMounted = false;
20995
20996    static String getEncryptKey() {
20997        try {
20998            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20999                    SD_ENCRYPTION_KEYSTORE_NAME);
21000            if (sdEncKey == null) {
21001                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21002                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21003                if (sdEncKey == null) {
21004                    Slog.e(TAG, "Failed to create encryption keys");
21005                    return null;
21006                }
21007            }
21008            return sdEncKey;
21009        } catch (NoSuchAlgorithmException nsae) {
21010            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21011            return null;
21012        } catch (IOException ioe) {
21013            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21014            return null;
21015        }
21016    }
21017
21018    /*
21019     * Update media status on PackageManager.
21020     */
21021    @Override
21022    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21023        int callingUid = Binder.getCallingUid();
21024        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21025            throw new SecurityException("Media status can only be updated by the system");
21026        }
21027        // reader; this apparently protects mMediaMounted, but should probably
21028        // be a different lock in that case.
21029        synchronized (mPackages) {
21030            Log.i(TAG, "Updating external media status from "
21031                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21032                    + (mediaStatus ? "mounted" : "unmounted"));
21033            if (DEBUG_SD_INSTALL)
21034                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21035                        + ", mMediaMounted=" + mMediaMounted);
21036            if (mediaStatus == mMediaMounted) {
21037                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21038                        : 0, -1);
21039                mHandler.sendMessage(msg);
21040                return;
21041            }
21042            mMediaMounted = mediaStatus;
21043        }
21044        // Queue up an async operation since the package installation may take a
21045        // little while.
21046        mHandler.post(new Runnable() {
21047            public void run() {
21048                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21049            }
21050        });
21051    }
21052
21053    /**
21054     * Called by StorageManagerService when the initial ASECs to scan are available.
21055     * Should block until all the ASEC containers are finished being scanned.
21056     */
21057    public void scanAvailableAsecs() {
21058        updateExternalMediaStatusInner(true, false, false);
21059    }
21060
21061    /*
21062     * Collect information of applications on external media, map them against
21063     * existing containers and update information based on current mount status.
21064     * Please note that we always have to report status if reportStatus has been
21065     * set to true especially when unloading packages.
21066     */
21067    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21068            boolean externalStorage) {
21069        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21070        int[] uidArr = EmptyArray.INT;
21071
21072        final String[] list = PackageHelper.getSecureContainerList();
21073        if (ArrayUtils.isEmpty(list)) {
21074            Log.i(TAG, "No secure containers found");
21075        } else {
21076            // Process list of secure containers and categorize them
21077            // as active or stale based on their package internal state.
21078
21079            // reader
21080            synchronized (mPackages) {
21081                for (String cid : list) {
21082                    // Leave stages untouched for now; installer service owns them
21083                    if (PackageInstallerService.isStageName(cid)) continue;
21084
21085                    if (DEBUG_SD_INSTALL)
21086                        Log.i(TAG, "Processing container " + cid);
21087                    String pkgName = getAsecPackageName(cid);
21088                    if (pkgName == null) {
21089                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21090                        continue;
21091                    }
21092                    if (DEBUG_SD_INSTALL)
21093                        Log.i(TAG, "Looking for pkg : " + pkgName);
21094
21095                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21096                    if (ps == null) {
21097                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21098                        continue;
21099                    }
21100
21101                    /*
21102                     * Skip packages that are not external if we're unmounting
21103                     * external storage.
21104                     */
21105                    if (externalStorage && !isMounted && !isExternal(ps)) {
21106                        continue;
21107                    }
21108
21109                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21110                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21111                    // The package status is changed only if the code path
21112                    // matches between settings and the container id.
21113                    if (ps.codePathString != null
21114                            && ps.codePathString.startsWith(args.getCodePath())) {
21115                        if (DEBUG_SD_INSTALL) {
21116                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21117                                    + " at code path: " + ps.codePathString);
21118                        }
21119
21120                        // We do have a valid package installed on sdcard
21121                        processCids.put(args, ps.codePathString);
21122                        final int uid = ps.appId;
21123                        if (uid != -1) {
21124                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21125                        }
21126                    } else {
21127                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21128                                + ps.codePathString);
21129                    }
21130                }
21131            }
21132
21133            Arrays.sort(uidArr);
21134        }
21135
21136        // Process packages with valid entries.
21137        if (isMounted) {
21138            if (DEBUG_SD_INSTALL)
21139                Log.i(TAG, "Loading packages");
21140            loadMediaPackages(processCids, uidArr, externalStorage);
21141            startCleaningPackages();
21142            mInstallerService.onSecureContainersAvailable();
21143        } else {
21144            if (DEBUG_SD_INSTALL)
21145                Log.i(TAG, "Unloading packages");
21146            unloadMediaPackages(processCids, uidArr, reportStatus);
21147        }
21148    }
21149
21150    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21151            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21152        final int size = infos.size();
21153        final String[] packageNames = new String[size];
21154        final int[] packageUids = new int[size];
21155        for (int i = 0; i < size; i++) {
21156            final ApplicationInfo info = infos.get(i);
21157            packageNames[i] = info.packageName;
21158            packageUids[i] = info.uid;
21159        }
21160        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21161                finishedReceiver);
21162    }
21163
21164    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21165            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21166        sendResourcesChangedBroadcast(mediaStatus, replacing,
21167                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21168    }
21169
21170    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21171            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21172        int size = pkgList.length;
21173        if (size > 0) {
21174            // Send broadcasts here
21175            Bundle extras = new Bundle();
21176            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21177            if (uidArr != null) {
21178                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21179            }
21180            if (replacing) {
21181                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21182            }
21183            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21184                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21185            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21186        }
21187    }
21188
21189   /*
21190     * Look at potentially valid container ids from processCids If package
21191     * information doesn't match the one on record or package scanning fails,
21192     * the cid is added to list of removeCids. We currently don't delete stale
21193     * containers.
21194     */
21195    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21196            boolean externalStorage) {
21197        ArrayList<String> pkgList = new ArrayList<String>();
21198        Set<AsecInstallArgs> keys = processCids.keySet();
21199
21200        for (AsecInstallArgs args : keys) {
21201            String codePath = processCids.get(args);
21202            if (DEBUG_SD_INSTALL)
21203                Log.i(TAG, "Loading container : " + args.cid);
21204            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21205            try {
21206                // Make sure there are no container errors first.
21207                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21208                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21209                            + " when installing from sdcard");
21210                    continue;
21211                }
21212                // Check code path here.
21213                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21214                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21215                            + " does not match one in settings " + codePath);
21216                    continue;
21217                }
21218                // Parse package
21219                int parseFlags = mDefParseFlags;
21220                if (args.isExternalAsec()) {
21221                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21222                }
21223                if (args.isFwdLocked()) {
21224                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21225                }
21226
21227                synchronized (mInstallLock) {
21228                    PackageParser.Package pkg = null;
21229                    try {
21230                        // Sadly we don't know the package name yet to freeze it
21231                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21232                                SCAN_IGNORE_FROZEN, 0, null);
21233                    } catch (PackageManagerException e) {
21234                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21235                    }
21236                    // Scan the package
21237                    if (pkg != null) {
21238                        /*
21239                         * TODO why is the lock being held? doPostInstall is
21240                         * called in other places without the lock. This needs
21241                         * to be straightened out.
21242                         */
21243                        // writer
21244                        synchronized (mPackages) {
21245                            retCode = PackageManager.INSTALL_SUCCEEDED;
21246                            pkgList.add(pkg.packageName);
21247                            // Post process args
21248                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21249                                    pkg.applicationInfo.uid);
21250                        }
21251                    } else {
21252                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21253                    }
21254                }
21255
21256            } finally {
21257                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21258                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21259                }
21260            }
21261        }
21262        // writer
21263        synchronized (mPackages) {
21264            // If the platform SDK has changed since the last time we booted,
21265            // we need to re-grant app permission to catch any new ones that
21266            // appear. This is really a hack, and means that apps can in some
21267            // cases get permissions that the user didn't initially explicitly
21268            // allow... it would be nice to have some better way to handle
21269            // this situation.
21270            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21271                    : mSettings.getInternalVersion();
21272            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21273                    : StorageManager.UUID_PRIVATE_INTERNAL;
21274
21275            int updateFlags = UPDATE_PERMISSIONS_ALL;
21276            if (ver.sdkVersion != mSdkVersion) {
21277                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21278                        + mSdkVersion + "; regranting permissions for external");
21279                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21280            }
21281            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21282
21283            // Yay, everything is now upgraded
21284            ver.forceCurrent();
21285
21286            // can downgrade to reader
21287            // Persist settings
21288            mSettings.writeLPr();
21289        }
21290        // Send a broadcast to let everyone know we are done processing
21291        if (pkgList.size() > 0) {
21292            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21293        }
21294    }
21295
21296   /*
21297     * Utility method to unload a list of specified containers
21298     */
21299    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21300        // Just unmount all valid containers.
21301        for (AsecInstallArgs arg : cidArgs) {
21302            synchronized (mInstallLock) {
21303                arg.doPostDeleteLI(false);
21304           }
21305       }
21306   }
21307
21308    /*
21309     * Unload packages mounted on external media. This involves deleting package
21310     * data from internal structures, sending broadcasts about disabled packages,
21311     * gc'ing to free up references, unmounting all secure containers
21312     * corresponding to packages on external media, and posting a
21313     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21314     * that we always have to post this message if status has been requested no
21315     * matter what.
21316     */
21317    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21318            final boolean reportStatus) {
21319        if (DEBUG_SD_INSTALL)
21320            Log.i(TAG, "unloading media packages");
21321        ArrayList<String> pkgList = new ArrayList<String>();
21322        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21323        final Set<AsecInstallArgs> keys = processCids.keySet();
21324        for (AsecInstallArgs args : keys) {
21325            String pkgName = args.getPackageName();
21326            if (DEBUG_SD_INSTALL)
21327                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21328            // Delete package internally
21329            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21330            synchronized (mInstallLock) {
21331                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21332                final boolean res;
21333                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21334                        "unloadMediaPackages")) {
21335                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21336                            null);
21337                }
21338                if (res) {
21339                    pkgList.add(pkgName);
21340                } else {
21341                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21342                    failedList.add(args);
21343                }
21344            }
21345        }
21346
21347        // reader
21348        synchronized (mPackages) {
21349            // We didn't update the settings after removing each package;
21350            // write them now for all packages.
21351            mSettings.writeLPr();
21352        }
21353
21354        // We have to absolutely send UPDATED_MEDIA_STATUS only
21355        // after confirming that all the receivers processed the ordered
21356        // broadcast when packages get disabled, force a gc to clean things up.
21357        // and unload all the containers.
21358        if (pkgList.size() > 0) {
21359            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21360                    new IIntentReceiver.Stub() {
21361                public void performReceive(Intent intent, int resultCode, String data,
21362                        Bundle extras, boolean ordered, boolean sticky,
21363                        int sendingUser) throws RemoteException {
21364                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21365                            reportStatus ? 1 : 0, 1, keys);
21366                    mHandler.sendMessage(msg);
21367                }
21368            });
21369        } else {
21370            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21371                    keys);
21372            mHandler.sendMessage(msg);
21373        }
21374    }
21375
21376    private void loadPrivatePackages(final VolumeInfo vol) {
21377        mHandler.post(new Runnable() {
21378            @Override
21379            public void run() {
21380                loadPrivatePackagesInner(vol);
21381            }
21382        });
21383    }
21384
21385    private void loadPrivatePackagesInner(VolumeInfo vol) {
21386        final String volumeUuid = vol.fsUuid;
21387        if (TextUtils.isEmpty(volumeUuid)) {
21388            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21389            return;
21390        }
21391
21392        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21393        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21394        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21395
21396        final VersionInfo ver;
21397        final List<PackageSetting> packages;
21398        synchronized (mPackages) {
21399            ver = mSettings.findOrCreateVersion(volumeUuid);
21400            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21401        }
21402
21403        for (PackageSetting ps : packages) {
21404            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21405            synchronized (mInstallLock) {
21406                final PackageParser.Package pkg;
21407                try {
21408                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21409                    loaded.add(pkg.applicationInfo);
21410
21411                } catch (PackageManagerException e) {
21412                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21413                }
21414
21415                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21416                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21417                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21418                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21419                }
21420            }
21421        }
21422
21423        // Reconcile app data for all started/unlocked users
21424        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21425        final UserManager um = mContext.getSystemService(UserManager.class);
21426        UserManagerInternal umInternal = getUserManagerInternal();
21427        for (UserInfo user : um.getUsers()) {
21428            final int flags;
21429            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21430                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21431            } else if (umInternal.isUserRunning(user.id)) {
21432                flags = StorageManager.FLAG_STORAGE_DE;
21433            } else {
21434                continue;
21435            }
21436
21437            try {
21438                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21439                synchronized (mInstallLock) {
21440                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21441                }
21442            } catch (IllegalStateException e) {
21443                // Device was probably ejected, and we'll process that event momentarily
21444                Slog.w(TAG, "Failed to prepare storage: " + e);
21445            }
21446        }
21447
21448        synchronized (mPackages) {
21449            int updateFlags = UPDATE_PERMISSIONS_ALL;
21450            if (ver.sdkVersion != mSdkVersion) {
21451                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21452                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21453                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21454            }
21455            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21456
21457            // Yay, everything is now upgraded
21458            ver.forceCurrent();
21459
21460            mSettings.writeLPr();
21461        }
21462
21463        for (PackageFreezer freezer : freezers) {
21464            freezer.close();
21465        }
21466
21467        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21468        sendResourcesChangedBroadcast(true, false, loaded, null);
21469    }
21470
21471    private void unloadPrivatePackages(final VolumeInfo vol) {
21472        mHandler.post(new Runnable() {
21473            @Override
21474            public void run() {
21475                unloadPrivatePackagesInner(vol);
21476            }
21477        });
21478    }
21479
21480    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21481        final String volumeUuid = vol.fsUuid;
21482        if (TextUtils.isEmpty(volumeUuid)) {
21483            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21484            return;
21485        }
21486
21487        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21488        synchronized (mInstallLock) {
21489        synchronized (mPackages) {
21490            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21491            for (PackageSetting ps : packages) {
21492                if (ps.pkg == null) continue;
21493
21494                final ApplicationInfo info = ps.pkg.applicationInfo;
21495                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21496                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21497
21498                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21499                        "unloadPrivatePackagesInner")) {
21500                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21501                            false, null)) {
21502                        unloaded.add(info);
21503                    } else {
21504                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21505                    }
21506                }
21507
21508                // Try very hard to release any references to this package
21509                // so we don't risk the system server being killed due to
21510                // open FDs
21511                AttributeCache.instance().removePackage(ps.name);
21512            }
21513
21514            mSettings.writeLPr();
21515        }
21516        }
21517
21518        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21519        sendResourcesChangedBroadcast(false, false, unloaded, null);
21520
21521        // Try very hard to release any references to this path so we don't risk
21522        // the system server being killed due to open FDs
21523        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21524
21525        for (int i = 0; i < 3; i++) {
21526            System.gc();
21527            System.runFinalization();
21528        }
21529    }
21530
21531    private void assertPackageKnown(String volumeUuid, String packageName)
21532            throws PackageManagerException {
21533        synchronized (mPackages) {
21534            // Normalize package name to handle renamed packages
21535            packageName = normalizePackageNameLPr(packageName);
21536
21537            final PackageSetting ps = mSettings.mPackages.get(packageName);
21538            if (ps == null) {
21539                throw new PackageManagerException("Package " + packageName + " is unknown");
21540            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21541                throw new PackageManagerException(
21542                        "Package " + packageName + " found on unknown volume " + volumeUuid
21543                                + "; expected volume " + ps.volumeUuid);
21544            }
21545        }
21546    }
21547
21548    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21549            throws PackageManagerException {
21550        synchronized (mPackages) {
21551            // Normalize package name to handle renamed packages
21552            packageName = normalizePackageNameLPr(packageName);
21553
21554            final PackageSetting ps = mSettings.mPackages.get(packageName);
21555            if (ps == null) {
21556                throw new PackageManagerException("Package " + packageName + " is unknown");
21557            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21558                throw new PackageManagerException(
21559                        "Package " + packageName + " found on unknown volume " + volumeUuid
21560                                + "; expected volume " + ps.volumeUuid);
21561            } else if (!ps.getInstalled(userId)) {
21562                throw new PackageManagerException(
21563                        "Package " + packageName + " not installed for user " + userId);
21564            }
21565        }
21566    }
21567
21568    private List<String> collectAbsoluteCodePaths() {
21569        synchronized (mPackages) {
21570            List<String> codePaths = new ArrayList<>();
21571            final int packageCount = mSettings.mPackages.size();
21572            for (int i = 0; i < packageCount; i++) {
21573                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21574                codePaths.add(ps.codePath.getAbsolutePath());
21575            }
21576            return codePaths;
21577        }
21578    }
21579
21580    /**
21581     * Examine all apps present on given mounted volume, and destroy apps that
21582     * aren't expected, either due to uninstallation or reinstallation on
21583     * another volume.
21584     */
21585    private void reconcileApps(String volumeUuid) {
21586        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21587        List<File> filesToDelete = null;
21588
21589        final File[] files = FileUtils.listFilesOrEmpty(
21590                Environment.getDataAppDirectory(volumeUuid));
21591        for (File file : files) {
21592            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21593                    && !PackageInstallerService.isStageName(file.getName());
21594            if (!isPackage) {
21595                // Ignore entries which are not packages
21596                continue;
21597            }
21598
21599            String absolutePath = file.getAbsolutePath();
21600
21601            boolean pathValid = false;
21602            final int absoluteCodePathCount = absoluteCodePaths.size();
21603            for (int i = 0; i < absoluteCodePathCount; i++) {
21604                String absoluteCodePath = absoluteCodePaths.get(i);
21605                if (absolutePath.startsWith(absoluteCodePath)) {
21606                    pathValid = true;
21607                    break;
21608                }
21609            }
21610
21611            if (!pathValid) {
21612                if (filesToDelete == null) {
21613                    filesToDelete = new ArrayList<>();
21614                }
21615                filesToDelete.add(file);
21616            }
21617        }
21618
21619        if (filesToDelete != null) {
21620            final int fileToDeleteCount = filesToDelete.size();
21621            for (int i = 0; i < fileToDeleteCount; i++) {
21622                File fileToDelete = filesToDelete.get(i);
21623                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21624                synchronized (mInstallLock) {
21625                    removeCodePathLI(fileToDelete);
21626                }
21627            }
21628        }
21629    }
21630
21631    /**
21632     * Reconcile all app data for the given user.
21633     * <p>
21634     * Verifies that directories exist and that ownership and labeling is
21635     * correct for all installed apps on all mounted volumes.
21636     */
21637    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21638        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21639        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21640            final String volumeUuid = vol.getFsUuid();
21641            synchronized (mInstallLock) {
21642                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21643            }
21644        }
21645    }
21646
21647    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21648            boolean migrateAppData) {
21649        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21650    }
21651
21652    /**
21653     * Reconcile all app data on given mounted volume.
21654     * <p>
21655     * Destroys app data that isn't expected, either due to uninstallation or
21656     * reinstallation on another volume.
21657     * <p>
21658     * Verifies that directories exist and that ownership and labeling is
21659     * correct for all installed apps.
21660     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21661     */
21662    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21663            boolean migrateAppData, boolean onlyCoreApps) {
21664        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21665                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21666        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21667
21668        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21669        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21670
21671        // First look for stale data that doesn't belong, and check if things
21672        // have changed since we did our last restorecon
21673        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21674            if (StorageManager.isFileEncryptedNativeOrEmulated()
21675                    && !StorageManager.isUserKeyUnlocked(userId)) {
21676                throw new RuntimeException(
21677                        "Yikes, someone asked us to reconcile CE storage while " + userId
21678                                + " was still locked; this would have caused massive data loss!");
21679            }
21680
21681            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21682            for (File file : files) {
21683                final String packageName = file.getName();
21684                try {
21685                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21686                } catch (PackageManagerException e) {
21687                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21688                    try {
21689                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21690                                StorageManager.FLAG_STORAGE_CE, 0);
21691                    } catch (InstallerException e2) {
21692                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21693                    }
21694                }
21695            }
21696        }
21697        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21698            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21699            for (File file : files) {
21700                final String packageName = file.getName();
21701                try {
21702                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21703                } catch (PackageManagerException e) {
21704                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21705                    try {
21706                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21707                                StorageManager.FLAG_STORAGE_DE, 0);
21708                    } catch (InstallerException e2) {
21709                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21710                    }
21711                }
21712            }
21713        }
21714
21715        // Ensure that data directories are ready to roll for all packages
21716        // installed for this volume and user
21717        final List<PackageSetting> packages;
21718        synchronized (mPackages) {
21719            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21720        }
21721        int preparedCount = 0;
21722        for (PackageSetting ps : packages) {
21723            final String packageName = ps.name;
21724            if (ps.pkg == null) {
21725                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21726                // TODO: might be due to legacy ASEC apps; we should circle back
21727                // and reconcile again once they're scanned
21728                continue;
21729            }
21730            // Skip non-core apps if requested
21731            if (onlyCoreApps && !ps.pkg.coreApp) {
21732                result.add(packageName);
21733                continue;
21734            }
21735
21736            if (ps.getInstalled(userId)) {
21737                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21738                preparedCount++;
21739            }
21740        }
21741
21742        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21743        return result;
21744    }
21745
21746    /**
21747     * Prepare app data for the given app just after it was installed or
21748     * upgraded. This method carefully only touches users that it's installed
21749     * for, and it forces a restorecon to handle any seinfo changes.
21750     * <p>
21751     * Verifies that directories exist and that ownership and labeling is
21752     * correct for all installed apps. If there is an ownership mismatch, it
21753     * will try recovering system apps by wiping data; third-party app data is
21754     * left intact.
21755     * <p>
21756     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21757     */
21758    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21759        final PackageSetting ps;
21760        synchronized (mPackages) {
21761            ps = mSettings.mPackages.get(pkg.packageName);
21762            mSettings.writeKernelMappingLPr(ps);
21763        }
21764
21765        final UserManager um = mContext.getSystemService(UserManager.class);
21766        UserManagerInternal umInternal = getUserManagerInternal();
21767        for (UserInfo user : um.getUsers()) {
21768            final int flags;
21769            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21770                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21771            } else if (umInternal.isUserRunning(user.id)) {
21772                flags = StorageManager.FLAG_STORAGE_DE;
21773            } else {
21774                continue;
21775            }
21776
21777            if (ps.getInstalled(user.id)) {
21778                // TODO: when user data is locked, mark that we're still dirty
21779                prepareAppDataLIF(pkg, user.id, flags);
21780            }
21781        }
21782    }
21783
21784    /**
21785     * Prepare app data for the given app.
21786     * <p>
21787     * Verifies that directories exist and that ownership and labeling is
21788     * correct for all installed apps. If there is an ownership mismatch, this
21789     * will try recovering system apps by wiping data; third-party app data is
21790     * left intact.
21791     */
21792    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21793        if (pkg == null) {
21794            Slog.wtf(TAG, "Package was null!", new Throwable());
21795            return;
21796        }
21797        prepareAppDataLeafLIF(pkg, userId, flags);
21798        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21799        for (int i = 0; i < childCount; i++) {
21800            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21801        }
21802    }
21803
21804    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21805            boolean maybeMigrateAppData) {
21806        prepareAppDataLIF(pkg, userId, flags);
21807
21808        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21809            // We may have just shuffled around app data directories, so
21810            // prepare them one more time
21811            prepareAppDataLIF(pkg, userId, flags);
21812        }
21813    }
21814
21815    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21816        if (DEBUG_APP_DATA) {
21817            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21818                    + Integer.toHexString(flags));
21819        }
21820
21821        final String volumeUuid = pkg.volumeUuid;
21822        final String packageName = pkg.packageName;
21823        final ApplicationInfo app = pkg.applicationInfo;
21824        final int appId = UserHandle.getAppId(app.uid);
21825
21826        Preconditions.checkNotNull(app.seInfo);
21827
21828        long ceDataInode = -1;
21829        try {
21830            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21831                    appId, app.seInfo, app.targetSdkVersion);
21832        } catch (InstallerException e) {
21833            if (app.isSystemApp()) {
21834                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21835                        + ", but trying to recover: " + e);
21836                destroyAppDataLeafLIF(pkg, userId, flags);
21837                try {
21838                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21839                            appId, app.seInfo, app.targetSdkVersion);
21840                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21841                } catch (InstallerException e2) {
21842                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21843                }
21844            } else {
21845                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21846            }
21847        }
21848
21849        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21850            // TODO: mark this structure as dirty so we persist it!
21851            synchronized (mPackages) {
21852                final PackageSetting ps = mSettings.mPackages.get(packageName);
21853                if (ps != null) {
21854                    ps.setCeDataInode(ceDataInode, userId);
21855                }
21856            }
21857        }
21858
21859        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21860    }
21861
21862    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21863        if (pkg == null) {
21864            Slog.wtf(TAG, "Package was null!", new Throwable());
21865            return;
21866        }
21867        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21868        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21869        for (int i = 0; i < childCount; i++) {
21870            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21871        }
21872    }
21873
21874    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21875        final String volumeUuid = pkg.volumeUuid;
21876        final String packageName = pkg.packageName;
21877        final ApplicationInfo app = pkg.applicationInfo;
21878
21879        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21880            // Create a native library symlink only if we have native libraries
21881            // and if the native libraries are 32 bit libraries. We do not provide
21882            // this symlink for 64 bit libraries.
21883            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21884                final String nativeLibPath = app.nativeLibraryDir;
21885                try {
21886                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21887                            nativeLibPath, userId);
21888                } catch (InstallerException e) {
21889                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21890                }
21891            }
21892        }
21893    }
21894
21895    /**
21896     * For system apps on non-FBE devices, this method migrates any existing
21897     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21898     * requested by the app.
21899     */
21900    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21901        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21902                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21903            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21904                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21905            try {
21906                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21907                        storageTarget);
21908            } catch (InstallerException e) {
21909                logCriticalInfo(Log.WARN,
21910                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21911            }
21912            return true;
21913        } else {
21914            return false;
21915        }
21916    }
21917
21918    public PackageFreezer freezePackage(String packageName, String killReason) {
21919        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21920    }
21921
21922    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21923        return new PackageFreezer(packageName, userId, killReason);
21924    }
21925
21926    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21927            String killReason) {
21928        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21929    }
21930
21931    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21932            String killReason) {
21933        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21934            return new PackageFreezer();
21935        } else {
21936            return freezePackage(packageName, userId, killReason);
21937        }
21938    }
21939
21940    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21941            String killReason) {
21942        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21943    }
21944
21945    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21946            String killReason) {
21947        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21948            return new PackageFreezer();
21949        } else {
21950            return freezePackage(packageName, userId, killReason);
21951        }
21952    }
21953
21954    /**
21955     * Class that freezes and kills the given package upon creation, and
21956     * unfreezes it upon closing. This is typically used when doing surgery on
21957     * app code/data to prevent the app from running while you're working.
21958     */
21959    private class PackageFreezer implements AutoCloseable {
21960        private final String mPackageName;
21961        private final PackageFreezer[] mChildren;
21962
21963        private final boolean mWeFroze;
21964
21965        private final AtomicBoolean mClosed = new AtomicBoolean();
21966        private final CloseGuard mCloseGuard = CloseGuard.get();
21967
21968        /**
21969         * Create and return a stub freezer that doesn't actually do anything,
21970         * typically used when someone requested
21971         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21972         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21973         */
21974        public PackageFreezer() {
21975            mPackageName = null;
21976            mChildren = null;
21977            mWeFroze = false;
21978            mCloseGuard.open("close");
21979        }
21980
21981        public PackageFreezer(String packageName, int userId, String killReason) {
21982            synchronized (mPackages) {
21983                mPackageName = packageName;
21984                mWeFroze = mFrozenPackages.add(mPackageName);
21985
21986                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21987                if (ps != null) {
21988                    killApplication(ps.name, ps.appId, userId, killReason);
21989                }
21990
21991                final PackageParser.Package p = mPackages.get(packageName);
21992                if (p != null && p.childPackages != null) {
21993                    final int N = p.childPackages.size();
21994                    mChildren = new PackageFreezer[N];
21995                    for (int i = 0; i < N; i++) {
21996                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21997                                userId, killReason);
21998                    }
21999                } else {
22000                    mChildren = null;
22001                }
22002            }
22003            mCloseGuard.open("close");
22004        }
22005
22006        @Override
22007        protected void finalize() throws Throwable {
22008            try {
22009                mCloseGuard.warnIfOpen();
22010                close();
22011            } finally {
22012                super.finalize();
22013            }
22014        }
22015
22016        @Override
22017        public void close() {
22018            mCloseGuard.close();
22019            if (mClosed.compareAndSet(false, true)) {
22020                synchronized (mPackages) {
22021                    if (mWeFroze) {
22022                        mFrozenPackages.remove(mPackageName);
22023                    }
22024
22025                    if (mChildren != null) {
22026                        for (PackageFreezer freezer : mChildren) {
22027                            freezer.close();
22028                        }
22029                    }
22030                }
22031            }
22032        }
22033    }
22034
22035    /**
22036     * Verify that given package is currently frozen.
22037     */
22038    private void checkPackageFrozen(String packageName) {
22039        synchronized (mPackages) {
22040            if (!mFrozenPackages.contains(packageName)) {
22041                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22042            }
22043        }
22044    }
22045
22046    @Override
22047    public int movePackage(final String packageName, final String volumeUuid) {
22048        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22049
22050        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22051        final int moveId = mNextMoveId.getAndIncrement();
22052        mHandler.post(new Runnable() {
22053            @Override
22054            public void run() {
22055                try {
22056                    movePackageInternal(packageName, volumeUuid, moveId, user);
22057                } catch (PackageManagerException e) {
22058                    Slog.w(TAG, "Failed to move " + packageName, e);
22059                    mMoveCallbacks.notifyStatusChanged(moveId,
22060                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22061                }
22062            }
22063        });
22064        return moveId;
22065    }
22066
22067    private void movePackageInternal(final String packageName, final String volumeUuid,
22068            final int moveId, UserHandle user) throws PackageManagerException {
22069        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22070        final PackageManager pm = mContext.getPackageManager();
22071
22072        final boolean currentAsec;
22073        final String currentVolumeUuid;
22074        final File codeFile;
22075        final String installerPackageName;
22076        final String packageAbiOverride;
22077        final int appId;
22078        final String seinfo;
22079        final String label;
22080        final int targetSdkVersion;
22081        final PackageFreezer freezer;
22082        final int[] installedUserIds;
22083
22084        // reader
22085        synchronized (mPackages) {
22086            final PackageParser.Package pkg = mPackages.get(packageName);
22087            final PackageSetting ps = mSettings.mPackages.get(packageName);
22088            if (pkg == null || ps == null) {
22089                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22090            }
22091
22092            if (pkg.applicationInfo.isSystemApp()) {
22093                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22094                        "Cannot move system application");
22095            }
22096
22097            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22098            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22099                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22100            if (isInternalStorage && !allow3rdPartyOnInternal) {
22101                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22102                        "3rd party apps are not allowed on internal storage");
22103            }
22104
22105            if (pkg.applicationInfo.isExternalAsec()) {
22106                currentAsec = true;
22107                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22108            } else if (pkg.applicationInfo.isForwardLocked()) {
22109                currentAsec = true;
22110                currentVolumeUuid = "forward_locked";
22111            } else {
22112                currentAsec = false;
22113                currentVolumeUuid = ps.volumeUuid;
22114
22115                final File probe = new File(pkg.codePath);
22116                final File probeOat = new File(probe, "oat");
22117                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22118                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22119                            "Move only supported for modern cluster style installs");
22120                }
22121            }
22122
22123            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22124                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22125                        "Package already moved to " + volumeUuid);
22126            }
22127            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22128                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22129                        "Device admin cannot be moved");
22130            }
22131
22132            if (mFrozenPackages.contains(packageName)) {
22133                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22134                        "Failed to move already frozen package");
22135            }
22136
22137            codeFile = new File(pkg.codePath);
22138            installerPackageName = ps.installerPackageName;
22139            packageAbiOverride = ps.cpuAbiOverrideString;
22140            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22141            seinfo = pkg.applicationInfo.seInfo;
22142            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22143            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22144            freezer = freezePackage(packageName, "movePackageInternal");
22145            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22146        }
22147
22148        final Bundle extras = new Bundle();
22149        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22150        extras.putString(Intent.EXTRA_TITLE, label);
22151        mMoveCallbacks.notifyCreated(moveId, extras);
22152
22153        int installFlags;
22154        final boolean moveCompleteApp;
22155        final File measurePath;
22156
22157        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22158            installFlags = INSTALL_INTERNAL;
22159            moveCompleteApp = !currentAsec;
22160            measurePath = Environment.getDataAppDirectory(volumeUuid);
22161        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22162            installFlags = INSTALL_EXTERNAL;
22163            moveCompleteApp = false;
22164            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22165        } else {
22166            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22167            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22168                    || !volume.isMountedWritable()) {
22169                freezer.close();
22170                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22171                        "Move location not mounted private volume");
22172            }
22173
22174            Preconditions.checkState(!currentAsec);
22175
22176            installFlags = INSTALL_INTERNAL;
22177            moveCompleteApp = true;
22178            measurePath = Environment.getDataAppDirectory(volumeUuid);
22179        }
22180
22181        final PackageStats stats = new PackageStats(null, -1);
22182        synchronized (mInstaller) {
22183            for (int userId : installedUserIds) {
22184                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22185                    freezer.close();
22186                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22187                            "Failed to measure package size");
22188                }
22189            }
22190        }
22191
22192        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22193                + stats.dataSize);
22194
22195        final long startFreeBytes = measurePath.getFreeSpace();
22196        final long sizeBytes;
22197        if (moveCompleteApp) {
22198            sizeBytes = stats.codeSize + stats.dataSize;
22199        } else {
22200            sizeBytes = stats.codeSize;
22201        }
22202
22203        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22204            freezer.close();
22205            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22206                    "Not enough free space to move");
22207        }
22208
22209        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22210
22211        final CountDownLatch installedLatch = new CountDownLatch(1);
22212        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22213            @Override
22214            public void onUserActionRequired(Intent intent) throws RemoteException {
22215                throw new IllegalStateException();
22216            }
22217
22218            @Override
22219            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22220                    Bundle extras) throws RemoteException {
22221                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22222                        + PackageManager.installStatusToString(returnCode, msg));
22223
22224                installedLatch.countDown();
22225                freezer.close();
22226
22227                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22228                switch (status) {
22229                    case PackageInstaller.STATUS_SUCCESS:
22230                        mMoveCallbacks.notifyStatusChanged(moveId,
22231                                PackageManager.MOVE_SUCCEEDED);
22232                        break;
22233                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22234                        mMoveCallbacks.notifyStatusChanged(moveId,
22235                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22236                        break;
22237                    default:
22238                        mMoveCallbacks.notifyStatusChanged(moveId,
22239                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22240                        break;
22241                }
22242            }
22243        };
22244
22245        final MoveInfo move;
22246        if (moveCompleteApp) {
22247            // Kick off a thread to report progress estimates
22248            new Thread() {
22249                @Override
22250                public void run() {
22251                    while (true) {
22252                        try {
22253                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22254                                break;
22255                            }
22256                        } catch (InterruptedException ignored) {
22257                        }
22258
22259                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22260                        final int progress = 10 + (int) MathUtils.constrain(
22261                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22262                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22263                    }
22264                }
22265            }.start();
22266
22267            final String dataAppName = codeFile.getName();
22268            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22269                    dataAppName, appId, seinfo, targetSdkVersion);
22270        } else {
22271            move = null;
22272        }
22273
22274        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22275
22276        final Message msg = mHandler.obtainMessage(INIT_COPY);
22277        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22278        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22279                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22280                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22281                PackageManager.INSTALL_REASON_UNKNOWN);
22282        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22283        msg.obj = params;
22284
22285        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22286                System.identityHashCode(msg.obj));
22287        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22288                System.identityHashCode(msg.obj));
22289
22290        mHandler.sendMessage(msg);
22291    }
22292
22293    @Override
22294    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22295        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22296
22297        final int realMoveId = mNextMoveId.getAndIncrement();
22298        final Bundle extras = new Bundle();
22299        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22300        mMoveCallbacks.notifyCreated(realMoveId, extras);
22301
22302        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22303            @Override
22304            public void onCreated(int moveId, Bundle extras) {
22305                // Ignored
22306            }
22307
22308            @Override
22309            public void onStatusChanged(int moveId, int status, long estMillis) {
22310                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22311            }
22312        };
22313
22314        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22315        storage.setPrimaryStorageUuid(volumeUuid, callback);
22316        return realMoveId;
22317    }
22318
22319    @Override
22320    public int getMoveStatus(int moveId) {
22321        mContext.enforceCallingOrSelfPermission(
22322                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22323        return mMoveCallbacks.mLastStatus.get(moveId);
22324    }
22325
22326    @Override
22327    public void registerMoveCallback(IPackageMoveObserver callback) {
22328        mContext.enforceCallingOrSelfPermission(
22329                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22330        mMoveCallbacks.register(callback);
22331    }
22332
22333    @Override
22334    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22335        mContext.enforceCallingOrSelfPermission(
22336                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22337        mMoveCallbacks.unregister(callback);
22338    }
22339
22340    @Override
22341    public boolean setInstallLocation(int loc) {
22342        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22343                null);
22344        if (getInstallLocation() == loc) {
22345            return true;
22346        }
22347        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22348                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22349            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22350                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22351            return true;
22352        }
22353        return false;
22354   }
22355
22356    @Override
22357    public int getInstallLocation() {
22358        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22359                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22360                PackageHelper.APP_INSTALL_AUTO);
22361    }
22362
22363    /** Called by UserManagerService */
22364    void cleanUpUser(UserManagerService userManager, int userHandle) {
22365        synchronized (mPackages) {
22366            mDirtyUsers.remove(userHandle);
22367            mUserNeedsBadging.delete(userHandle);
22368            mSettings.removeUserLPw(userHandle);
22369            mPendingBroadcasts.remove(userHandle);
22370            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22371            removeUnusedPackagesLPw(userManager, userHandle);
22372        }
22373    }
22374
22375    /**
22376     * We're removing userHandle and would like to remove any downloaded packages
22377     * that are no longer in use by any other user.
22378     * @param userHandle the user being removed
22379     */
22380    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22381        final boolean DEBUG_CLEAN_APKS = false;
22382        int [] users = userManager.getUserIds();
22383        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22384        while (psit.hasNext()) {
22385            PackageSetting ps = psit.next();
22386            if (ps.pkg == null) {
22387                continue;
22388            }
22389            final String packageName = ps.pkg.packageName;
22390            // Skip over if system app
22391            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22392                continue;
22393            }
22394            if (DEBUG_CLEAN_APKS) {
22395                Slog.i(TAG, "Checking package " + packageName);
22396            }
22397            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22398            if (keep) {
22399                if (DEBUG_CLEAN_APKS) {
22400                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22401                }
22402            } else {
22403                for (int i = 0; i < users.length; i++) {
22404                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22405                        keep = true;
22406                        if (DEBUG_CLEAN_APKS) {
22407                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22408                                    + users[i]);
22409                        }
22410                        break;
22411                    }
22412                }
22413            }
22414            if (!keep) {
22415                if (DEBUG_CLEAN_APKS) {
22416                    Slog.i(TAG, "  Removing package " + packageName);
22417                }
22418                mHandler.post(new Runnable() {
22419                    public void run() {
22420                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22421                                userHandle, 0);
22422                    } //end run
22423                });
22424            }
22425        }
22426    }
22427
22428    /** Called by UserManagerService */
22429    void createNewUser(int userId, String[] disallowedPackages) {
22430        synchronized (mInstallLock) {
22431            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22432        }
22433        synchronized (mPackages) {
22434            scheduleWritePackageRestrictionsLocked(userId);
22435            scheduleWritePackageListLocked(userId);
22436            applyFactoryDefaultBrowserLPw(userId);
22437            primeDomainVerificationsLPw(userId);
22438        }
22439    }
22440
22441    void onNewUserCreated(final int userId) {
22442        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22443        // If permission review for legacy apps is required, we represent
22444        // dagerous permissions for such apps as always granted runtime
22445        // permissions to keep per user flag state whether review is needed.
22446        // Hence, if a new user is added we have to propagate dangerous
22447        // permission grants for these legacy apps.
22448        if (mPermissionReviewRequired) {
22449            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22450                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22451        }
22452    }
22453
22454    @Override
22455    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22456        mContext.enforceCallingOrSelfPermission(
22457                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22458                "Only package verification agents can read the verifier device identity");
22459
22460        synchronized (mPackages) {
22461            return mSettings.getVerifierDeviceIdentityLPw();
22462        }
22463    }
22464
22465    @Override
22466    public void setPermissionEnforced(String permission, boolean enforced) {
22467        // TODO: Now that we no longer change GID for storage, this should to away.
22468        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22469                "setPermissionEnforced");
22470        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22471            synchronized (mPackages) {
22472                if (mSettings.mReadExternalStorageEnforced == null
22473                        || mSettings.mReadExternalStorageEnforced != enforced) {
22474                    mSettings.mReadExternalStorageEnforced = enforced;
22475                    mSettings.writeLPr();
22476                }
22477            }
22478            // kill any non-foreground processes so we restart them and
22479            // grant/revoke the GID.
22480            final IActivityManager am = ActivityManager.getService();
22481            if (am != null) {
22482                final long token = Binder.clearCallingIdentity();
22483                try {
22484                    am.killProcessesBelowForeground("setPermissionEnforcement");
22485                } catch (RemoteException e) {
22486                } finally {
22487                    Binder.restoreCallingIdentity(token);
22488                }
22489            }
22490        } else {
22491            throw new IllegalArgumentException("No selective enforcement for " + permission);
22492        }
22493    }
22494
22495    @Override
22496    @Deprecated
22497    public boolean isPermissionEnforced(String permission) {
22498        return true;
22499    }
22500
22501    @Override
22502    public boolean isStorageLow() {
22503        final long token = Binder.clearCallingIdentity();
22504        try {
22505            final DeviceStorageMonitorInternal
22506                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22507            if (dsm != null) {
22508                return dsm.isMemoryLow();
22509            } else {
22510                return false;
22511            }
22512        } finally {
22513            Binder.restoreCallingIdentity(token);
22514        }
22515    }
22516
22517    @Override
22518    public IPackageInstaller getPackageInstaller() {
22519        return mInstallerService;
22520    }
22521
22522    private boolean userNeedsBadging(int userId) {
22523        int index = mUserNeedsBadging.indexOfKey(userId);
22524        if (index < 0) {
22525            final UserInfo userInfo;
22526            final long token = Binder.clearCallingIdentity();
22527            try {
22528                userInfo = sUserManager.getUserInfo(userId);
22529            } finally {
22530                Binder.restoreCallingIdentity(token);
22531            }
22532            final boolean b;
22533            if (userInfo != null && userInfo.isManagedProfile()) {
22534                b = true;
22535            } else {
22536                b = false;
22537            }
22538            mUserNeedsBadging.put(userId, b);
22539            return b;
22540        }
22541        return mUserNeedsBadging.valueAt(index);
22542    }
22543
22544    @Override
22545    public KeySet getKeySetByAlias(String packageName, String alias) {
22546        if (packageName == null || alias == null) {
22547            return null;
22548        }
22549        synchronized(mPackages) {
22550            final PackageParser.Package pkg = mPackages.get(packageName);
22551            if (pkg == null) {
22552                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22553                throw new IllegalArgumentException("Unknown package: " + packageName);
22554            }
22555            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22556            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22557        }
22558    }
22559
22560    @Override
22561    public KeySet getSigningKeySet(String packageName) {
22562        if (packageName == null) {
22563            return null;
22564        }
22565        synchronized(mPackages) {
22566            final PackageParser.Package pkg = mPackages.get(packageName);
22567            if (pkg == null) {
22568                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22569                throw new IllegalArgumentException("Unknown package: " + packageName);
22570            }
22571            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22572                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22573                throw new SecurityException("May not access signing KeySet of other apps.");
22574            }
22575            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22576            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22577        }
22578    }
22579
22580    @Override
22581    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22582        if (packageName == null || ks == null) {
22583            return false;
22584        }
22585        synchronized(mPackages) {
22586            final PackageParser.Package pkg = mPackages.get(packageName);
22587            if (pkg == null) {
22588                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22589                throw new IllegalArgumentException("Unknown package: " + packageName);
22590            }
22591            IBinder ksh = ks.getToken();
22592            if (ksh instanceof KeySetHandle) {
22593                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22594                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22595            }
22596            return false;
22597        }
22598    }
22599
22600    @Override
22601    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22602        if (packageName == null || ks == null) {
22603            return false;
22604        }
22605        synchronized(mPackages) {
22606            final PackageParser.Package pkg = mPackages.get(packageName);
22607            if (pkg == null) {
22608                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22609                throw new IllegalArgumentException("Unknown package: " + packageName);
22610            }
22611            IBinder ksh = ks.getToken();
22612            if (ksh instanceof KeySetHandle) {
22613                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22614                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22615            }
22616            return false;
22617        }
22618    }
22619
22620    private void deletePackageIfUnusedLPr(final String packageName) {
22621        PackageSetting ps = mSettings.mPackages.get(packageName);
22622        if (ps == null) {
22623            return;
22624        }
22625        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22626            // TODO Implement atomic delete if package is unused
22627            // It is currently possible that the package will be deleted even if it is installed
22628            // after this method returns.
22629            mHandler.post(new Runnable() {
22630                public void run() {
22631                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22632                            0, PackageManager.DELETE_ALL_USERS);
22633                }
22634            });
22635        }
22636    }
22637
22638    /**
22639     * Check and throw if the given before/after packages would be considered a
22640     * downgrade.
22641     */
22642    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22643            throws PackageManagerException {
22644        if (after.versionCode < before.mVersionCode) {
22645            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22646                    "Update version code " + after.versionCode + " is older than current "
22647                    + before.mVersionCode);
22648        } else if (after.versionCode == before.mVersionCode) {
22649            if (after.baseRevisionCode < before.baseRevisionCode) {
22650                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22651                        "Update base revision code " + after.baseRevisionCode
22652                        + " is older than current " + before.baseRevisionCode);
22653            }
22654
22655            if (!ArrayUtils.isEmpty(after.splitNames)) {
22656                for (int i = 0; i < after.splitNames.length; i++) {
22657                    final String splitName = after.splitNames[i];
22658                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22659                    if (j != -1) {
22660                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22661                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22662                                    "Update split " + splitName + " revision code "
22663                                    + after.splitRevisionCodes[i] + " is older than current "
22664                                    + before.splitRevisionCodes[j]);
22665                        }
22666                    }
22667                }
22668            }
22669        }
22670    }
22671
22672    private static class MoveCallbacks extends Handler {
22673        private static final int MSG_CREATED = 1;
22674        private static final int MSG_STATUS_CHANGED = 2;
22675
22676        private final RemoteCallbackList<IPackageMoveObserver>
22677                mCallbacks = new RemoteCallbackList<>();
22678
22679        private final SparseIntArray mLastStatus = new SparseIntArray();
22680
22681        public MoveCallbacks(Looper looper) {
22682            super(looper);
22683        }
22684
22685        public void register(IPackageMoveObserver callback) {
22686            mCallbacks.register(callback);
22687        }
22688
22689        public void unregister(IPackageMoveObserver callback) {
22690            mCallbacks.unregister(callback);
22691        }
22692
22693        @Override
22694        public void handleMessage(Message msg) {
22695            final SomeArgs args = (SomeArgs) msg.obj;
22696            final int n = mCallbacks.beginBroadcast();
22697            for (int i = 0; i < n; i++) {
22698                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22699                try {
22700                    invokeCallback(callback, msg.what, args);
22701                } catch (RemoteException ignored) {
22702                }
22703            }
22704            mCallbacks.finishBroadcast();
22705            args.recycle();
22706        }
22707
22708        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22709                throws RemoteException {
22710            switch (what) {
22711                case MSG_CREATED: {
22712                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22713                    break;
22714                }
22715                case MSG_STATUS_CHANGED: {
22716                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22717                    break;
22718                }
22719            }
22720        }
22721
22722        private void notifyCreated(int moveId, Bundle extras) {
22723            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22724
22725            final SomeArgs args = SomeArgs.obtain();
22726            args.argi1 = moveId;
22727            args.arg2 = extras;
22728            obtainMessage(MSG_CREATED, args).sendToTarget();
22729        }
22730
22731        private void notifyStatusChanged(int moveId, int status) {
22732            notifyStatusChanged(moveId, status, -1);
22733        }
22734
22735        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22736            Slog.v(TAG, "Move " + moveId + " status " + status);
22737
22738            final SomeArgs args = SomeArgs.obtain();
22739            args.argi1 = moveId;
22740            args.argi2 = status;
22741            args.arg3 = estMillis;
22742            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22743
22744            synchronized (mLastStatus) {
22745                mLastStatus.put(moveId, status);
22746            }
22747        }
22748    }
22749
22750    private final static class OnPermissionChangeListeners extends Handler {
22751        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22752
22753        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22754                new RemoteCallbackList<>();
22755
22756        public OnPermissionChangeListeners(Looper looper) {
22757            super(looper);
22758        }
22759
22760        @Override
22761        public void handleMessage(Message msg) {
22762            switch (msg.what) {
22763                case MSG_ON_PERMISSIONS_CHANGED: {
22764                    final int uid = msg.arg1;
22765                    handleOnPermissionsChanged(uid);
22766                } break;
22767            }
22768        }
22769
22770        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22771            mPermissionListeners.register(listener);
22772
22773        }
22774
22775        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22776            mPermissionListeners.unregister(listener);
22777        }
22778
22779        public void onPermissionsChanged(int uid) {
22780            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22781                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22782            }
22783        }
22784
22785        private void handleOnPermissionsChanged(int uid) {
22786            final int count = mPermissionListeners.beginBroadcast();
22787            try {
22788                for (int i = 0; i < count; i++) {
22789                    IOnPermissionsChangeListener callback = mPermissionListeners
22790                            .getBroadcastItem(i);
22791                    try {
22792                        callback.onPermissionsChanged(uid);
22793                    } catch (RemoteException e) {
22794                        Log.e(TAG, "Permission listener is dead", e);
22795                    }
22796                }
22797            } finally {
22798                mPermissionListeners.finishBroadcast();
22799            }
22800        }
22801    }
22802
22803    private class PackageManagerInternalImpl extends PackageManagerInternal {
22804        @Override
22805        public void setLocationPackagesProvider(PackagesProvider provider) {
22806            synchronized (mPackages) {
22807                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22808            }
22809        }
22810
22811        @Override
22812        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22813            synchronized (mPackages) {
22814                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22815            }
22816        }
22817
22818        @Override
22819        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22820            synchronized (mPackages) {
22821                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22822            }
22823        }
22824
22825        @Override
22826        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22827            synchronized (mPackages) {
22828                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22829            }
22830        }
22831
22832        @Override
22833        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22834            synchronized (mPackages) {
22835                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22836            }
22837        }
22838
22839        @Override
22840        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22841            synchronized (mPackages) {
22842                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22843            }
22844        }
22845
22846        @Override
22847        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22848            synchronized (mPackages) {
22849                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22850                        packageName, userId);
22851            }
22852        }
22853
22854        @Override
22855        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22856            synchronized (mPackages) {
22857                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22858                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22859                        packageName, userId);
22860            }
22861        }
22862
22863        @Override
22864        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22865            synchronized (mPackages) {
22866                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22867                        packageName, userId);
22868            }
22869        }
22870
22871        @Override
22872        public void setKeepUninstalledPackages(final List<String> packageList) {
22873            Preconditions.checkNotNull(packageList);
22874            List<String> removedFromList = null;
22875            synchronized (mPackages) {
22876                if (mKeepUninstalledPackages != null) {
22877                    final int packagesCount = mKeepUninstalledPackages.size();
22878                    for (int i = 0; i < packagesCount; i++) {
22879                        String oldPackage = mKeepUninstalledPackages.get(i);
22880                        if (packageList != null && packageList.contains(oldPackage)) {
22881                            continue;
22882                        }
22883                        if (removedFromList == null) {
22884                            removedFromList = new ArrayList<>();
22885                        }
22886                        removedFromList.add(oldPackage);
22887                    }
22888                }
22889                mKeepUninstalledPackages = new ArrayList<>(packageList);
22890                if (removedFromList != null) {
22891                    final int removedCount = removedFromList.size();
22892                    for (int i = 0; i < removedCount; i++) {
22893                        deletePackageIfUnusedLPr(removedFromList.get(i));
22894                    }
22895                }
22896            }
22897        }
22898
22899        @Override
22900        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22901            synchronized (mPackages) {
22902                // If we do not support permission review, done.
22903                if (!mPermissionReviewRequired) {
22904                    return false;
22905                }
22906
22907                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22908                if (packageSetting == null) {
22909                    return false;
22910                }
22911
22912                // Permission review applies only to apps not supporting the new permission model.
22913                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22914                    return false;
22915                }
22916
22917                // Legacy apps have the permission and get user consent on launch.
22918                PermissionsState permissionsState = packageSetting.getPermissionsState();
22919                return permissionsState.isPermissionReviewRequired(userId);
22920            }
22921        }
22922
22923        @Override
22924        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22925            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22926        }
22927
22928        @Override
22929        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22930                int userId) {
22931            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22932        }
22933
22934        @Override
22935        public void setDeviceAndProfileOwnerPackages(
22936                int deviceOwnerUserId, String deviceOwnerPackage,
22937                SparseArray<String> profileOwnerPackages) {
22938            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22939                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22940        }
22941
22942        @Override
22943        public boolean isPackageDataProtected(int userId, String packageName) {
22944            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22945        }
22946
22947        @Override
22948        public boolean isPackageEphemeral(int userId, String packageName) {
22949            synchronized (mPackages) {
22950                final PackageSetting ps = mSettings.mPackages.get(packageName);
22951                return ps != null ? ps.getInstantApp(userId) : false;
22952            }
22953        }
22954
22955        @Override
22956        public boolean wasPackageEverLaunched(String packageName, int userId) {
22957            synchronized (mPackages) {
22958                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22959            }
22960        }
22961
22962        @Override
22963        public void grantRuntimePermission(String packageName, String name, int userId,
22964                boolean overridePolicy) {
22965            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22966                    overridePolicy);
22967        }
22968
22969        @Override
22970        public void revokeRuntimePermission(String packageName, String name, int userId,
22971                boolean overridePolicy) {
22972            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22973                    overridePolicy);
22974        }
22975
22976        @Override
22977        public String getNameForUid(int uid) {
22978            return PackageManagerService.this.getNameForUid(uid);
22979        }
22980
22981        @Override
22982        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
22983                Intent origIntent, String resolvedType, String callingPackage, int userId) {
22984            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
22985                    responseObj, origIntent, resolvedType, callingPackage, userId);
22986        }
22987
22988        @Override
22989        public void grantEphemeralAccess(int userId, Intent intent,
22990                int targetAppId, int ephemeralAppId) {
22991            synchronized (mPackages) {
22992                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22993                        targetAppId, ephemeralAppId);
22994            }
22995        }
22996
22997        @Override
22998        public void pruneInstantApps() {
22999            synchronized (mPackages) {
23000                mInstantAppRegistry.pruneInstantAppsLPw();
23001            }
23002        }
23003
23004        @Override
23005        public String getSetupWizardPackageName() {
23006            return mSetupWizardPackage;
23007        }
23008
23009        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23010            if (policy != null) {
23011                mExternalSourcesPolicy = policy;
23012            }
23013        }
23014
23015        @Override
23016        public boolean isPackagePersistent(String packageName) {
23017            synchronized (mPackages) {
23018                PackageParser.Package pkg = mPackages.get(packageName);
23019                return pkg != null
23020                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23021                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23022                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23023                        : false;
23024            }
23025        }
23026
23027        @Override
23028        public List<PackageInfo> getOverlayPackages(int userId) {
23029            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23030            synchronized (mPackages) {
23031                for (PackageParser.Package p : mPackages.values()) {
23032                    if (p.mOverlayTarget != null) {
23033                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23034                        if (pkg != null) {
23035                            overlayPackages.add(pkg);
23036                        }
23037                    }
23038                }
23039            }
23040            return overlayPackages;
23041        }
23042
23043        @Override
23044        public List<String> getTargetPackageNames(int userId) {
23045            List<String> targetPackages = new ArrayList<>();
23046            synchronized (mPackages) {
23047                for (PackageParser.Package p : mPackages.values()) {
23048                    if (p.mOverlayTarget == null) {
23049                        targetPackages.add(p.packageName);
23050                    }
23051                }
23052            }
23053            return targetPackages;
23054        }
23055
23056        @Override
23057        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23058                @Nullable List<String> overlayPackageNames) {
23059            synchronized (mPackages) {
23060                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23061                    Slog.e(TAG, "failed to find package " + targetPackageName);
23062                    return false;
23063                }
23064
23065                ArrayList<String> paths = null;
23066                if (overlayPackageNames != null) {
23067                    final int N = overlayPackageNames.size();
23068                    paths = new ArrayList<>(N);
23069                    for (int i = 0; i < N; i++) {
23070                        final String packageName = overlayPackageNames.get(i);
23071                        final PackageParser.Package pkg = mPackages.get(packageName);
23072                        if (pkg == null) {
23073                            Slog.e(TAG, "failed to find package " + packageName);
23074                            return false;
23075                        }
23076                        paths.add(pkg.baseCodePath);
23077                    }
23078                }
23079
23080                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23081                    mEnabledOverlayPaths.get(userId);
23082                if (userSpecificOverlays == null) {
23083                    userSpecificOverlays = new ArrayMap<>();
23084                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23085                }
23086
23087                if (paths != null && paths.size() > 0) {
23088                    userSpecificOverlays.put(targetPackageName, paths);
23089                } else {
23090                    userSpecificOverlays.remove(targetPackageName);
23091                }
23092                return true;
23093            }
23094        }
23095
23096        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23097                int flags, int userId) {
23098            return resolveIntentInternal(
23099                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23100        }
23101    }
23102
23103    @Override
23104    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23105        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23106        synchronized (mPackages) {
23107            final long identity = Binder.clearCallingIdentity();
23108            try {
23109                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23110                        packageNames, userId);
23111            } finally {
23112                Binder.restoreCallingIdentity(identity);
23113            }
23114        }
23115    }
23116
23117    @Override
23118    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23119        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23120        synchronized (mPackages) {
23121            final long identity = Binder.clearCallingIdentity();
23122            try {
23123                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23124                        packageNames, userId);
23125            } finally {
23126                Binder.restoreCallingIdentity(identity);
23127            }
23128        }
23129    }
23130
23131    private static void enforceSystemOrPhoneCaller(String tag) {
23132        int callingUid = Binder.getCallingUid();
23133        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23134            throw new SecurityException(
23135                    "Cannot call " + tag + " from UID " + callingUid);
23136        }
23137    }
23138
23139    boolean isHistoricalPackageUsageAvailable() {
23140        return mPackageUsage.isHistoricalPackageUsageAvailable();
23141    }
23142
23143    /**
23144     * Return a <b>copy</b> of the collection of packages known to the package manager.
23145     * @return A copy of the values of mPackages.
23146     */
23147    Collection<PackageParser.Package> getPackages() {
23148        synchronized (mPackages) {
23149            return new ArrayList<>(mPackages.values());
23150        }
23151    }
23152
23153    /**
23154     * Logs process start information (including base APK hash) to the security log.
23155     * @hide
23156     */
23157    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23158            String apkFile, int pid) {
23159        if (!SecurityLog.isLoggingEnabled()) {
23160            return;
23161        }
23162        Bundle data = new Bundle();
23163        data.putLong("startTimestamp", System.currentTimeMillis());
23164        data.putString("processName", processName);
23165        data.putInt("uid", uid);
23166        data.putString("seinfo", seinfo);
23167        data.putString("apkFile", apkFile);
23168        data.putInt("pid", pid);
23169        Message msg = mProcessLoggingHandler.obtainMessage(
23170                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23171        msg.setData(data);
23172        mProcessLoggingHandler.sendMessage(msg);
23173    }
23174
23175    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23176        return mCompilerStats.getPackageStats(pkgName);
23177    }
23178
23179    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23180        return getOrCreateCompilerPackageStats(pkg.packageName);
23181    }
23182
23183    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23184        return mCompilerStats.getOrCreatePackageStats(pkgName);
23185    }
23186
23187    public void deleteCompilerPackageStats(String pkgName) {
23188        mCompilerStats.deletePackageStats(pkgName);
23189    }
23190
23191    @Override
23192    public int getInstallReason(String packageName, int userId) {
23193        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23194                true /* requireFullPermission */, false /* checkShell */,
23195                "get install reason");
23196        synchronized (mPackages) {
23197            final PackageSetting ps = mSettings.mPackages.get(packageName);
23198            if (ps != null) {
23199                return ps.getInstallReason(userId);
23200            }
23201        }
23202        return PackageManager.INSTALL_REASON_UNKNOWN;
23203    }
23204
23205    @Override
23206    public boolean canRequestPackageInstalls(String packageName, int userId) {
23207        int callingUid = Binder.getCallingUid();
23208        int uid = getPackageUid(packageName, 0, userId);
23209        if (callingUid != uid && callingUid != Process.ROOT_UID
23210                && callingUid != Process.SYSTEM_UID) {
23211            throw new SecurityException(
23212                    "Caller uid " + callingUid + " does not own package " + packageName);
23213        }
23214        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23215        if (info == null) {
23216            return false;
23217        }
23218        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23219            throw new UnsupportedOperationException(
23220                    "Operation only supported on apps targeting Android O or higher");
23221        }
23222        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23223        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23224        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23225            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23226        }
23227        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23228            return false;
23229        }
23230        if (mExternalSourcesPolicy != null) {
23231            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23232            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23233                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23234            }
23235        }
23236        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23237    }
23238}
23239