PackageManagerService.java revision 06ca1e08739fb2df62327293a6222f541639642d
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    public static final int REASON_CORE_APP = 8;
544
545    public static final int REASON_LAST = REASON_CORE_APP;
546
547    /** All dangerous permission names in the same order as the events in MetricsEvent */
548    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
549            Manifest.permission.READ_CALENDAR,
550            Manifest.permission.WRITE_CALENDAR,
551            Manifest.permission.CAMERA,
552            Manifest.permission.READ_CONTACTS,
553            Manifest.permission.WRITE_CONTACTS,
554            Manifest.permission.GET_ACCOUNTS,
555            Manifest.permission.ACCESS_FINE_LOCATION,
556            Manifest.permission.ACCESS_COARSE_LOCATION,
557            Manifest.permission.RECORD_AUDIO,
558            Manifest.permission.READ_PHONE_STATE,
559            Manifest.permission.CALL_PHONE,
560            Manifest.permission.READ_CALL_LOG,
561            Manifest.permission.WRITE_CALL_LOG,
562            Manifest.permission.ADD_VOICEMAIL,
563            Manifest.permission.USE_SIP,
564            Manifest.permission.PROCESS_OUTGOING_CALLS,
565            Manifest.permission.READ_CELL_BROADCASTS,
566            Manifest.permission.BODY_SENSORS,
567            Manifest.permission.SEND_SMS,
568            Manifest.permission.RECEIVE_SMS,
569            Manifest.permission.READ_SMS,
570            Manifest.permission.RECEIVE_WAP_PUSH,
571            Manifest.permission.RECEIVE_MMS,
572            Manifest.permission.READ_EXTERNAL_STORAGE,
573            Manifest.permission.WRITE_EXTERNAL_STORAGE,
574            Manifest.permission.READ_PHONE_NUMBER,
575            Manifest.permission.ANSWER_PHONE_CALLS);
576
577
578    /**
579     * Version number for the package parser cache. Increment this whenever the format or
580     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
581     */
582    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
583
584    /**
585     * Whether the package parser cache is enabled.
586     */
587    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
588
589    final ServiceThread mHandlerThread;
590
591    final PackageHandler mHandler;
592
593    private final ProcessLoggingHandler mProcessLoggingHandler;
594
595    /**
596     * Messages for {@link #mHandler} that need to wait for system ready before
597     * being dispatched.
598     */
599    private ArrayList<Message> mPostSystemReadyMessages;
600
601    final int mSdkVersion = Build.VERSION.SDK_INT;
602
603    final Context mContext;
604    final boolean mFactoryTest;
605    final boolean mOnlyCore;
606    final DisplayMetrics mMetrics;
607    final int mDefParseFlags;
608    final String[] mSeparateProcesses;
609    final boolean mIsUpgrade;
610    final boolean mIsPreNUpgrade;
611    final boolean mIsPreNMR1Upgrade;
612
613    @GuardedBy("mPackages")
614    private boolean mDexOptDialogShown;
615
616    /** The location for ASEC container files on internal storage. */
617    final String mAsecInternalPath;
618
619    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
620    // LOCK HELD.  Can be called with mInstallLock held.
621    @GuardedBy("mInstallLock")
622    final Installer mInstaller;
623
624    /** Directory where installed third-party apps stored */
625    final File mAppInstallDir;
626
627    /**
628     * Directory to which applications installed internally have their
629     * 32 bit native libraries copied.
630     */
631    private File mAppLib32InstallDir;
632
633    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
634    // apps.
635    final File mDrmAppPrivateInstallDir;
636
637    // ----------------------------------------------------------------
638
639    // Lock for state used when installing and doing other long running
640    // operations.  Methods that must be called with this lock held have
641    // the suffix "LI".
642    final Object mInstallLock = new Object();
643
644    // ----------------------------------------------------------------
645
646    // Keys are String (package name), values are Package.  This also serves
647    // as the lock for the global state.  Methods that must be called with
648    // this lock held have the prefix "LP".
649    @GuardedBy("mPackages")
650    final ArrayMap<String, PackageParser.Package> mPackages =
651            new ArrayMap<String, PackageParser.Package>();
652
653    final ArrayMap<String, Set<String>> mKnownCodebase =
654            new ArrayMap<String, Set<String>>();
655
656    // List of APK paths to load for each user and package. This data is never
657    // persisted by the package manager. Instead, the overlay manager will
658    // ensure the data is up-to-date in runtime.
659    @GuardedBy("mPackages")
660    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
661        new SparseArray<ArrayMap<String, ArrayList<String>>>();
662
663    /**
664     * Tracks new system packages [received in an OTA] that we expect to
665     * find updated user-installed versions. Keys are package name, values
666     * are package location.
667     */
668    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
669    /**
670     * Tracks high priority intent filters for protected actions. During boot, certain
671     * filter actions are protected and should never be allowed to have a high priority
672     * intent filter for them. However, there is one, and only one exception -- the
673     * setup wizard. It must be able to define a high priority intent filter for these
674     * actions to ensure there are no escapes from the wizard. We need to delay processing
675     * of these during boot as we need to look at all of the system packages in order
676     * to know which component is the setup wizard.
677     */
678    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
679    /**
680     * Whether or not processing protected filters should be deferred.
681     */
682    private boolean mDeferProtectedFilters = true;
683
684    /**
685     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
686     */
687    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
688    /**
689     * Whether or not system app permissions should be promoted from install to runtime.
690     */
691    boolean mPromoteSystemApps;
692
693    @GuardedBy("mPackages")
694    final Settings mSettings;
695
696    /**
697     * Set of package names that are currently "frozen", which means active
698     * surgery is being done on the code/data for that package. The platform
699     * will refuse to launch frozen packages to avoid race conditions.
700     *
701     * @see PackageFreezer
702     */
703    @GuardedBy("mPackages")
704    final ArraySet<String> mFrozenPackages = new ArraySet<>();
705
706    final ProtectedPackages mProtectedPackages;
707
708    boolean mFirstBoot;
709
710    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
711
712    // System configuration read by SystemConfig.
713    final int[] mGlobalGids;
714    final SparseArray<ArraySet<String>> mSystemPermissions;
715    @GuardedBy("mAvailableFeatures")
716    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
717
718    // If mac_permissions.xml was found for seinfo labeling.
719    boolean mFoundPolicyFile;
720
721    private final InstantAppRegistry mInstantAppRegistry;
722
723    @GuardedBy("mPackages")
724    int mChangedPackagesSequenceNumber;
725    /**
726     * List of changed [installed, removed or updated] packages.
727     * mapping from user id -> sequence number -> package name
728     */
729    @GuardedBy("mPackages")
730    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
731    /**
732     * The sequence number of the last change to a package.
733     * mapping from user id -> package name -> sequence number
734     */
735    @GuardedBy("mPackages")
736    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
737
738    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
739        @Override public boolean hasFeature(String feature) {
740            return PackageManagerService.this.hasSystemFeature(feature, 0);
741        }
742    };
743
744    public static final class SharedLibraryEntry {
745        public final String path;
746        public final String apk;
747        public final SharedLibraryInfo info;
748
749        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
750                String declaringPackageName, int declaringPackageVersionCode) {
751            path = _path;
752            apk = _apk;
753            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
754                    declaringPackageName, declaringPackageVersionCode), null);
755        }
756    }
757
758    // Currently known shared libraries.
759    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
760    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
761            new ArrayMap<>();
762
763    // All available activities, for your resolving pleasure.
764    final ActivityIntentResolver mActivities =
765            new ActivityIntentResolver();
766
767    // All available receivers, for your resolving pleasure.
768    final ActivityIntentResolver mReceivers =
769            new ActivityIntentResolver();
770
771    // All available services, for your resolving pleasure.
772    final ServiceIntentResolver mServices = new ServiceIntentResolver();
773
774    // All available providers, for your resolving pleasure.
775    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
776
777    // Mapping from provider base names (first directory in content URI codePath)
778    // to the provider information.
779    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
780            new ArrayMap<String, PackageParser.Provider>();
781
782    // Mapping from instrumentation class names to info about them.
783    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
784            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
785
786    // Mapping from permission names to info about them.
787    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
788            new ArrayMap<String, PackageParser.PermissionGroup>();
789
790    // Packages whose data we have transfered into another package, thus
791    // should no longer exist.
792    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
793
794    // Broadcast actions that are only available to the system.
795    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
796
797    /** List of packages waiting for verification. */
798    final SparseArray<PackageVerificationState> mPendingVerification
799            = new SparseArray<PackageVerificationState>();
800
801    /** Set of packages associated with each app op permission. */
802    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
803
804    final PackageInstallerService mInstallerService;
805
806    private final PackageDexOptimizer mPackageDexOptimizer;
807    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
808    // is used by other apps).
809    private final DexManager mDexManager;
810
811    private AtomicInteger mNextMoveId = new AtomicInteger();
812    private final MoveCallbacks mMoveCallbacks;
813
814    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
815
816    // Cache of users who need badging.
817    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
818
819    /** Token for keys in mPendingVerification. */
820    private int mPendingVerificationToken = 0;
821
822    volatile boolean mSystemReady;
823    volatile boolean mSafeMode;
824    volatile boolean mHasSystemUidErrors;
825
826    ApplicationInfo mAndroidApplication;
827    final ActivityInfo mResolveActivity = new ActivityInfo();
828    final ResolveInfo mResolveInfo = new ResolveInfo();
829    ComponentName mResolveComponentName;
830    PackageParser.Package mPlatformPackage;
831    ComponentName mCustomResolverComponentName;
832
833    boolean mResolverReplaced = false;
834
835    private final @Nullable ComponentName mIntentFilterVerifierComponent;
836    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
837
838    private int mIntentFilterVerificationToken = 0;
839
840    /** The service connection to the ephemeral resolver */
841    final EphemeralResolverConnection mInstantAppResolverConnection;
842
843    /** Component used to install ephemeral applications */
844    ComponentName mInstantAppInstallerComponent;
845    final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo();
846    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
847
848    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
849            = new SparseArray<IntentFilterVerificationState>();
850
851    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
852
853    // List of packages names to keep cached, even if they are uninstalled for all users
854    private List<String> mKeepUninstalledPackages;
855
856    private UserManagerInternal mUserManagerInternal;
857
858    private DeviceIdleController.LocalService mDeviceIdleController;
859
860    private File mCacheDir;
861
862    private ArraySet<String> mPrivappPermissionsViolations;
863
864    private Future<?> mPrepareAppDataFuture;
865
866    private static class IFVerificationParams {
867        PackageParser.Package pkg;
868        boolean replacing;
869        int userId;
870        int verifierUid;
871
872        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
873                int _userId, int _verifierUid) {
874            pkg = _pkg;
875            replacing = _replacing;
876            userId = _userId;
877            replacing = _replacing;
878            verifierUid = _verifierUid;
879        }
880    }
881
882    private interface IntentFilterVerifier<T extends IntentFilter> {
883        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
884                                               T filter, String packageName);
885        void startVerifications(int userId);
886        void receiveVerificationResponse(int verificationId);
887    }
888
889    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
890        private Context mContext;
891        private ComponentName mIntentFilterVerifierComponent;
892        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
893
894        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
895            mContext = context;
896            mIntentFilterVerifierComponent = verifierComponent;
897        }
898
899        private String getDefaultScheme() {
900            return IntentFilter.SCHEME_HTTPS;
901        }
902
903        @Override
904        public void startVerifications(int userId) {
905            // Launch verifications requests
906            int count = mCurrentIntentFilterVerifications.size();
907            for (int n=0; n<count; n++) {
908                int verificationId = mCurrentIntentFilterVerifications.get(n);
909                final IntentFilterVerificationState ivs =
910                        mIntentFilterVerificationStates.get(verificationId);
911
912                String packageName = ivs.getPackageName();
913
914                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
915                final int filterCount = filters.size();
916                ArraySet<String> domainsSet = new ArraySet<>();
917                for (int m=0; m<filterCount; m++) {
918                    PackageParser.ActivityIntentInfo filter = filters.get(m);
919                    domainsSet.addAll(filter.getHostsList());
920                }
921                synchronized (mPackages) {
922                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
923                            packageName, domainsSet) != null) {
924                        scheduleWriteSettingsLocked();
925                    }
926                }
927                sendVerificationRequest(userId, verificationId, ivs);
928            }
929            mCurrentIntentFilterVerifications.clear();
930        }
931
932        private void sendVerificationRequest(int userId, int verificationId,
933                IntentFilterVerificationState ivs) {
934
935            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
936            verificationIntent.putExtra(
937                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
938                    verificationId);
939            verificationIntent.putExtra(
940                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
941                    getDefaultScheme());
942            verificationIntent.putExtra(
943                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
944                    ivs.getHostsString());
945            verificationIntent.putExtra(
946                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
947                    ivs.getPackageName());
948            verificationIntent.setComponent(mIntentFilterVerifierComponent);
949            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
950
951            UserHandle user = new UserHandle(userId);
952            mContext.sendBroadcastAsUser(verificationIntent, user);
953            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
954                    "Sending IntentFilter verification broadcast");
955        }
956
957        public void receiveVerificationResponse(int verificationId) {
958            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
959
960            final boolean verified = ivs.isVerified();
961
962            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
963            final int count = filters.size();
964            if (DEBUG_DOMAIN_VERIFICATION) {
965                Slog.i(TAG, "Received verification response " + verificationId
966                        + " for " + count + " filters, verified=" + verified);
967            }
968            for (int n=0; n<count; n++) {
969                PackageParser.ActivityIntentInfo filter = filters.get(n);
970                filter.setVerified(verified);
971
972                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
973                        + " verified with result:" + verified + " and hosts:"
974                        + ivs.getHostsString());
975            }
976
977            mIntentFilterVerificationStates.remove(verificationId);
978
979            final String packageName = ivs.getPackageName();
980            IntentFilterVerificationInfo ivi = null;
981
982            synchronized (mPackages) {
983                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
984            }
985            if (ivi == null) {
986                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
987                        + verificationId + " packageName:" + packageName);
988                return;
989            }
990            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
991                    "Updating IntentFilterVerificationInfo for package " + packageName
992                            +" verificationId:" + verificationId);
993
994            synchronized (mPackages) {
995                if (verified) {
996                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
997                } else {
998                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
999                }
1000                scheduleWriteSettingsLocked();
1001
1002                final int userId = ivs.getUserId();
1003                if (userId != UserHandle.USER_ALL) {
1004                    final int userStatus =
1005                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1006
1007                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1008                    boolean needUpdate = false;
1009
1010                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1011                    // already been set by the User thru the Disambiguation dialog
1012                    switch (userStatus) {
1013                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1014                            if (verified) {
1015                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1016                            } else {
1017                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1018                            }
1019                            needUpdate = true;
1020                            break;
1021
1022                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1023                            if (verified) {
1024                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1025                                needUpdate = true;
1026                            }
1027                            break;
1028
1029                        default:
1030                            // Nothing to do
1031                    }
1032
1033                    if (needUpdate) {
1034                        mSettings.updateIntentFilterVerificationStatusLPw(
1035                                packageName, updatedStatus, userId);
1036                        scheduleWritePackageRestrictionsLocked(userId);
1037                    }
1038                }
1039            }
1040        }
1041
1042        @Override
1043        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1044                    ActivityIntentInfo filter, String packageName) {
1045            if (!hasValidDomains(filter)) {
1046                return false;
1047            }
1048            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1049            if (ivs == null) {
1050                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1051                        packageName);
1052            }
1053            if (DEBUG_DOMAIN_VERIFICATION) {
1054                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1055            }
1056            ivs.addFilter(filter);
1057            return true;
1058        }
1059
1060        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1061                int userId, int verificationId, String packageName) {
1062            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1063                    verifierUid, userId, packageName);
1064            ivs.setPendingState();
1065            synchronized (mPackages) {
1066                mIntentFilterVerificationStates.append(verificationId, ivs);
1067                mCurrentIntentFilterVerifications.add(verificationId);
1068            }
1069            return ivs;
1070        }
1071    }
1072
1073    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1074        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1075                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1076                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1077    }
1078
1079    // Set of pending broadcasts for aggregating enable/disable of components.
1080    static class PendingPackageBroadcasts {
1081        // for each user id, a map of <package name -> components within that package>
1082        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1083
1084        public PendingPackageBroadcasts() {
1085            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1086        }
1087
1088        public ArrayList<String> get(int userId, String packageName) {
1089            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1090            return packages.get(packageName);
1091        }
1092
1093        public void put(int userId, String packageName, ArrayList<String> components) {
1094            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1095            packages.put(packageName, components);
1096        }
1097
1098        public void remove(int userId, String packageName) {
1099            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1100            if (packages != null) {
1101                packages.remove(packageName);
1102            }
1103        }
1104
1105        public void remove(int userId) {
1106            mUidMap.remove(userId);
1107        }
1108
1109        public int userIdCount() {
1110            return mUidMap.size();
1111        }
1112
1113        public int userIdAt(int n) {
1114            return mUidMap.keyAt(n);
1115        }
1116
1117        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1118            return mUidMap.get(userId);
1119        }
1120
1121        public int size() {
1122            // total number of pending broadcast entries across all userIds
1123            int num = 0;
1124            for (int i = 0; i< mUidMap.size(); i++) {
1125                num += mUidMap.valueAt(i).size();
1126            }
1127            return num;
1128        }
1129
1130        public void clear() {
1131            mUidMap.clear();
1132        }
1133
1134        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1135            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1136            if (map == null) {
1137                map = new ArrayMap<String, ArrayList<String>>();
1138                mUidMap.put(userId, map);
1139            }
1140            return map;
1141        }
1142    }
1143    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1144
1145    // Service Connection to remote media container service to copy
1146    // package uri's from external media onto secure containers
1147    // or internal storage.
1148    private IMediaContainerService mContainerService = null;
1149
1150    static final int SEND_PENDING_BROADCAST = 1;
1151    static final int MCS_BOUND = 3;
1152    static final int END_COPY = 4;
1153    static final int INIT_COPY = 5;
1154    static final int MCS_UNBIND = 6;
1155    static final int START_CLEANING_PACKAGE = 7;
1156    static final int FIND_INSTALL_LOC = 8;
1157    static final int POST_INSTALL = 9;
1158    static final int MCS_RECONNECT = 10;
1159    static final int MCS_GIVE_UP = 11;
1160    static final int UPDATED_MEDIA_STATUS = 12;
1161    static final int WRITE_SETTINGS = 13;
1162    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1163    static final int PACKAGE_VERIFIED = 15;
1164    static final int CHECK_PENDING_VERIFICATION = 16;
1165    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1166    static final int INTENT_FILTER_VERIFIED = 18;
1167    static final int WRITE_PACKAGE_LIST = 19;
1168    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1169
1170    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1171
1172    // Delay time in millisecs
1173    static final int BROADCAST_DELAY = 10 * 1000;
1174
1175    static UserManagerService sUserManager;
1176
1177    // Stores a list of users whose package restrictions file needs to be updated
1178    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1179
1180    final private DefaultContainerConnection mDefContainerConn =
1181            new DefaultContainerConnection();
1182    class DefaultContainerConnection implements ServiceConnection {
1183        public void onServiceConnected(ComponentName name, IBinder service) {
1184            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1185            final IMediaContainerService imcs = IMediaContainerService.Stub
1186                    .asInterface(Binder.allowBlocking(service));
1187            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1188        }
1189
1190        public void onServiceDisconnected(ComponentName name) {
1191            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1192        }
1193    }
1194
1195    // Recordkeeping of restore-after-install operations that are currently in flight
1196    // between the Package Manager and the Backup Manager
1197    static class PostInstallData {
1198        public InstallArgs args;
1199        public PackageInstalledInfo res;
1200
1201        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1202            args = _a;
1203            res = _r;
1204        }
1205    }
1206
1207    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1208    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1209
1210    // XML tags for backup/restore of various bits of state
1211    private static final String TAG_PREFERRED_BACKUP = "pa";
1212    private static final String TAG_DEFAULT_APPS = "da";
1213    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1214
1215    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1216    private static final String TAG_ALL_GRANTS = "rt-grants";
1217    private static final String TAG_GRANT = "grant";
1218    private static final String ATTR_PACKAGE_NAME = "pkg";
1219
1220    private static final String TAG_PERMISSION = "perm";
1221    private static final String ATTR_PERMISSION_NAME = "name";
1222    private static final String ATTR_IS_GRANTED = "g";
1223    private static final String ATTR_USER_SET = "set";
1224    private static final String ATTR_USER_FIXED = "fixed";
1225    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1226
1227    // System/policy permission grants are not backed up
1228    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1229            FLAG_PERMISSION_POLICY_FIXED
1230            | FLAG_PERMISSION_SYSTEM_FIXED
1231            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1232
1233    // And we back up these user-adjusted states
1234    private static final int USER_RUNTIME_GRANT_MASK =
1235            FLAG_PERMISSION_USER_SET
1236            | FLAG_PERMISSION_USER_FIXED
1237            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1238
1239    final @Nullable String mRequiredVerifierPackage;
1240    final @NonNull String mRequiredInstallerPackage;
1241    final @NonNull String mRequiredUninstallerPackage;
1242    final @Nullable String mSetupWizardPackage;
1243    final @Nullable String mStorageManagerPackage;
1244    final @NonNull String mServicesSystemSharedLibraryPackageName;
1245    final @NonNull String mSharedSystemSharedLibraryPackageName;
1246
1247    final boolean mPermissionReviewRequired;
1248
1249    private final PackageUsage mPackageUsage = new PackageUsage();
1250    private final CompilerStats mCompilerStats = new CompilerStats();
1251
1252    class PackageHandler extends Handler {
1253        private boolean mBound = false;
1254        final ArrayList<HandlerParams> mPendingInstalls =
1255            new ArrayList<HandlerParams>();
1256
1257        private boolean connectToService() {
1258            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1259                    " DefaultContainerService");
1260            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1261            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1262            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1263                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1264                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1265                mBound = true;
1266                return true;
1267            }
1268            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1269            return false;
1270        }
1271
1272        private void disconnectService() {
1273            mContainerService = null;
1274            mBound = false;
1275            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1276            mContext.unbindService(mDefContainerConn);
1277            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1278        }
1279
1280        PackageHandler(Looper looper) {
1281            super(looper);
1282        }
1283
1284        public void handleMessage(Message msg) {
1285            try {
1286                doHandleMessage(msg);
1287            } finally {
1288                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1289            }
1290        }
1291
1292        void doHandleMessage(Message msg) {
1293            switch (msg.what) {
1294                case INIT_COPY: {
1295                    HandlerParams params = (HandlerParams) msg.obj;
1296                    int idx = mPendingInstalls.size();
1297                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1298                    // If a bind was already initiated we dont really
1299                    // need to do anything. The pending install
1300                    // will be processed later on.
1301                    if (!mBound) {
1302                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1303                                System.identityHashCode(mHandler));
1304                        // If this is the only one pending we might
1305                        // have to bind to the service again.
1306                        if (!connectToService()) {
1307                            Slog.e(TAG, "Failed to bind to media container service");
1308                            params.serviceError();
1309                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1310                                    System.identityHashCode(mHandler));
1311                            if (params.traceMethod != null) {
1312                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1313                                        params.traceCookie);
1314                            }
1315                            return;
1316                        } else {
1317                            // Once we bind to the service, the first
1318                            // pending request will be processed.
1319                            mPendingInstalls.add(idx, params);
1320                        }
1321                    } else {
1322                        mPendingInstalls.add(idx, params);
1323                        // Already bound to the service. Just make
1324                        // sure we trigger off processing the first request.
1325                        if (idx == 0) {
1326                            mHandler.sendEmptyMessage(MCS_BOUND);
1327                        }
1328                    }
1329                    break;
1330                }
1331                case MCS_BOUND: {
1332                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1333                    if (msg.obj != null) {
1334                        mContainerService = (IMediaContainerService) msg.obj;
1335                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1336                                System.identityHashCode(mHandler));
1337                    }
1338                    if (mContainerService == null) {
1339                        if (!mBound) {
1340                            // Something seriously wrong since we are not bound and we are not
1341                            // waiting for connection. Bail out.
1342                            Slog.e(TAG, "Cannot bind to media container service");
1343                            for (HandlerParams params : mPendingInstalls) {
1344                                // Indicate service bind error
1345                                params.serviceError();
1346                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1347                                        System.identityHashCode(params));
1348                                if (params.traceMethod != null) {
1349                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1350                                            params.traceMethod, params.traceCookie);
1351                                }
1352                                return;
1353                            }
1354                            mPendingInstalls.clear();
1355                        } else {
1356                            Slog.w(TAG, "Waiting to connect to media container service");
1357                        }
1358                    } else if (mPendingInstalls.size() > 0) {
1359                        HandlerParams params = mPendingInstalls.get(0);
1360                        if (params != null) {
1361                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1362                                    System.identityHashCode(params));
1363                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1364                            if (params.startCopy()) {
1365                                // We are done...  look for more work or to
1366                                // go idle.
1367                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1368                                        "Checking for more work or unbind...");
1369                                // Delete pending install
1370                                if (mPendingInstalls.size() > 0) {
1371                                    mPendingInstalls.remove(0);
1372                                }
1373                                if (mPendingInstalls.size() == 0) {
1374                                    if (mBound) {
1375                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1376                                                "Posting delayed MCS_UNBIND");
1377                                        removeMessages(MCS_UNBIND);
1378                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1379                                        // Unbind after a little delay, to avoid
1380                                        // continual thrashing.
1381                                        sendMessageDelayed(ubmsg, 10000);
1382                                    }
1383                                } else {
1384                                    // There are more pending requests in queue.
1385                                    // Just post MCS_BOUND message to trigger processing
1386                                    // of next pending install.
1387                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1388                                            "Posting MCS_BOUND for next work");
1389                                    mHandler.sendEmptyMessage(MCS_BOUND);
1390                                }
1391                            }
1392                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1393                        }
1394                    } else {
1395                        // Should never happen ideally.
1396                        Slog.w(TAG, "Empty queue");
1397                    }
1398                    break;
1399                }
1400                case MCS_RECONNECT: {
1401                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1402                    if (mPendingInstalls.size() > 0) {
1403                        if (mBound) {
1404                            disconnectService();
1405                        }
1406                        if (!connectToService()) {
1407                            Slog.e(TAG, "Failed to bind to media container service");
1408                            for (HandlerParams params : mPendingInstalls) {
1409                                // Indicate service bind error
1410                                params.serviceError();
1411                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1412                                        System.identityHashCode(params));
1413                            }
1414                            mPendingInstalls.clear();
1415                        }
1416                    }
1417                    break;
1418                }
1419                case MCS_UNBIND: {
1420                    // If there is no actual work left, then time to unbind.
1421                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1422
1423                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1424                        if (mBound) {
1425                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1426
1427                            disconnectService();
1428                        }
1429                    } else if (mPendingInstalls.size() > 0) {
1430                        // There are more pending requests in queue.
1431                        // Just post MCS_BOUND message to trigger processing
1432                        // of next pending install.
1433                        mHandler.sendEmptyMessage(MCS_BOUND);
1434                    }
1435
1436                    break;
1437                }
1438                case MCS_GIVE_UP: {
1439                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1440                    HandlerParams params = mPendingInstalls.remove(0);
1441                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1442                            System.identityHashCode(params));
1443                    break;
1444                }
1445                case SEND_PENDING_BROADCAST: {
1446                    String packages[];
1447                    ArrayList<String> components[];
1448                    int size = 0;
1449                    int uids[];
1450                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1451                    synchronized (mPackages) {
1452                        if (mPendingBroadcasts == null) {
1453                            return;
1454                        }
1455                        size = mPendingBroadcasts.size();
1456                        if (size <= 0) {
1457                            // Nothing to be done. Just return
1458                            return;
1459                        }
1460                        packages = new String[size];
1461                        components = new ArrayList[size];
1462                        uids = new int[size];
1463                        int i = 0;  // filling out the above arrays
1464
1465                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1466                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1467                            Iterator<Map.Entry<String, ArrayList<String>>> it
1468                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1469                                            .entrySet().iterator();
1470                            while (it.hasNext() && i < size) {
1471                                Map.Entry<String, ArrayList<String>> ent = it.next();
1472                                packages[i] = ent.getKey();
1473                                components[i] = ent.getValue();
1474                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1475                                uids[i] = (ps != null)
1476                                        ? UserHandle.getUid(packageUserId, ps.appId)
1477                                        : -1;
1478                                i++;
1479                            }
1480                        }
1481                        size = i;
1482                        mPendingBroadcasts.clear();
1483                    }
1484                    // Send broadcasts
1485                    for (int i = 0; i < size; i++) {
1486                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1487                    }
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1489                    break;
1490                }
1491                case START_CLEANING_PACKAGE: {
1492                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1493                    final String packageName = (String)msg.obj;
1494                    final int userId = msg.arg1;
1495                    final boolean andCode = msg.arg2 != 0;
1496                    synchronized (mPackages) {
1497                        if (userId == UserHandle.USER_ALL) {
1498                            int[] users = sUserManager.getUserIds();
1499                            for (int user : users) {
1500                                mSettings.addPackageToCleanLPw(
1501                                        new PackageCleanItem(user, packageName, andCode));
1502                            }
1503                        } else {
1504                            mSettings.addPackageToCleanLPw(
1505                                    new PackageCleanItem(userId, packageName, andCode));
1506                        }
1507                    }
1508                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1509                    startCleaningPackages();
1510                } break;
1511                case POST_INSTALL: {
1512                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1513
1514                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1515                    final boolean didRestore = (msg.arg2 != 0);
1516                    mRunningInstalls.delete(msg.arg1);
1517
1518                    if (data != null) {
1519                        InstallArgs args = data.args;
1520                        PackageInstalledInfo parentRes = data.res;
1521
1522                        final boolean grantPermissions = (args.installFlags
1523                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1524                        final boolean killApp = (args.installFlags
1525                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1526                        final String[] grantedPermissions = args.installGrantPermissions;
1527
1528                        // Handle the parent package
1529                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1530                                grantedPermissions, didRestore, args.installerPackageName,
1531                                args.observer);
1532
1533                        // Handle the child packages
1534                        final int childCount = (parentRes.addedChildPackages != null)
1535                                ? parentRes.addedChildPackages.size() : 0;
1536                        for (int i = 0; i < childCount; i++) {
1537                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1538                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1539                                    grantedPermissions, false, args.installerPackageName,
1540                                    args.observer);
1541                        }
1542
1543                        // Log tracing if needed
1544                        if (args.traceMethod != null) {
1545                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1546                                    args.traceCookie);
1547                        }
1548                    } else {
1549                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1550                    }
1551
1552                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1553                } break;
1554                case UPDATED_MEDIA_STATUS: {
1555                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1556                    boolean reportStatus = msg.arg1 == 1;
1557                    boolean doGc = msg.arg2 == 1;
1558                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1559                    if (doGc) {
1560                        // Force a gc to clear up stale containers.
1561                        Runtime.getRuntime().gc();
1562                    }
1563                    if (msg.obj != null) {
1564                        @SuppressWarnings("unchecked")
1565                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1566                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1567                        // Unload containers
1568                        unloadAllContainers(args);
1569                    }
1570                    if (reportStatus) {
1571                        try {
1572                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1573                                    "Invoking StorageManagerService call back");
1574                            PackageHelper.getStorageManager().finishMediaUpdate();
1575                        } catch (RemoteException e) {
1576                            Log.e(TAG, "StorageManagerService not running?");
1577                        }
1578                    }
1579                } break;
1580                case WRITE_SETTINGS: {
1581                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1582                    synchronized (mPackages) {
1583                        removeMessages(WRITE_SETTINGS);
1584                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1585                        mSettings.writeLPr();
1586                        mDirtyUsers.clear();
1587                    }
1588                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1589                } break;
1590                case WRITE_PACKAGE_RESTRICTIONS: {
1591                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1592                    synchronized (mPackages) {
1593                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1594                        for (int userId : mDirtyUsers) {
1595                            mSettings.writePackageRestrictionsLPr(userId);
1596                        }
1597                        mDirtyUsers.clear();
1598                    }
1599                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1600                } break;
1601                case WRITE_PACKAGE_LIST: {
1602                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1603                    synchronized (mPackages) {
1604                        removeMessages(WRITE_PACKAGE_LIST);
1605                        mSettings.writePackageListLPr(msg.arg1);
1606                    }
1607                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1608                } break;
1609                case CHECK_PENDING_VERIFICATION: {
1610                    final int verificationId = msg.arg1;
1611                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1612
1613                    if ((state != null) && !state.timeoutExtended()) {
1614                        final InstallArgs args = state.getInstallArgs();
1615                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1616
1617                        Slog.i(TAG, "Verification timed out for " + originUri);
1618                        mPendingVerification.remove(verificationId);
1619
1620                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1621
1622                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1623                            Slog.i(TAG, "Continuing with installation of " + originUri);
1624                            state.setVerifierResponse(Binder.getCallingUid(),
1625                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1626                            broadcastPackageVerified(verificationId, originUri,
1627                                    PackageManager.VERIFICATION_ALLOW,
1628                                    state.getInstallArgs().getUser());
1629                            try {
1630                                ret = args.copyApk(mContainerService, true);
1631                            } catch (RemoteException e) {
1632                                Slog.e(TAG, "Could not contact the ContainerService");
1633                            }
1634                        } else {
1635                            broadcastPackageVerified(verificationId, originUri,
1636                                    PackageManager.VERIFICATION_REJECT,
1637                                    state.getInstallArgs().getUser());
1638                        }
1639
1640                        Trace.asyncTraceEnd(
1641                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1642
1643                        processPendingInstall(args, ret);
1644                        mHandler.sendEmptyMessage(MCS_UNBIND);
1645                    }
1646                    break;
1647                }
1648                case PACKAGE_VERIFIED: {
1649                    final int verificationId = msg.arg1;
1650
1651                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1652                    if (state == null) {
1653                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1654                        break;
1655                    }
1656
1657                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1658
1659                    state.setVerifierResponse(response.callerUid, response.code);
1660
1661                    if (state.isVerificationComplete()) {
1662                        mPendingVerification.remove(verificationId);
1663
1664                        final InstallArgs args = state.getInstallArgs();
1665                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1666
1667                        int ret;
1668                        if (state.isInstallAllowed()) {
1669                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1670                            broadcastPackageVerified(verificationId, originUri,
1671                                    response.code, state.getInstallArgs().getUser());
1672                            try {
1673                                ret = args.copyApk(mContainerService, true);
1674                            } catch (RemoteException e) {
1675                                Slog.e(TAG, "Could not contact the ContainerService");
1676                            }
1677                        } else {
1678                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1679                        }
1680
1681                        Trace.asyncTraceEnd(
1682                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1683
1684                        processPendingInstall(args, ret);
1685                        mHandler.sendEmptyMessage(MCS_UNBIND);
1686                    }
1687
1688                    break;
1689                }
1690                case START_INTENT_FILTER_VERIFICATIONS: {
1691                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1692                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1693                            params.replacing, params.pkg);
1694                    break;
1695                }
1696                case INTENT_FILTER_VERIFIED: {
1697                    final int verificationId = msg.arg1;
1698
1699                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1700                            verificationId);
1701                    if (state == null) {
1702                        Slog.w(TAG, "Invalid IntentFilter verification token "
1703                                + verificationId + " received");
1704                        break;
1705                    }
1706
1707                    final int userId = state.getUserId();
1708
1709                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1710                            "Processing IntentFilter verification with token:"
1711                            + verificationId + " and userId:" + userId);
1712
1713                    final IntentFilterVerificationResponse response =
1714                            (IntentFilterVerificationResponse) msg.obj;
1715
1716                    state.setVerifierResponse(response.callerUid, response.code);
1717
1718                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1719                            "IntentFilter verification with token:" + verificationId
1720                            + " and userId:" + userId
1721                            + " is settings verifier response with response code:"
1722                            + response.code);
1723
1724                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1725                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1726                                + response.getFailedDomainsString());
1727                    }
1728
1729                    if (state.isVerificationComplete()) {
1730                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1731                    } else {
1732                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1733                                "IntentFilter verification with token:" + verificationId
1734                                + " was not said to be complete");
1735                    }
1736
1737                    break;
1738                }
1739                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1740                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1741                            mInstantAppResolverConnection,
1742                            (InstantAppRequest) msg.obj,
1743                            mInstantAppInstallerActivity,
1744                            mHandler);
1745                }
1746            }
1747        }
1748    }
1749
1750    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1751            boolean killApp, String[] grantedPermissions,
1752            boolean launchedForRestore, String installerPackage,
1753            IPackageInstallObserver2 installObserver) {
1754        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1755            // Send the removed broadcasts
1756            if (res.removedInfo != null) {
1757                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1758            }
1759
1760            // Now that we successfully installed the package, grant runtime
1761            // permissions if requested before broadcasting the install. Also
1762            // for legacy apps in permission review mode we clear the permission
1763            // review flag which is used to emulate runtime permissions for
1764            // legacy apps.
1765            if (grantPermissions) {
1766                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1767            }
1768
1769            final boolean update = res.removedInfo != null
1770                    && res.removedInfo.removedPackage != null;
1771
1772            // If this is the first time we have child packages for a disabled privileged
1773            // app that had no children, we grant requested runtime permissions to the new
1774            // children if the parent on the system image had them already granted.
1775            if (res.pkg.parentPackage != null) {
1776                synchronized (mPackages) {
1777                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1778                }
1779            }
1780
1781            synchronized (mPackages) {
1782                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1783            }
1784
1785            final String packageName = res.pkg.applicationInfo.packageName;
1786
1787            // Determine the set of users who are adding this package for
1788            // the first time vs. those who are seeing an update.
1789            int[] firstUsers = EMPTY_INT_ARRAY;
1790            int[] updateUsers = EMPTY_INT_ARRAY;
1791            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1792            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1793            for (int newUser : res.newUsers) {
1794                if (ps.getInstantApp(newUser)) {
1795                    continue;
1796                }
1797                if (allNewUsers) {
1798                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1799                    continue;
1800                }
1801                boolean isNew = true;
1802                for (int origUser : res.origUsers) {
1803                    if (origUser == newUser) {
1804                        isNew = false;
1805                        break;
1806                    }
1807                }
1808                if (isNew) {
1809                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1810                } else {
1811                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1812                }
1813            }
1814
1815            // Send installed broadcasts if the package is not a static shared lib.
1816            if (res.pkg.staticSharedLibName == null) {
1817                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1818
1819                // Send added for users that see the package for the first time
1820                // sendPackageAddedForNewUsers also deals with system apps
1821                int appId = UserHandle.getAppId(res.uid);
1822                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1823                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1824
1825                // Send added for users that don't see the package for the first time
1826                Bundle extras = new Bundle(1);
1827                extras.putInt(Intent.EXTRA_UID, res.uid);
1828                if (update) {
1829                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1830                }
1831                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1832                        extras, 0 /*flags*/, null /*targetPackage*/,
1833                        null /*finishedReceiver*/, updateUsers);
1834
1835                // Send replaced for users that don't see the package for the first time
1836                if (update) {
1837                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1838                            packageName, extras, 0 /*flags*/,
1839                            null /*targetPackage*/, null /*finishedReceiver*/,
1840                            updateUsers);
1841                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1842                            null /*package*/, null /*extras*/, 0 /*flags*/,
1843                            packageName /*targetPackage*/,
1844                            null /*finishedReceiver*/, updateUsers);
1845                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1846                    // First-install and we did a restore, so we're responsible for the
1847                    // first-launch broadcast.
1848                    if (DEBUG_BACKUP) {
1849                        Slog.i(TAG, "Post-restore of " + packageName
1850                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1851                    }
1852                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1853                }
1854
1855                // Send broadcast package appeared if forward locked/external for all users
1856                // treat asec-hosted packages like removable media on upgrade
1857                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1858                    if (DEBUG_INSTALL) {
1859                        Slog.i(TAG, "upgrading pkg " + res.pkg
1860                                + " is ASEC-hosted -> AVAILABLE");
1861                    }
1862                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1863                    ArrayList<String> pkgList = new ArrayList<>(1);
1864                    pkgList.add(packageName);
1865                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1866                }
1867            }
1868
1869            // Work that needs to happen on first install within each user
1870            if (firstUsers != null && firstUsers.length > 0) {
1871                synchronized (mPackages) {
1872                    for (int userId : firstUsers) {
1873                        // If this app is a browser and it's newly-installed for some
1874                        // users, clear any default-browser state in those users. The
1875                        // app's nature doesn't depend on the user, so we can just check
1876                        // its browser nature in any user and generalize.
1877                        if (packageIsBrowser(packageName, userId)) {
1878                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1879                        }
1880
1881                        // We may also need to apply pending (restored) runtime
1882                        // permission grants within these users.
1883                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1884                    }
1885                }
1886            }
1887
1888            // Log current value of "unknown sources" setting
1889            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1890                    getUnknownSourcesSettings());
1891
1892            // Force a gc to clear up things
1893            Runtime.getRuntime().gc();
1894
1895            // Remove the replaced package's older resources safely now
1896            // We delete after a gc for applications  on sdcard.
1897            if (res.removedInfo != null && res.removedInfo.args != null) {
1898                synchronized (mInstallLock) {
1899                    res.removedInfo.args.doPostDeleteLI(true);
1900                }
1901            }
1902
1903            // Notify DexManager that the package was installed for new users.
1904            // The updated users should already be indexed and the package code paths
1905            // should not change.
1906            // Don't notify the manager for ephemeral apps as they are not expected to
1907            // survive long enough to benefit of background optimizations.
1908            for (int userId : firstUsers) {
1909                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1910                mDexManager.notifyPackageInstalled(info, userId);
1911            }
1912        }
1913
1914        // If someone is watching installs - notify them
1915        if (installObserver != null) {
1916            try {
1917                Bundle extras = extrasForInstallResult(res);
1918                installObserver.onPackageInstalled(res.name, res.returnCode,
1919                        res.returnMsg, extras);
1920            } catch (RemoteException e) {
1921                Slog.i(TAG, "Observer no longer exists.");
1922            }
1923        }
1924    }
1925
1926    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1927            PackageParser.Package pkg) {
1928        if (pkg.parentPackage == null) {
1929            return;
1930        }
1931        if (pkg.requestedPermissions == null) {
1932            return;
1933        }
1934        final PackageSetting disabledSysParentPs = mSettings
1935                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1936        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1937                || !disabledSysParentPs.isPrivileged()
1938                || (disabledSysParentPs.childPackageNames != null
1939                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1940            return;
1941        }
1942        final int[] allUserIds = sUserManager.getUserIds();
1943        final int permCount = pkg.requestedPermissions.size();
1944        for (int i = 0; i < permCount; i++) {
1945            String permission = pkg.requestedPermissions.get(i);
1946            BasePermission bp = mSettings.mPermissions.get(permission);
1947            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1948                continue;
1949            }
1950            for (int userId : allUserIds) {
1951                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1952                        permission, userId)) {
1953                    grantRuntimePermission(pkg.packageName, permission, userId);
1954                }
1955            }
1956        }
1957    }
1958
1959    private StorageEventListener mStorageListener = new StorageEventListener() {
1960        @Override
1961        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1962            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1963                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1964                    final String volumeUuid = vol.getFsUuid();
1965
1966                    // Clean up any users or apps that were removed or recreated
1967                    // while this volume was missing
1968                    sUserManager.reconcileUsers(volumeUuid);
1969                    reconcileApps(volumeUuid);
1970
1971                    // Clean up any install sessions that expired or were
1972                    // cancelled while this volume was missing
1973                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1974
1975                    loadPrivatePackages(vol);
1976
1977                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1978                    unloadPrivatePackages(vol);
1979                }
1980            }
1981
1982            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1983                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1984                    updateExternalMediaStatus(true, false);
1985                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1986                    updateExternalMediaStatus(false, false);
1987                }
1988            }
1989        }
1990
1991        @Override
1992        public void onVolumeForgotten(String fsUuid) {
1993            if (TextUtils.isEmpty(fsUuid)) {
1994                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1995                return;
1996            }
1997
1998            // Remove any apps installed on the forgotten volume
1999            synchronized (mPackages) {
2000                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2001                for (PackageSetting ps : packages) {
2002                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2003                    deletePackageVersioned(new VersionedPackage(ps.name,
2004                            PackageManager.VERSION_CODE_HIGHEST),
2005                            new LegacyPackageDeleteObserver(null).getBinder(),
2006                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2007                    // Try very hard to release any references to this package
2008                    // so we don't risk the system server being killed due to
2009                    // open FDs
2010                    AttributeCache.instance().removePackage(ps.name);
2011                }
2012
2013                mSettings.onVolumeForgotten(fsUuid);
2014                mSettings.writeLPr();
2015            }
2016        }
2017    };
2018
2019    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2020            String[] grantedPermissions) {
2021        for (int userId : userIds) {
2022            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2023        }
2024    }
2025
2026    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2027            String[] grantedPermissions) {
2028        SettingBase sb = (SettingBase) pkg.mExtras;
2029        if (sb == null) {
2030            return;
2031        }
2032
2033        PermissionsState permissionsState = sb.getPermissionsState();
2034
2035        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2036                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2037
2038        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2039                >= Build.VERSION_CODES.M;
2040
2041        for (String permission : pkg.requestedPermissions) {
2042            final BasePermission bp;
2043            synchronized (mPackages) {
2044                bp = mSettings.mPermissions.get(permission);
2045            }
2046            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2047                    && (grantedPermissions == null
2048                           || ArrayUtils.contains(grantedPermissions, permission))) {
2049                final int flags = permissionsState.getPermissionFlags(permission, userId);
2050                if (supportsRuntimePermissions) {
2051                    // Installer cannot change immutable permissions.
2052                    if ((flags & immutableFlags) == 0) {
2053                        grantRuntimePermission(pkg.packageName, permission, userId);
2054                    }
2055                } else if (mPermissionReviewRequired) {
2056                    // In permission review mode we clear the review flag when we
2057                    // are asked to install the app with all permissions granted.
2058                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2059                        updatePermissionFlags(permission, pkg.packageName,
2060                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2061                    }
2062                }
2063            }
2064        }
2065    }
2066
2067    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2068        Bundle extras = null;
2069        switch (res.returnCode) {
2070            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2071                extras = new Bundle();
2072                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2073                        res.origPermission);
2074                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2075                        res.origPackage);
2076                break;
2077            }
2078            case PackageManager.INSTALL_SUCCEEDED: {
2079                extras = new Bundle();
2080                extras.putBoolean(Intent.EXTRA_REPLACING,
2081                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2082                break;
2083            }
2084        }
2085        return extras;
2086    }
2087
2088    void scheduleWriteSettingsLocked() {
2089        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2090            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2091        }
2092    }
2093
2094    void scheduleWritePackageListLocked(int userId) {
2095        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2096            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2097            msg.arg1 = userId;
2098            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2099        }
2100    }
2101
2102    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2103        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2104        scheduleWritePackageRestrictionsLocked(userId);
2105    }
2106
2107    void scheduleWritePackageRestrictionsLocked(int userId) {
2108        final int[] userIds = (userId == UserHandle.USER_ALL)
2109                ? sUserManager.getUserIds() : new int[]{userId};
2110        for (int nextUserId : userIds) {
2111            if (!sUserManager.exists(nextUserId)) return;
2112            mDirtyUsers.add(nextUserId);
2113            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2114                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2115            }
2116        }
2117    }
2118
2119    public static PackageManagerService main(Context context, Installer installer,
2120            boolean factoryTest, boolean onlyCore) {
2121        // Self-check for initial settings.
2122        PackageManagerServiceCompilerMapping.checkProperties();
2123
2124        PackageManagerService m = new PackageManagerService(context, installer,
2125                factoryTest, onlyCore);
2126        m.enableSystemUserPackages();
2127        ServiceManager.addService("package", m);
2128        return m;
2129    }
2130
2131    private void enableSystemUserPackages() {
2132        if (!UserManager.isSplitSystemUser()) {
2133            return;
2134        }
2135        // For system user, enable apps based on the following conditions:
2136        // - app is whitelisted or belong to one of these groups:
2137        //   -- system app which has no launcher icons
2138        //   -- system app which has INTERACT_ACROSS_USERS permission
2139        //   -- system IME app
2140        // - app is not in the blacklist
2141        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2142        Set<String> enableApps = new ArraySet<>();
2143        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2144                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2145                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2146        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2147        enableApps.addAll(wlApps);
2148        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2149                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2150        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2151        enableApps.removeAll(blApps);
2152        Log.i(TAG, "Applications installed for system user: " + enableApps);
2153        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2154                UserHandle.SYSTEM);
2155        final int allAppsSize = allAps.size();
2156        synchronized (mPackages) {
2157            for (int i = 0; i < allAppsSize; i++) {
2158                String pName = allAps.get(i);
2159                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2160                // Should not happen, but we shouldn't be failing if it does
2161                if (pkgSetting == null) {
2162                    continue;
2163                }
2164                boolean install = enableApps.contains(pName);
2165                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2166                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2167                            + " for system user");
2168                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2169                }
2170            }
2171            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2172        }
2173    }
2174
2175    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2176        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2177                Context.DISPLAY_SERVICE);
2178        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2179    }
2180
2181    /**
2182     * Requests that files preopted on a secondary system partition be copied to the data partition
2183     * if possible.  Note that the actual copying of the files is accomplished by init for security
2184     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2185     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2186     */
2187    private static void requestCopyPreoptedFiles() {
2188        final int WAIT_TIME_MS = 100;
2189        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2190        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2191            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2192            // We will wait for up to 100 seconds.
2193            final long timeStart = SystemClock.uptimeMillis();
2194            final long timeEnd = timeStart + 100 * 1000;
2195            long timeNow = timeStart;
2196            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2197                try {
2198                    Thread.sleep(WAIT_TIME_MS);
2199                } catch (InterruptedException e) {
2200                    // Do nothing
2201                }
2202                timeNow = SystemClock.uptimeMillis();
2203                if (timeNow > timeEnd) {
2204                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2205                    Slog.wtf(TAG, "cppreopt did not finish!");
2206                    break;
2207                }
2208            }
2209
2210            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2211        }
2212    }
2213
2214    public PackageManagerService(Context context, Installer installer,
2215            boolean factoryTest, boolean onlyCore) {
2216        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2217        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2218        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2219                SystemClock.uptimeMillis());
2220
2221        if (mSdkVersion <= 0) {
2222            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2223        }
2224
2225        mContext = context;
2226
2227        mPermissionReviewRequired = context.getResources().getBoolean(
2228                R.bool.config_permissionReviewRequired);
2229
2230        mFactoryTest = factoryTest;
2231        mOnlyCore = onlyCore;
2232        mMetrics = new DisplayMetrics();
2233        mSettings = new Settings(mPackages);
2234        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2235                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2236        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2237                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2238        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2239                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2240        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2241                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2242        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2243                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2244        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2245                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2246
2247        String separateProcesses = SystemProperties.get("debug.separate_processes");
2248        if (separateProcesses != null && separateProcesses.length() > 0) {
2249            if ("*".equals(separateProcesses)) {
2250                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2251                mSeparateProcesses = null;
2252                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2253            } else {
2254                mDefParseFlags = 0;
2255                mSeparateProcesses = separateProcesses.split(",");
2256                Slog.w(TAG, "Running with debug.separate_processes: "
2257                        + separateProcesses);
2258            }
2259        } else {
2260            mDefParseFlags = 0;
2261            mSeparateProcesses = null;
2262        }
2263
2264        mInstaller = installer;
2265        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2266                "*dexopt*");
2267        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2268        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2269
2270        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2271                FgThread.get().getLooper());
2272
2273        getDefaultDisplayMetrics(context, mMetrics);
2274
2275        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2276        SystemConfig systemConfig = SystemConfig.getInstance();
2277        mGlobalGids = systemConfig.getGlobalGids();
2278        mSystemPermissions = systemConfig.getSystemPermissions();
2279        mAvailableFeatures = systemConfig.getAvailableFeatures();
2280        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2281
2282        mProtectedPackages = new ProtectedPackages(mContext);
2283
2284        synchronized (mInstallLock) {
2285        // writer
2286        synchronized (mPackages) {
2287            mHandlerThread = new ServiceThread(TAG,
2288                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2289            mHandlerThread.start();
2290            mHandler = new PackageHandler(mHandlerThread.getLooper());
2291            mProcessLoggingHandler = new ProcessLoggingHandler();
2292            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2293
2294            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2295            mInstantAppRegistry = new InstantAppRegistry(this);
2296
2297            File dataDir = Environment.getDataDirectory();
2298            mAppInstallDir = new File(dataDir, "app");
2299            mAppLib32InstallDir = new File(dataDir, "app-lib");
2300            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2301            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2302            sUserManager = new UserManagerService(context, this,
2303                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2304
2305            // Propagate permission configuration in to package manager.
2306            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2307                    = systemConfig.getPermissions();
2308            for (int i=0; i<permConfig.size(); i++) {
2309                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2310                BasePermission bp = mSettings.mPermissions.get(perm.name);
2311                if (bp == null) {
2312                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2313                    mSettings.mPermissions.put(perm.name, bp);
2314                }
2315                if (perm.gids != null) {
2316                    bp.setGids(perm.gids, perm.perUser);
2317                }
2318            }
2319
2320            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2321            final int builtInLibCount = libConfig.size();
2322            for (int i = 0; i < builtInLibCount; i++) {
2323                String name = libConfig.keyAt(i);
2324                String path = libConfig.valueAt(i);
2325                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2326                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2327            }
2328
2329            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2330
2331            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2332            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2333            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2334
2335            // Clean up orphaned packages for which the code path doesn't exist
2336            // and they are an update to a system app - caused by bug/32321269
2337            final int packageSettingCount = mSettings.mPackages.size();
2338            for (int i = packageSettingCount - 1; i >= 0; i--) {
2339                PackageSetting ps = mSettings.mPackages.valueAt(i);
2340                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2341                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2342                    mSettings.mPackages.removeAt(i);
2343                    mSettings.enableSystemPackageLPw(ps.name);
2344                }
2345            }
2346
2347            if (mFirstBoot) {
2348                requestCopyPreoptedFiles();
2349            }
2350
2351            String customResolverActivity = Resources.getSystem().getString(
2352                    R.string.config_customResolverActivity);
2353            if (TextUtils.isEmpty(customResolverActivity)) {
2354                customResolverActivity = null;
2355            } else {
2356                mCustomResolverComponentName = ComponentName.unflattenFromString(
2357                        customResolverActivity);
2358            }
2359
2360            long startTime = SystemClock.uptimeMillis();
2361
2362            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2363                    startTime);
2364
2365            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2366            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2367
2368            if (bootClassPath == null) {
2369                Slog.w(TAG, "No BOOTCLASSPATH found!");
2370            }
2371
2372            if (systemServerClassPath == null) {
2373                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2374            }
2375
2376            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2377            final String[] dexCodeInstructionSets =
2378                    getDexCodeInstructionSets(
2379                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2380
2381            /**
2382             * Ensure all external libraries have had dexopt run on them.
2383             */
2384            if (mSharedLibraries.size() > 0) {
2385                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2386                // NOTE: For now, we're compiling these system "shared libraries"
2387                // (and framework jars) into all available architectures. It's possible
2388                // to compile them only when we come across an app that uses them (there's
2389                // already logic for that in scanPackageLI) but that adds some complexity.
2390                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2391                    final int libCount = mSharedLibraries.size();
2392                    for (int i = 0; i < libCount; i++) {
2393                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2394                        final int versionCount = versionedLib.size();
2395                        for (int j = 0; j < versionCount; j++) {
2396                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2397                            final String libPath = libEntry.path != null
2398                                    ? libEntry.path : libEntry.apk;
2399                            if (libPath == null) {
2400                                continue;
2401                            }
2402                            try {
2403                                // Shared libraries do not have profiles so we perform a full
2404                                // AOT compilation (if needed).
2405                                int dexoptNeeded = DexFile.getDexOptNeeded(
2406                                        libPath, dexCodeInstructionSet,
2407                                        getCompilerFilterForReason(REASON_SHARED_APK),
2408                                        false /* newProfile */);
2409                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2410                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2411                                            dexCodeInstructionSet, dexoptNeeded, null,
2412                                            DEXOPT_PUBLIC,
2413                                            getCompilerFilterForReason(REASON_SHARED_APK),
2414                                            StorageManager.UUID_PRIVATE_INTERNAL,
2415                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2416                                }
2417                            } catch (FileNotFoundException e) {
2418                                Slog.w(TAG, "Library not found: " + libPath);
2419                            } catch (IOException | InstallerException e) {
2420                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2421                                        + e.getMessage());
2422                            }
2423                        }
2424                    }
2425                }
2426                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2427            }
2428
2429            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2430
2431            final VersionInfo ver = mSettings.getInternalVersion();
2432            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2433
2434            // when upgrading from pre-M, promote system app permissions from install to runtime
2435            mPromoteSystemApps =
2436                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2437
2438            // When upgrading from pre-N, we need to handle package extraction like first boot,
2439            // as there is no profiling data available.
2440            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2441
2442            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2443
2444            // save off the names of pre-existing system packages prior to scanning; we don't
2445            // want to automatically grant runtime permissions for new system apps
2446            if (mPromoteSystemApps) {
2447                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2448                while (pkgSettingIter.hasNext()) {
2449                    PackageSetting ps = pkgSettingIter.next();
2450                    if (isSystemApp(ps)) {
2451                        mExistingSystemPackages.add(ps.name);
2452                    }
2453                }
2454            }
2455
2456            mCacheDir = preparePackageParserCache(mIsUpgrade);
2457
2458            // Set flag to monitor and not change apk file paths when
2459            // scanning install directories.
2460            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2461
2462            if (mIsUpgrade || mFirstBoot) {
2463                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2464            }
2465
2466            // Collect vendor overlay packages. (Do this before scanning any apps.)
2467            // For security and version matching reason, only consider
2468            // overlay packages if they reside in the right directory.
2469            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2470                    | PackageParser.PARSE_IS_SYSTEM
2471                    | PackageParser.PARSE_IS_SYSTEM_DIR
2472                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2473
2474            // Find base frameworks (resource packages without code).
2475            scanDirTracedLI(frameworkDir, mDefParseFlags
2476                    | PackageParser.PARSE_IS_SYSTEM
2477                    | PackageParser.PARSE_IS_SYSTEM_DIR
2478                    | PackageParser.PARSE_IS_PRIVILEGED,
2479                    scanFlags | SCAN_NO_DEX, 0);
2480
2481            // Collected privileged system packages.
2482            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2483            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2484                    | PackageParser.PARSE_IS_SYSTEM
2485                    | PackageParser.PARSE_IS_SYSTEM_DIR
2486                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2487
2488            // Collect ordinary system packages.
2489            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2490            scanDirTracedLI(systemAppDir, mDefParseFlags
2491                    | PackageParser.PARSE_IS_SYSTEM
2492                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2493
2494            // Collect all vendor packages.
2495            File vendorAppDir = new File("/vendor/app");
2496            try {
2497                vendorAppDir = vendorAppDir.getCanonicalFile();
2498            } catch (IOException e) {
2499                // failed to look up canonical path, continue with original one
2500            }
2501            scanDirTracedLI(vendorAppDir, mDefParseFlags
2502                    | PackageParser.PARSE_IS_SYSTEM
2503                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2504
2505            // Collect all OEM packages.
2506            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2507            scanDirTracedLI(oemAppDir, mDefParseFlags
2508                    | PackageParser.PARSE_IS_SYSTEM
2509                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2510
2511            // Prune any system packages that no longer exist.
2512            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2513            if (!mOnlyCore) {
2514                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2515                while (psit.hasNext()) {
2516                    PackageSetting ps = psit.next();
2517
2518                    /*
2519                     * If this is not a system app, it can't be a
2520                     * disable system app.
2521                     */
2522                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2523                        continue;
2524                    }
2525
2526                    /*
2527                     * If the package is scanned, it's not erased.
2528                     */
2529                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2530                    if (scannedPkg != null) {
2531                        /*
2532                         * If the system app is both scanned and in the
2533                         * disabled packages list, then it must have been
2534                         * added via OTA. Remove it from the currently
2535                         * scanned package so the previously user-installed
2536                         * application can be scanned.
2537                         */
2538                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2539                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2540                                    + ps.name + "; removing system app.  Last known codePath="
2541                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2542                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2543                                    + scannedPkg.mVersionCode);
2544                            removePackageLI(scannedPkg, true);
2545                            mExpectingBetter.put(ps.name, ps.codePath);
2546                        }
2547
2548                        continue;
2549                    }
2550
2551                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2552                        psit.remove();
2553                        logCriticalInfo(Log.WARN, "System package " + ps.name
2554                                + " no longer exists; it's data will be wiped");
2555                        // Actual deletion of code and data will be handled by later
2556                        // reconciliation step
2557                    } else {
2558                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2559                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2560                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2561                        }
2562                    }
2563                }
2564            }
2565
2566            //look for any incomplete package installations
2567            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2568            for (int i = 0; i < deletePkgsList.size(); i++) {
2569                // Actual deletion of code and data will be handled by later
2570                // reconciliation step
2571                final String packageName = deletePkgsList.get(i).name;
2572                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2573                synchronized (mPackages) {
2574                    mSettings.removePackageLPw(packageName);
2575                }
2576            }
2577
2578            //delete tmp files
2579            deleteTempPackageFiles();
2580
2581            // Remove any shared userIDs that have no associated packages
2582            mSettings.pruneSharedUsersLPw();
2583
2584            if (!mOnlyCore) {
2585                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2586                        SystemClock.uptimeMillis());
2587                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2588
2589                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2590                        | PackageParser.PARSE_FORWARD_LOCK,
2591                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2592
2593                /**
2594                 * Remove disable package settings for any updated system
2595                 * apps that were removed via an OTA. If they're not a
2596                 * previously-updated app, remove them completely.
2597                 * Otherwise, just revoke their system-level permissions.
2598                 */
2599                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2600                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2601                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2602
2603                    String msg;
2604                    if (deletedPkg == null) {
2605                        msg = "Updated system package " + deletedAppName
2606                                + " no longer exists; it's data will be wiped";
2607                        // Actual deletion of code and data will be handled by later
2608                        // reconciliation step
2609                    } else {
2610                        msg = "Updated system app + " + deletedAppName
2611                                + " no longer present; removing system privileges for "
2612                                + deletedAppName;
2613
2614                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2615
2616                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2617                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2618                    }
2619                    logCriticalInfo(Log.WARN, msg);
2620                }
2621
2622                /**
2623                 * Make sure all system apps that we expected to appear on
2624                 * the userdata partition actually showed up. If they never
2625                 * appeared, crawl back and revive the system version.
2626                 */
2627                for (int i = 0; i < mExpectingBetter.size(); i++) {
2628                    final String packageName = mExpectingBetter.keyAt(i);
2629                    if (!mPackages.containsKey(packageName)) {
2630                        final File scanFile = mExpectingBetter.valueAt(i);
2631
2632                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2633                                + " but never showed up; reverting to system");
2634
2635                        int reparseFlags = mDefParseFlags;
2636                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2637                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2638                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2639                                    | PackageParser.PARSE_IS_PRIVILEGED;
2640                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2641                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2642                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2643                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2644                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2645                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2646                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2647                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2648                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2649                        } else {
2650                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2651                            continue;
2652                        }
2653
2654                        mSettings.enableSystemPackageLPw(packageName);
2655
2656                        try {
2657                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2658                        } catch (PackageManagerException e) {
2659                            Slog.e(TAG, "Failed to parse original system package: "
2660                                    + e.getMessage());
2661                        }
2662                    }
2663                }
2664            }
2665            mExpectingBetter.clear();
2666
2667            // Resolve the storage manager.
2668            mStorageManagerPackage = getStorageManagerPackageName();
2669
2670            // Resolve protected action filters. Only the setup wizard is allowed to
2671            // have a high priority filter for these actions.
2672            mSetupWizardPackage = getSetupWizardPackageName();
2673            if (mProtectedFilters.size() > 0) {
2674                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2675                    Slog.i(TAG, "No setup wizard;"
2676                        + " All protected intents capped to priority 0");
2677                }
2678                for (ActivityIntentInfo filter : mProtectedFilters) {
2679                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2680                        if (DEBUG_FILTERS) {
2681                            Slog.i(TAG, "Found setup wizard;"
2682                                + " allow priority " + filter.getPriority() + ";"
2683                                + " package: " + filter.activity.info.packageName
2684                                + " activity: " + filter.activity.className
2685                                + " priority: " + filter.getPriority());
2686                        }
2687                        // skip setup wizard; allow it to keep the high priority filter
2688                        continue;
2689                    }
2690                    Slog.w(TAG, "Protected action; cap priority to 0;"
2691                            + " package: " + filter.activity.info.packageName
2692                            + " activity: " + filter.activity.className
2693                            + " origPrio: " + filter.getPriority());
2694                    filter.setPriority(0);
2695                }
2696            }
2697            mDeferProtectedFilters = false;
2698            mProtectedFilters.clear();
2699
2700            // Now that we know all of the shared libraries, update all clients to have
2701            // the correct library paths.
2702            updateAllSharedLibrariesLPw(null);
2703
2704            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2705                // NOTE: We ignore potential failures here during a system scan (like
2706                // the rest of the commands above) because there's precious little we
2707                // can do about it. A settings error is reported, though.
2708                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2709            }
2710
2711            // Now that we know all the packages we are keeping,
2712            // read and update their last usage times.
2713            mPackageUsage.read(mPackages);
2714            mCompilerStats.read();
2715
2716            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2717                    SystemClock.uptimeMillis());
2718            Slog.i(TAG, "Time to scan packages: "
2719                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2720                    + " seconds");
2721
2722            // If the platform SDK has changed since the last time we booted,
2723            // we need to re-grant app permission to catch any new ones that
2724            // appear.  This is really a hack, and means that apps can in some
2725            // cases get permissions that the user didn't initially explicitly
2726            // allow...  it would be nice to have some better way to handle
2727            // this situation.
2728            int updateFlags = UPDATE_PERMISSIONS_ALL;
2729            if (ver.sdkVersion != mSdkVersion) {
2730                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2731                        + mSdkVersion + "; regranting permissions for internal storage");
2732                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2733            }
2734            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2735            ver.sdkVersion = mSdkVersion;
2736
2737            // If this is the first boot or an update from pre-M, and it is a normal
2738            // boot, then we need to initialize the default preferred apps across
2739            // all defined users.
2740            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2741                for (UserInfo user : sUserManager.getUsers(true)) {
2742                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2743                    applyFactoryDefaultBrowserLPw(user.id);
2744                    primeDomainVerificationsLPw(user.id);
2745                }
2746            }
2747
2748            // Prepare storage for system user really early during boot,
2749            // since core system apps like SettingsProvider and SystemUI
2750            // can't wait for user to start
2751            final int storageFlags;
2752            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2753                storageFlags = StorageManager.FLAG_STORAGE_DE;
2754            } else {
2755                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2756            }
2757            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2758                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2759                    true /* onlyCoreApps */);
2760            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2761                if (deferPackages == null || deferPackages.isEmpty()) {
2762                    return;
2763                }
2764                int count = 0;
2765                for (String pkgName : deferPackages) {
2766                    PackageParser.Package pkg = null;
2767                    synchronized (mPackages) {
2768                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2769                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2770                            pkg = ps.pkg;
2771                        }
2772                    }
2773                    if (pkg != null) {
2774                        synchronized (mInstallLock) {
2775                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2776                                    true /* maybeMigrateAppData */);
2777                        }
2778                        count++;
2779                    }
2780                }
2781                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2782            }, "prepareAppData");
2783
2784            // If this is first boot after an OTA, and a normal boot, then
2785            // we need to clear code cache directories.
2786            // Note that we do *not* clear the application profiles. These remain valid
2787            // across OTAs and are used to drive profile verification (post OTA) and
2788            // profile compilation (without waiting to collect a fresh set of profiles).
2789            if (mIsUpgrade && !onlyCore) {
2790                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2791                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2792                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2793                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2794                        // No apps are running this early, so no need to freeze
2795                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2796                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2797                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2798                    }
2799                }
2800                ver.fingerprint = Build.FINGERPRINT;
2801            }
2802
2803            checkDefaultBrowser();
2804
2805            // clear only after permissions and other defaults have been updated
2806            mExistingSystemPackages.clear();
2807            mPromoteSystemApps = false;
2808
2809            // All the changes are done during package scanning.
2810            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2811
2812            // can downgrade to reader
2813            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2814            mSettings.writeLPr();
2815            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2816
2817            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2818            // early on (before the package manager declares itself as early) because other
2819            // components in the system server might ask for package contexts for these apps.
2820            //
2821            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2822            // (i.e, that the data partition is unavailable).
2823            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2824                long start = System.nanoTime();
2825                List<PackageParser.Package> coreApps = new ArrayList<>();
2826                for (PackageParser.Package pkg : mPackages.values()) {
2827                    if (pkg.coreApp) {
2828                        coreApps.add(pkg);
2829                    }
2830                }
2831
2832                int[] stats = performDexOptUpgrade(coreApps, false,
2833                        getCompilerFilterForReason(REASON_CORE_APP));
2834
2835                final int elapsedTimeSeconds =
2836                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2837                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2838
2839                if (DEBUG_DEXOPT) {
2840                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2841                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2842                }
2843
2844
2845                // TODO: Should we log these stats to tron too ?
2846                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2847                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2848                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2849                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2850            }
2851
2852            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2853                    SystemClock.uptimeMillis());
2854
2855            if (!mOnlyCore) {
2856                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2857                mRequiredInstallerPackage = getRequiredInstallerLPr();
2858                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2859                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2860                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2861                        mIntentFilterVerifierComponent);
2862                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2863                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2864                        SharedLibraryInfo.VERSION_UNDEFINED);
2865                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2866                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2867                        SharedLibraryInfo.VERSION_UNDEFINED);
2868            } else {
2869                mRequiredVerifierPackage = null;
2870                mRequiredInstallerPackage = null;
2871                mRequiredUninstallerPackage = null;
2872                mIntentFilterVerifierComponent = null;
2873                mIntentFilterVerifier = null;
2874                mServicesSystemSharedLibraryPackageName = null;
2875                mSharedSystemSharedLibraryPackageName = null;
2876            }
2877
2878            mInstallerService = new PackageInstallerService(context, this);
2879
2880            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2881            if (ephemeralResolverComponent != null) {
2882                if (DEBUG_EPHEMERAL) {
2883                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2884                }
2885                mInstantAppResolverConnection =
2886                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2887            } else {
2888                mInstantAppResolverConnection = null;
2889            }
2890            mInstantAppInstallerComponent = getEphemeralInstallerLPr();
2891            if (mInstantAppInstallerComponent != null) {
2892                if (DEBUG_EPHEMERAL) {
2893                    Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent);
2894                }
2895                setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent);
2896            }
2897
2898            // Read and update the usage of dex files.
2899            // Do this at the end of PM init so that all the packages have their
2900            // data directory reconciled.
2901            // At this point we know the code paths of the packages, so we can validate
2902            // the disk file and build the internal cache.
2903            // The usage file is expected to be small so loading and verifying it
2904            // should take a fairly small time compare to the other activities (e.g. package
2905            // scanning).
2906            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2907            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2908            for (int userId : currentUserIds) {
2909                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2910            }
2911            mDexManager.load(userPackages);
2912        } // synchronized (mPackages)
2913        } // synchronized (mInstallLock)
2914
2915        // Now after opening every single application zip, make sure they
2916        // are all flushed.  Not really needed, but keeps things nice and
2917        // tidy.
2918        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2919        Runtime.getRuntime().gc();
2920        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2921
2922        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2923        FallbackCategoryProvider.loadFallbacks();
2924        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2925
2926        // The initial scanning above does many calls into installd while
2927        // holding the mPackages lock, but we're mostly interested in yelling
2928        // once we have a booted system.
2929        mInstaller.setWarnIfHeld(mPackages);
2930
2931        // Expose private service for system components to use.
2932        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2933        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2934    }
2935
2936    private static File preparePackageParserCache(boolean isUpgrade) {
2937        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2938            return null;
2939        }
2940
2941        // Disable package parsing on eng builds to allow for faster incremental development.
2942        if ("eng".equals(Build.TYPE)) {
2943            return null;
2944        }
2945
2946        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2947            Slog.i(TAG, "Disabling package parser cache due to system property.");
2948            return null;
2949        }
2950
2951        // The base directory for the package parser cache lives under /data/system/.
2952        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2953                "package_cache");
2954        if (cacheBaseDir == null) {
2955            return null;
2956        }
2957
2958        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2959        // This also serves to "GC" unused entries when the package cache version changes (which
2960        // can only happen during upgrades).
2961        if (isUpgrade) {
2962            FileUtils.deleteContents(cacheBaseDir);
2963        }
2964
2965
2966        // Return the versioned package cache directory. This is something like
2967        // "/data/system/package_cache/1"
2968        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2969
2970        // The following is a workaround to aid development on non-numbered userdebug
2971        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2972        // the system partition is newer.
2973        //
2974        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2975        // that starts with "eng." to signify that this is an engineering build and not
2976        // destined for release.
2977        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2978            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2979
2980            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2981            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2982            // in general and should not be used for production changes. In this specific case,
2983            // we know that they will work.
2984            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2985            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2986                FileUtils.deleteContents(cacheBaseDir);
2987                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2988            }
2989        }
2990
2991        return cacheDir;
2992    }
2993
2994    @Override
2995    public boolean isFirstBoot() {
2996        return mFirstBoot;
2997    }
2998
2999    @Override
3000    public boolean isOnlyCoreApps() {
3001        return mOnlyCore;
3002    }
3003
3004    @Override
3005    public boolean isUpgrade() {
3006        return mIsUpgrade;
3007    }
3008
3009    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3010        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3011
3012        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3013                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3014                UserHandle.USER_SYSTEM);
3015        if (matches.size() == 1) {
3016            return matches.get(0).getComponentInfo().packageName;
3017        } else if (matches.size() == 0) {
3018            Log.e(TAG, "There should probably be a verifier, but, none were found");
3019            return null;
3020        }
3021        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3022    }
3023
3024    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3025        synchronized (mPackages) {
3026            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3027            if (libraryEntry == null) {
3028                throw new IllegalStateException("Missing required shared library:" + name);
3029            }
3030            return libraryEntry.apk;
3031        }
3032    }
3033
3034    private @NonNull String getRequiredInstallerLPr() {
3035        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3036        intent.addCategory(Intent.CATEGORY_DEFAULT);
3037        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3038
3039        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3040                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3041                UserHandle.USER_SYSTEM);
3042        if (matches.size() == 1) {
3043            ResolveInfo resolveInfo = matches.get(0);
3044            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3045                throw new RuntimeException("The installer must be a privileged app");
3046            }
3047            return matches.get(0).getComponentInfo().packageName;
3048        } else {
3049            throw new RuntimeException("There must be exactly one installer; found " + matches);
3050        }
3051    }
3052
3053    private @NonNull String getRequiredUninstallerLPr() {
3054        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3055        intent.addCategory(Intent.CATEGORY_DEFAULT);
3056        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3057
3058        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3059                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3060                UserHandle.USER_SYSTEM);
3061        if (resolveInfo == null ||
3062                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3063            throw new RuntimeException("There must be exactly one uninstaller; found "
3064                    + resolveInfo);
3065        }
3066        return resolveInfo.getComponentInfo().packageName;
3067    }
3068
3069    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3070        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3071
3072        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3073                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3074                UserHandle.USER_SYSTEM);
3075        ResolveInfo best = null;
3076        final int N = matches.size();
3077        for (int i = 0; i < N; i++) {
3078            final ResolveInfo cur = matches.get(i);
3079            final String packageName = cur.getComponentInfo().packageName;
3080            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3081                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3082                continue;
3083            }
3084
3085            if (best == null || cur.priority > best.priority) {
3086                best = cur;
3087            }
3088        }
3089
3090        if (best != null) {
3091            return best.getComponentInfo().getComponentName();
3092        } else {
3093            throw new RuntimeException("There must be at least one intent filter verifier");
3094        }
3095    }
3096
3097    private @Nullable ComponentName getEphemeralResolverLPr() {
3098        final String[] packageArray =
3099                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3100        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3101            if (DEBUG_EPHEMERAL) {
3102                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3103            }
3104            return null;
3105        }
3106
3107        final int resolveFlags =
3108                MATCH_DIRECT_BOOT_AWARE
3109                | MATCH_DIRECT_BOOT_UNAWARE
3110                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3111        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3112        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3113                resolveFlags, UserHandle.USER_SYSTEM);
3114
3115        final int N = resolvers.size();
3116        if (N == 0) {
3117            if (DEBUG_EPHEMERAL) {
3118                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3119            }
3120            return null;
3121        }
3122
3123        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3124        for (int i = 0; i < N; i++) {
3125            final ResolveInfo info = resolvers.get(i);
3126
3127            if (info.serviceInfo == null) {
3128                continue;
3129            }
3130
3131            final String packageName = info.serviceInfo.packageName;
3132            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3133                if (DEBUG_EPHEMERAL) {
3134                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3135                            + " pkg: " + packageName + ", info:" + info);
3136                }
3137                continue;
3138            }
3139
3140            if (DEBUG_EPHEMERAL) {
3141                Slog.v(TAG, "Ephemeral resolver found;"
3142                        + " pkg: " + packageName + ", info:" + info);
3143            }
3144            return new ComponentName(packageName, info.serviceInfo.name);
3145        }
3146        if (DEBUG_EPHEMERAL) {
3147            Slog.v(TAG, "Ephemeral resolver NOT found");
3148        }
3149        return null;
3150    }
3151
3152    private @Nullable ComponentName getEphemeralInstallerLPr() {
3153        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3154        intent.addCategory(Intent.CATEGORY_DEFAULT);
3155        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3156
3157        final int resolveFlags =
3158                MATCH_DIRECT_BOOT_AWARE
3159                | MATCH_DIRECT_BOOT_UNAWARE
3160                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3161        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3162                resolveFlags, UserHandle.USER_SYSTEM);
3163        Iterator<ResolveInfo> iter = matches.iterator();
3164        while (iter.hasNext()) {
3165            final ResolveInfo rInfo = iter.next();
3166            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3167            if (ps != null) {
3168                final PermissionsState permissionsState = ps.getPermissionsState();
3169                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3170                    continue;
3171                }
3172            }
3173            iter.remove();
3174        }
3175        if (matches.size() == 0) {
3176            return null;
3177        } else if (matches.size() == 1) {
3178            return matches.get(0).getComponentInfo().getComponentName();
3179        } else {
3180            throw new RuntimeException(
3181                    "There must be at most one ephemeral installer; found " + matches);
3182        }
3183    }
3184
3185    private void primeDomainVerificationsLPw(int userId) {
3186        if (DEBUG_DOMAIN_VERIFICATION) {
3187            Slog.d(TAG, "Priming domain verifications in user " + userId);
3188        }
3189
3190        SystemConfig systemConfig = SystemConfig.getInstance();
3191        ArraySet<String> packages = systemConfig.getLinkedApps();
3192
3193        for (String packageName : packages) {
3194            PackageParser.Package pkg = mPackages.get(packageName);
3195            if (pkg != null) {
3196                if (!pkg.isSystemApp()) {
3197                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3198                    continue;
3199                }
3200
3201                ArraySet<String> domains = null;
3202                for (PackageParser.Activity a : pkg.activities) {
3203                    for (ActivityIntentInfo filter : a.intents) {
3204                        if (hasValidDomains(filter)) {
3205                            if (domains == null) {
3206                                domains = new ArraySet<String>();
3207                            }
3208                            domains.addAll(filter.getHostsList());
3209                        }
3210                    }
3211                }
3212
3213                if (domains != null && domains.size() > 0) {
3214                    if (DEBUG_DOMAIN_VERIFICATION) {
3215                        Slog.v(TAG, "      + " + packageName);
3216                    }
3217                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3218                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3219                    // and then 'always' in the per-user state actually used for intent resolution.
3220                    final IntentFilterVerificationInfo ivi;
3221                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3222                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3223                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3224                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3225                } else {
3226                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3227                            + "' does not handle web links");
3228                }
3229            } else {
3230                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3231            }
3232        }
3233
3234        scheduleWritePackageRestrictionsLocked(userId);
3235        scheduleWriteSettingsLocked();
3236    }
3237
3238    private void applyFactoryDefaultBrowserLPw(int userId) {
3239        // The default browser app's package name is stored in a string resource,
3240        // with a product-specific overlay used for vendor customization.
3241        String browserPkg = mContext.getResources().getString(
3242                com.android.internal.R.string.default_browser);
3243        if (!TextUtils.isEmpty(browserPkg)) {
3244            // non-empty string => required to be a known package
3245            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3246            if (ps == null) {
3247                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3248                browserPkg = null;
3249            } else {
3250                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3251            }
3252        }
3253
3254        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3255        // default.  If there's more than one, just leave everything alone.
3256        if (browserPkg == null) {
3257            calculateDefaultBrowserLPw(userId);
3258        }
3259    }
3260
3261    private void calculateDefaultBrowserLPw(int userId) {
3262        List<String> allBrowsers = resolveAllBrowserApps(userId);
3263        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3264        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3265    }
3266
3267    private List<String> resolveAllBrowserApps(int userId) {
3268        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3269        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3270                PackageManager.MATCH_ALL, userId);
3271
3272        final int count = list.size();
3273        List<String> result = new ArrayList<String>(count);
3274        for (int i=0; i<count; i++) {
3275            ResolveInfo info = list.get(i);
3276            if (info.activityInfo == null
3277                    || !info.handleAllWebDataURI
3278                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3279                    || result.contains(info.activityInfo.packageName)) {
3280                continue;
3281            }
3282            result.add(info.activityInfo.packageName);
3283        }
3284
3285        return result;
3286    }
3287
3288    private boolean packageIsBrowser(String packageName, int userId) {
3289        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3290                PackageManager.MATCH_ALL, userId);
3291        final int N = list.size();
3292        for (int i = 0; i < N; i++) {
3293            ResolveInfo info = list.get(i);
3294            if (packageName.equals(info.activityInfo.packageName)) {
3295                return true;
3296            }
3297        }
3298        return false;
3299    }
3300
3301    private void checkDefaultBrowser() {
3302        final int myUserId = UserHandle.myUserId();
3303        final String packageName = getDefaultBrowserPackageName(myUserId);
3304        if (packageName != null) {
3305            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3306            if (info == null) {
3307                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3308                synchronized (mPackages) {
3309                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3310                }
3311            }
3312        }
3313    }
3314
3315    @Override
3316    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3317            throws RemoteException {
3318        try {
3319            return super.onTransact(code, data, reply, flags);
3320        } catch (RuntimeException e) {
3321            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3322                Slog.wtf(TAG, "Package Manager Crash", e);
3323            }
3324            throw e;
3325        }
3326    }
3327
3328    static int[] appendInts(int[] cur, int[] add) {
3329        if (add == null) return cur;
3330        if (cur == null) return add;
3331        final int N = add.length;
3332        for (int i=0; i<N; i++) {
3333            cur = appendInt(cur, add[i]);
3334        }
3335        return cur;
3336    }
3337
3338    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3339        if (!sUserManager.exists(userId)) return null;
3340        if (ps == null) {
3341            return null;
3342        }
3343        final PackageParser.Package p = ps.pkg;
3344        if (p == null) {
3345            return null;
3346        }
3347        // Filter out ephemeral app metadata:
3348        //   * The system/shell/root can see metadata for any app
3349        //   * An installed app can see metadata for 1) other installed apps
3350        //     and 2) ephemeral apps that have explicitly interacted with it
3351        //   * Ephemeral apps can only see their own data and exposed installed apps
3352        //   * Holding a signature permission allows seeing instant apps
3353        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3354        if (callingAppId != Process.SYSTEM_UID
3355                && callingAppId != Process.SHELL_UID
3356                && callingAppId != Process.ROOT_UID
3357                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3358                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3359            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3360            if (instantAppPackageName != null) {
3361                // ephemeral apps can only get information on themselves or
3362                // installed apps that are exposed.
3363                if (!instantAppPackageName.equals(p.packageName)
3364                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3365                    return null;
3366                }
3367            } else {
3368                if (ps.getInstantApp(userId)) {
3369                    // only get access to the ephemeral app if we've been granted access
3370                    if (!mInstantAppRegistry.isInstantAccessGranted(
3371                            userId, callingAppId, ps.appId)) {
3372                        return null;
3373                    }
3374                }
3375            }
3376        }
3377
3378        final PermissionsState permissionsState = ps.getPermissionsState();
3379
3380        // Compute GIDs only if requested
3381        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3382                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3383        // Compute granted permissions only if package has requested permissions
3384        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3385                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3386        final PackageUserState state = ps.readUserState(userId);
3387
3388        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3389                && ps.isSystem()) {
3390            flags |= MATCH_ANY_USER;
3391        }
3392
3393        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3394                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3395
3396        if (packageInfo == null) {
3397            return null;
3398        }
3399
3400        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3401
3402        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3403                resolveExternalPackageNameLPr(p);
3404
3405        return packageInfo;
3406    }
3407
3408    @Override
3409    public void checkPackageStartable(String packageName, int userId) {
3410        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3411
3412        synchronized (mPackages) {
3413            final PackageSetting ps = mSettings.mPackages.get(packageName);
3414            if (ps == null) {
3415                throw new SecurityException("Package " + packageName + " was not found!");
3416            }
3417
3418            if (!ps.getInstalled(userId)) {
3419                throw new SecurityException(
3420                        "Package " + packageName + " was not installed for user " + userId + "!");
3421            }
3422
3423            if (mSafeMode && !ps.isSystem()) {
3424                throw new SecurityException("Package " + packageName + " not a system app!");
3425            }
3426
3427            if (mFrozenPackages.contains(packageName)) {
3428                throw new SecurityException("Package " + packageName + " is currently frozen!");
3429            }
3430
3431            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3432                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3433                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3434            }
3435        }
3436    }
3437
3438    @Override
3439    public boolean isPackageAvailable(String packageName, int userId) {
3440        if (!sUserManager.exists(userId)) return false;
3441        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3442                false /* requireFullPermission */, false /* checkShell */, "is package available");
3443        synchronized (mPackages) {
3444            PackageParser.Package p = mPackages.get(packageName);
3445            if (p != null) {
3446                final PackageSetting ps = (PackageSetting) p.mExtras;
3447                if (ps != null) {
3448                    final PackageUserState state = ps.readUserState(userId);
3449                    if (state != null) {
3450                        return PackageParser.isAvailable(state);
3451                    }
3452                }
3453            }
3454        }
3455        return false;
3456    }
3457
3458    @Override
3459    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3460        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3461                flags, userId);
3462    }
3463
3464    @Override
3465    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3466            int flags, int userId) {
3467        return getPackageInfoInternal(versionedPackage.getPackageName(),
3468                // TODO: We will change version code to long, so in the new API it is long
3469                (int) versionedPackage.getVersionCode(), flags, userId);
3470    }
3471
3472    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3473            int flags, int userId) {
3474        if (!sUserManager.exists(userId)) return null;
3475        flags = updateFlagsForPackage(flags, userId, packageName);
3476        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3477                false /* requireFullPermission */, false /* checkShell */, "get package info");
3478
3479        // reader
3480        synchronized (mPackages) {
3481            // Normalize package name to handle renamed packages and static libs
3482            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3483
3484            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3485            if (matchFactoryOnly) {
3486                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3487                if (ps != null) {
3488                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3489                        return null;
3490                    }
3491                    return generatePackageInfo(ps, flags, userId);
3492                }
3493            }
3494
3495            PackageParser.Package p = mPackages.get(packageName);
3496            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3497                return null;
3498            }
3499            if (DEBUG_PACKAGE_INFO)
3500                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3501            if (p != null) {
3502                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3503                        Binder.getCallingUid(), userId)) {
3504                    return null;
3505                }
3506                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3507            }
3508            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3509                final PackageSetting ps = mSettings.mPackages.get(packageName);
3510                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3511                    return null;
3512                }
3513                return generatePackageInfo(ps, flags, userId);
3514            }
3515        }
3516        return null;
3517    }
3518
3519
3520    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3521        // System/shell/root get to see all static libs
3522        final int appId = UserHandle.getAppId(uid);
3523        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3524                || appId == Process.ROOT_UID) {
3525            return false;
3526        }
3527
3528        // No package means no static lib as it is always on internal storage
3529        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3530            return false;
3531        }
3532
3533        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3534                ps.pkg.staticSharedLibVersion);
3535        if (libEntry == null) {
3536            return false;
3537        }
3538
3539        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3540        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3541        if (uidPackageNames == null) {
3542            return true;
3543        }
3544
3545        for (String uidPackageName : uidPackageNames) {
3546            if (ps.name.equals(uidPackageName)) {
3547                return false;
3548            }
3549            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3550            if (uidPs != null) {
3551                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3552                        libEntry.info.getName());
3553                if (index < 0) {
3554                    continue;
3555                }
3556                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3557                    return false;
3558                }
3559            }
3560        }
3561        return true;
3562    }
3563
3564    @Override
3565    public String[] currentToCanonicalPackageNames(String[] names) {
3566        String[] out = new String[names.length];
3567        // reader
3568        synchronized (mPackages) {
3569            for (int i=names.length-1; i>=0; i--) {
3570                PackageSetting ps = mSettings.mPackages.get(names[i]);
3571                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3572            }
3573        }
3574        return out;
3575    }
3576
3577    @Override
3578    public String[] canonicalToCurrentPackageNames(String[] names) {
3579        String[] out = new String[names.length];
3580        // reader
3581        synchronized (mPackages) {
3582            for (int i=names.length-1; i>=0; i--) {
3583                String cur = mSettings.getRenamedPackageLPr(names[i]);
3584                out[i] = cur != null ? cur : names[i];
3585            }
3586        }
3587        return out;
3588    }
3589
3590    @Override
3591    public int getPackageUid(String packageName, int flags, int userId) {
3592        if (!sUserManager.exists(userId)) return -1;
3593        flags = updateFlagsForPackage(flags, userId, packageName);
3594        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3595                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3596
3597        // reader
3598        synchronized (mPackages) {
3599            final PackageParser.Package p = mPackages.get(packageName);
3600            if (p != null && p.isMatch(flags)) {
3601                return UserHandle.getUid(userId, p.applicationInfo.uid);
3602            }
3603            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3604                final PackageSetting ps = mSettings.mPackages.get(packageName);
3605                if (ps != null && ps.isMatch(flags)) {
3606                    return UserHandle.getUid(userId, ps.appId);
3607                }
3608            }
3609        }
3610
3611        return -1;
3612    }
3613
3614    @Override
3615    public int[] getPackageGids(String packageName, int flags, int userId) {
3616        if (!sUserManager.exists(userId)) return null;
3617        flags = updateFlagsForPackage(flags, userId, packageName);
3618        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3619                false /* requireFullPermission */, false /* checkShell */,
3620                "getPackageGids");
3621
3622        // reader
3623        synchronized (mPackages) {
3624            final PackageParser.Package p = mPackages.get(packageName);
3625            if (p != null && p.isMatch(flags)) {
3626                PackageSetting ps = (PackageSetting) p.mExtras;
3627                // TODO: Shouldn't this be checking for package installed state for userId and
3628                // return null?
3629                return ps.getPermissionsState().computeGids(userId);
3630            }
3631            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3632                final PackageSetting ps = mSettings.mPackages.get(packageName);
3633                if (ps != null && ps.isMatch(flags)) {
3634                    return ps.getPermissionsState().computeGids(userId);
3635                }
3636            }
3637        }
3638
3639        return null;
3640    }
3641
3642    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3643        if (bp.perm != null) {
3644            return PackageParser.generatePermissionInfo(bp.perm, flags);
3645        }
3646        PermissionInfo pi = new PermissionInfo();
3647        pi.name = bp.name;
3648        pi.packageName = bp.sourcePackage;
3649        pi.nonLocalizedLabel = bp.name;
3650        pi.protectionLevel = bp.protectionLevel;
3651        return pi;
3652    }
3653
3654    @Override
3655    public PermissionInfo getPermissionInfo(String name, int flags) {
3656        // reader
3657        synchronized (mPackages) {
3658            final BasePermission p = mSettings.mPermissions.get(name);
3659            if (p != null) {
3660                return generatePermissionInfo(p, flags);
3661            }
3662            return null;
3663        }
3664    }
3665
3666    @Override
3667    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3668            int flags) {
3669        // reader
3670        synchronized (mPackages) {
3671            if (group != null && !mPermissionGroups.containsKey(group)) {
3672                // This is thrown as NameNotFoundException
3673                return null;
3674            }
3675
3676            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3677            for (BasePermission p : mSettings.mPermissions.values()) {
3678                if (group == null) {
3679                    if (p.perm == null || p.perm.info.group == null) {
3680                        out.add(generatePermissionInfo(p, flags));
3681                    }
3682                } else {
3683                    if (p.perm != null && group.equals(p.perm.info.group)) {
3684                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3685                    }
3686                }
3687            }
3688            return new ParceledListSlice<>(out);
3689        }
3690    }
3691
3692    @Override
3693    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3694        // reader
3695        synchronized (mPackages) {
3696            return PackageParser.generatePermissionGroupInfo(
3697                    mPermissionGroups.get(name), flags);
3698        }
3699    }
3700
3701    @Override
3702    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3703        // reader
3704        synchronized (mPackages) {
3705            final int N = mPermissionGroups.size();
3706            ArrayList<PermissionGroupInfo> out
3707                    = new ArrayList<PermissionGroupInfo>(N);
3708            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3709                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3710            }
3711            return new ParceledListSlice<>(out);
3712        }
3713    }
3714
3715    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3716            int uid, int userId) {
3717        if (!sUserManager.exists(userId)) return null;
3718        PackageSetting ps = mSettings.mPackages.get(packageName);
3719        if (ps != null) {
3720            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3721                return null;
3722            }
3723            if (ps.pkg == null) {
3724                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3725                if (pInfo != null) {
3726                    return pInfo.applicationInfo;
3727                }
3728                return null;
3729            }
3730            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3731                    ps.readUserState(userId), userId);
3732            if (ai != null) {
3733                rebaseEnabledOverlays(ai, userId);
3734                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3735            }
3736            return ai;
3737        }
3738        return null;
3739    }
3740
3741    @Override
3742    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3743        if (!sUserManager.exists(userId)) return null;
3744        flags = updateFlagsForApplication(flags, userId, packageName);
3745        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3746                false /* requireFullPermission */, false /* checkShell */, "get application info");
3747
3748        // writer
3749        synchronized (mPackages) {
3750            // Normalize package name to handle renamed packages and static libs
3751            packageName = resolveInternalPackageNameLPr(packageName,
3752                    PackageManager.VERSION_CODE_HIGHEST);
3753
3754            PackageParser.Package p = mPackages.get(packageName);
3755            if (DEBUG_PACKAGE_INFO) Log.v(
3756                    TAG, "getApplicationInfo " + packageName
3757                    + ": " + p);
3758            if (p != null) {
3759                PackageSetting ps = mSettings.mPackages.get(packageName);
3760                if (ps == null) return null;
3761                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3762                    return null;
3763                }
3764                // Note: isEnabledLP() does not apply here - always return info
3765                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3766                        p, flags, ps.readUserState(userId), userId);
3767                if (ai != null) {
3768                    rebaseEnabledOverlays(ai, userId);
3769                    ai.packageName = resolveExternalPackageNameLPr(p);
3770                }
3771                return ai;
3772            }
3773            if ("android".equals(packageName)||"system".equals(packageName)) {
3774                return mAndroidApplication;
3775            }
3776            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3777                // Already generates the external package name
3778                return generateApplicationInfoFromSettingsLPw(packageName,
3779                        Binder.getCallingUid(), flags, userId);
3780            }
3781        }
3782        return null;
3783    }
3784
3785    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3786        List<String> paths = new ArrayList<>();
3787        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3788            mEnabledOverlayPaths.get(userId);
3789        if (userSpecificOverlays != null) {
3790            if (!"android".equals(ai.packageName)) {
3791                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3792                if (frameworkOverlays != null) {
3793                    paths.addAll(frameworkOverlays);
3794                }
3795            }
3796
3797            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3798            if (appOverlays != null) {
3799                paths.addAll(appOverlays);
3800            }
3801        }
3802        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3803    }
3804
3805    private String normalizePackageNameLPr(String packageName) {
3806        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3807        return normalizedPackageName != null ? normalizedPackageName : packageName;
3808    }
3809
3810    @Override
3811    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3812            final IPackageDataObserver observer) {
3813        mContext.enforceCallingOrSelfPermission(
3814                android.Manifest.permission.CLEAR_APP_CACHE, null);
3815        mHandler.post(() -> {
3816            boolean success = false;
3817            try {
3818                freeStorage(volumeUuid, freeStorageSize, 0);
3819                success = true;
3820            } catch (IOException e) {
3821                Slog.w(TAG, e);
3822            }
3823            if (observer != null) {
3824                try {
3825                    observer.onRemoveCompleted(null, success);
3826                } catch (RemoteException e) {
3827                    Slog.w(TAG, e);
3828                }
3829            }
3830        });
3831    }
3832
3833    @Override
3834    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3835            final IntentSender pi) {
3836        mContext.enforceCallingOrSelfPermission(
3837                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3838        mHandler.post(() -> {
3839            boolean success = false;
3840            try {
3841                freeStorage(volumeUuid, freeStorageSize, 0);
3842                success = true;
3843            } catch (IOException e) {
3844                Slog.w(TAG, e);
3845            }
3846            if (pi != null) {
3847                try {
3848                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3849                } catch (SendIntentException e) {
3850                    Slog.w(TAG, e);
3851                }
3852            }
3853        });
3854    }
3855
3856    /**
3857     * Blocking call to clear various types of cached data across the system
3858     * until the requested bytes are available.
3859     */
3860    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3861        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3862        final File file = storage.findPathForUuid(volumeUuid);
3863
3864        if (ENABLE_FREE_CACHE_V2) {
3865            final boolean aggressive = (storageFlags
3866                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3867
3868            // 1. Pre-flight to determine if we have any chance to succeed
3869            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3870
3871            // 3. Consider parsed APK data (aggressive only)
3872            if (aggressive) {
3873                FileUtils.deleteContents(mCacheDir);
3874            }
3875            if (file.getUsableSpace() >= bytes) return;
3876
3877            // 4. Consider cached app data (above quotas)
3878            try {
3879                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3880            } catch (InstallerException ignored) {
3881            }
3882            if (file.getUsableSpace() >= bytes) return;
3883
3884            // 5. Consider shared libraries with refcount=0 and age>2h
3885            // 6. Consider dexopt output (aggressive only)
3886            // 7. Consider ephemeral apps not used in last week
3887
3888            // 8. Consider cached app data (below quotas)
3889            try {
3890                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3891                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3892            } catch (InstallerException ignored) {
3893            }
3894            if (file.getUsableSpace() >= bytes) return;
3895
3896            // 9. Consider DropBox entries
3897            // 10. Consider ephemeral cookies
3898
3899        } else {
3900            try {
3901                mInstaller.freeCache(volumeUuid, bytes, 0);
3902            } catch (InstallerException ignored) {
3903            }
3904            if (file.getUsableSpace() >= bytes) return;
3905        }
3906
3907        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3908    }
3909
3910    /**
3911     * Update given flags based on encryption status of current user.
3912     */
3913    private int updateFlags(int flags, int userId) {
3914        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3915                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3916            // Caller expressed an explicit opinion about what encryption
3917            // aware/unaware components they want to see, so fall through and
3918            // give them what they want
3919        } else {
3920            // Caller expressed no opinion, so match based on user state
3921            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3922                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3923            } else {
3924                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3925            }
3926        }
3927        return flags;
3928    }
3929
3930    private UserManagerInternal getUserManagerInternal() {
3931        if (mUserManagerInternal == null) {
3932            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3933        }
3934        return mUserManagerInternal;
3935    }
3936
3937    private DeviceIdleController.LocalService getDeviceIdleController() {
3938        if (mDeviceIdleController == null) {
3939            mDeviceIdleController =
3940                    LocalServices.getService(DeviceIdleController.LocalService.class);
3941        }
3942        return mDeviceIdleController;
3943    }
3944
3945    /**
3946     * Update given flags when being used to request {@link PackageInfo}.
3947     */
3948    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3949        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3950        boolean triaged = true;
3951        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3952                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3953            // Caller is asking for component details, so they'd better be
3954            // asking for specific encryption matching behavior, or be triaged
3955            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3956                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3957                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3958                triaged = false;
3959            }
3960        }
3961        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3962                | PackageManager.MATCH_SYSTEM_ONLY
3963                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3964            triaged = false;
3965        }
3966        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3967            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3968                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3969                    + Debug.getCallers(5));
3970        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3971                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3972            // If the caller wants all packages and has a restricted profile associated with it,
3973            // then match all users. This is to make sure that launchers that need to access work
3974            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3975            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3976            flags |= PackageManager.MATCH_ANY_USER;
3977        }
3978        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3979            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3980                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3981        }
3982        return updateFlags(flags, userId);
3983    }
3984
3985    /**
3986     * Update given flags when being used to request {@link ApplicationInfo}.
3987     */
3988    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3989        return updateFlagsForPackage(flags, userId, cookie);
3990    }
3991
3992    /**
3993     * Update given flags when being used to request {@link ComponentInfo}.
3994     */
3995    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3996        if (cookie instanceof Intent) {
3997            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3998                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3999            }
4000        }
4001
4002        boolean triaged = true;
4003        // Caller is asking for component details, so they'd better be
4004        // asking for specific encryption matching behavior, or be triaged
4005        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4006                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4007                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4008            triaged = false;
4009        }
4010        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4011            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4012                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4013        }
4014
4015        return updateFlags(flags, userId);
4016    }
4017
4018    /**
4019     * Update given intent when being used to request {@link ResolveInfo}.
4020     */
4021    private Intent updateIntentForResolve(Intent intent) {
4022        if (intent.getSelector() != null) {
4023            intent = intent.getSelector();
4024        }
4025        if (DEBUG_PREFERRED) {
4026            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4027        }
4028        return intent;
4029    }
4030
4031    /**
4032     * Update given flags when being used to request {@link ResolveInfo}.
4033     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4034     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4035     * flag set. However, this flag is only honoured in three circumstances:
4036     * <ul>
4037     * <li>when called from a system process</li>
4038     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4039     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4040     * action and a {@code android.intent.category.BROWSABLE} category</li>
4041     * </ul>
4042     */
4043    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4044        // Safe mode means we shouldn't match any third-party components
4045        if (mSafeMode) {
4046            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4047        }
4048        final int callingUid = Binder.getCallingUid();
4049        if (getInstantAppPackageName(callingUid) != null) {
4050            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4051            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4052            flags |= PackageManager.MATCH_INSTANT;
4053        } else {
4054            // Otherwise, prevent leaking ephemeral components
4055            final boolean isSpecialProcess =
4056                    callingUid == Process.SYSTEM_UID
4057                    || callingUid == Process.SHELL_UID
4058                    || callingUid == 0;
4059            final boolean allowMatchInstant =
4060                    (includeInstantApp
4061                            && Intent.ACTION_VIEW.equals(intent.getAction())
4062                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4063                            && hasWebURI(intent))
4064                    || isSpecialProcess
4065                    || mContext.checkCallingOrSelfPermission(
4066                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4067            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4068            if (!allowMatchInstant) {
4069                flags &= ~PackageManager.MATCH_INSTANT;
4070            }
4071        }
4072        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4073    }
4074
4075    @Override
4076    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4077        if (!sUserManager.exists(userId)) return null;
4078        flags = updateFlagsForComponent(flags, userId, component);
4079        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4080                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4081        synchronized (mPackages) {
4082            PackageParser.Activity a = mActivities.mActivities.get(component);
4083
4084            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4085            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4086                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4087                if (ps == null) return null;
4088                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4089                        userId);
4090            }
4091            if (mResolveComponentName.equals(component)) {
4092                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4093                        new PackageUserState(), userId);
4094            }
4095        }
4096        return null;
4097    }
4098
4099    @Override
4100    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4101            String resolvedType) {
4102        synchronized (mPackages) {
4103            if (component.equals(mResolveComponentName)) {
4104                // The resolver supports EVERYTHING!
4105                return true;
4106            }
4107            PackageParser.Activity a = mActivities.mActivities.get(component);
4108            if (a == null) {
4109                return false;
4110            }
4111            for (int i=0; i<a.intents.size(); i++) {
4112                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4113                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4114                    return true;
4115                }
4116            }
4117            return false;
4118        }
4119    }
4120
4121    @Override
4122    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4123        if (!sUserManager.exists(userId)) return null;
4124        flags = updateFlagsForComponent(flags, userId, component);
4125        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4126                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4127        synchronized (mPackages) {
4128            PackageParser.Activity a = mReceivers.mActivities.get(component);
4129            if (DEBUG_PACKAGE_INFO) Log.v(
4130                TAG, "getReceiverInfo " + component + ": " + a);
4131            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4132                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4133                if (ps == null) return null;
4134                ActivityInfo ri = PackageParser.generateActivityInfo(a, flags,
4135                        ps.readUserState(userId), userId);
4136                if (ri != null) {
4137                    rebaseEnabledOverlays(ri.applicationInfo, userId);
4138                }
4139                return ri;
4140            }
4141        }
4142        return null;
4143    }
4144
4145    @Override
4146    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4147        if (!sUserManager.exists(userId)) return null;
4148        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4149
4150        flags = updateFlagsForPackage(flags, userId, null);
4151
4152        final boolean canSeeStaticLibraries =
4153                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4154                        == PERMISSION_GRANTED
4155                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4156                        == PERMISSION_GRANTED
4157                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4158                        == PERMISSION_GRANTED
4159                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4160                        == PERMISSION_GRANTED;
4161
4162        synchronized (mPackages) {
4163            List<SharedLibraryInfo> result = null;
4164
4165            final int libCount = mSharedLibraries.size();
4166            for (int i = 0; i < libCount; i++) {
4167                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4168                if (versionedLib == null) {
4169                    continue;
4170                }
4171
4172                final int versionCount = versionedLib.size();
4173                for (int j = 0; j < versionCount; j++) {
4174                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4175                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4176                        break;
4177                    }
4178                    final long identity = Binder.clearCallingIdentity();
4179                    try {
4180                        // TODO: We will change version code to long, so in the new API it is long
4181                        PackageInfo packageInfo = getPackageInfoVersioned(
4182                                libInfo.getDeclaringPackage(), flags, userId);
4183                        if (packageInfo == null) {
4184                            continue;
4185                        }
4186                    } finally {
4187                        Binder.restoreCallingIdentity(identity);
4188                    }
4189
4190                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4191                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4192                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4193
4194                    if (result == null) {
4195                        result = new ArrayList<>();
4196                    }
4197                    result.add(resLibInfo);
4198                }
4199            }
4200
4201            return result != null ? new ParceledListSlice<>(result) : null;
4202        }
4203    }
4204
4205    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4206            SharedLibraryInfo libInfo, int flags, int userId) {
4207        List<VersionedPackage> versionedPackages = null;
4208        final int packageCount = mSettings.mPackages.size();
4209        for (int i = 0; i < packageCount; i++) {
4210            PackageSetting ps = mSettings.mPackages.valueAt(i);
4211
4212            if (ps == null) {
4213                continue;
4214            }
4215
4216            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4217                continue;
4218            }
4219
4220            final String libName = libInfo.getName();
4221            if (libInfo.isStatic()) {
4222                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4223                if (libIdx < 0) {
4224                    continue;
4225                }
4226                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4227                    continue;
4228                }
4229                if (versionedPackages == null) {
4230                    versionedPackages = new ArrayList<>();
4231                }
4232                // If the dependent is a static shared lib, use the public package name
4233                String dependentPackageName = ps.name;
4234                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4235                    dependentPackageName = ps.pkg.manifestPackageName;
4236                }
4237                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4238            } else if (ps.pkg != null) {
4239                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4240                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4241                    if (versionedPackages == null) {
4242                        versionedPackages = new ArrayList<>();
4243                    }
4244                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4245                }
4246            }
4247        }
4248
4249        return versionedPackages;
4250    }
4251
4252    @Override
4253    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4254        if (!sUserManager.exists(userId)) return null;
4255        flags = updateFlagsForComponent(flags, userId, component);
4256        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4257                false /* requireFullPermission */, false /* checkShell */, "get service info");
4258        synchronized (mPackages) {
4259            PackageParser.Service s = mServices.mServices.get(component);
4260            if (DEBUG_PACKAGE_INFO) Log.v(
4261                TAG, "getServiceInfo " + component + ": " + s);
4262            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4263                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4264                if (ps == null) return null;
4265                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4266                        ps.readUserState(userId), userId);
4267                if (si != null) {
4268                    rebaseEnabledOverlays(si.applicationInfo, userId);
4269                }
4270                return si;
4271            }
4272        }
4273        return null;
4274    }
4275
4276    @Override
4277    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4278        if (!sUserManager.exists(userId)) return null;
4279        flags = updateFlagsForComponent(flags, userId, component);
4280        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4281                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4282        synchronized (mPackages) {
4283            PackageParser.Provider p = mProviders.mProviders.get(component);
4284            if (DEBUG_PACKAGE_INFO) Log.v(
4285                TAG, "getProviderInfo " + component + ": " + p);
4286            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4287                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4288                if (ps == null) return null;
4289                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4290                        ps.readUserState(userId), userId);
4291                if (pi != null) {
4292                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4293                }
4294                return pi;
4295            }
4296        }
4297        return null;
4298    }
4299
4300    @Override
4301    public String[] getSystemSharedLibraryNames() {
4302        synchronized (mPackages) {
4303            Set<String> libs = null;
4304            final int libCount = mSharedLibraries.size();
4305            for (int i = 0; i < libCount; i++) {
4306                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4307                if (versionedLib == null) {
4308                    continue;
4309                }
4310                final int versionCount = versionedLib.size();
4311                for (int j = 0; j < versionCount; j++) {
4312                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4313                    if (!libEntry.info.isStatic()) {
4314                        if (libs == null) {
4315                            libs = new ArraySet<>();
4316                        }
4317                        libs.add(libEntry.info.getName());
4318                        break;
4319                    }
4320                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4321                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4322                            UserHandle.getUserId(Binder.getCallingUid()))) {
4323                        if (libs == null) {
4324                            libs = new ArraySet<>();
4325                        }
4326                        libs.add(libEntry.info.getName());
4327                        break;
4328                    }
4329                }
4330            }
4331
4332            if (libs != null) {
4333                String[] libsArray = new String[libs.size()];
4334                libs.toArray(libsArray);
4335                return libsArray;
4336            }
4337
4338            return null;
4339        }
4340    }
4341
4342    @Override
4343    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4344        synchronized (mPackages) {
4345            return mServicesSystemSharedLibraryPackageName;
4346        }
4347    }
4348
4349    @Override
4350    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4351        synchronized (mPackages) {
4352            return mSharedSystemSharedLibraryPackageName;
4353        }
4354    }
4355
4356    private void updateSequenceNumberLP(String packageName, int[] userList) {
4357        for (int i = userList.length - 1; i >= 0; --i) {
4358            final int userId = userList[i];
4359            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4360            if (changedPackages == null) {
4361                changedPackages = new SparseArray<>();
4362                mChangedPackages.put(userId, changedPackages);
4363            }
4364            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4365            if (sequenceNumbers == null) {
4366                sequenceNumbers = new HashMap<>();
4367                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4368            }
4369            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4370            if (sequenceNumber != null) {
4371                changedPackages.remove(sequenceNumber);
4372            }
4373            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4374            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4375        }
4376        mChangedPackagesSequenceNumber++;
4377    }
4378
4379    @Override
4380    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4381        synchronized (mPackages) {
4382            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4383                return null;
4384            }
4385            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4386            if (changedPackages == null) {
4387                return null;
4388            }
4389            final List<String> packageNames =
4390                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4391            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4392                final String packageName = changedPackages.get(i);
4393                if (packageName != null) {
4394                    packageNames.add(packageName);
4395                }
4396            }
4397            return packageNames.isEmpty()
4398                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4399        }
4400    }
4401
4402    @Override
4403    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4404        ArrayList<FeatureInfo> res;
4405        synchronized (mAvailableFeatures) {
4406            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4407            res.addAll(mAvailableFeatures.values());
4408        }
4409        final FeatureInfo fi = new FeatureInfo();
4410        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4411                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4412        res.add(fi);
4413
4414        return new ParceledListSlice<>(res);
4415    }
4416
4417    @Override
4418    public boolean hasSystemFeature(String name, int version) {
4419        synchronized (mAvailableFeatures) {
4420            final FeatureInfo feat = mAvailableFeatures.get(name);
4421            if (feat == null) {
4422                return false;
4423            } else {
4424                return feat.version >= version;
4425            }
4426        }
4427    }
4428
4429    @Override
4430    public int checkPermission(String permName, String pkgName, int userId) {
4431        if (!sUserManager.exists(userId)) {
4432            return PackageManager.PERMISSION_DENIED;
4433        }
4434
4435        synchronized (mPackages) {
4436            final PackageParser.Package p = mPackages.get(pkgName);
4437            if (p != null && p.mExtras != null) {
4438                final PackageSetting ps = (PackageSetting) p.mExtras;
4439                final PermissionsState permissionsState = ps.getPermissionsState();
4440                if (permissionsState.hasPermission(permName, userId)) {
4441                    return PackageManager.PERMISSION_GRANTED;
4442                }
4443                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4444                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4445                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4446                    return PackageManager.PERMISSION_GRANTED;
4447                }
4448            }
4449        }
4450
4451        return PackageManager.PERMISSION_DENIED;
4452    }
4453
4454    @Override
4455    public int checkUidPermission(String permName, int uid) {
4456        final int userId = UserHandle.getUserId(uid);
4457
4458        if (!sUserManager.exists(userId)) {
4459            return PackageManager.PERMISSION_DENIED;
4460        }
4461
4462        synchronized (mPackages) {
4463            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4464            if (obj != null) {
4465                final SettingBase ps = (SettingBase) obj;
4466                final PermissionsState permissionsState = ps.getPermissionsState();
4467                if (permissionsState.hasPermission(permName, userId)) {
4468                    return PackageManager.PERMISSION_GRANTED;
4469                }
4470                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4471                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4472                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4473                    return PackageManager.PERMISSION_GRANTED;
4474                }
4475            } else {
4476                ArraySet<String> perms = mSystemPermissions.get(uid);
4477                if (perms != null) {
4478                    if (perms.contains(permName)) {
4479                        return PackageManager.PERMISSION_GRANTED;
4480                    }
4481                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4482                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4483                        return PackageManager.PERMISSION_GRANTED;
4484                    }
4485                }
4486            }
4487        }
4488
4489        return PackageManager.PERMISSION_DENIED;
4490    }
4491
4492    @Override
4493    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4494        if (UserHandle.getCallingUserId() != userId) {
4495            mContext.enforceCallingPermission(
4496                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4497                    "isPermissionRevokedByPolicy for user " + userId);
4498        }
4499
4500        if (checkPermission(permission, packageName, userId)
4501                == PackageManager.PERMISSION_GRANTED) {
4502            return false;
4503        }
4504
4505        final long identity = Binder.clearCallingIdentity();
4506        try {
4507            final int flags = getPermissionFlags(permission, packageName, userId);
4508            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4509        } finally {
4510            Binder.restoreCallingIdentity(identity);
4511        }
4512    }
4513
4514    @Override
4515    public String getPermissionControllerPackageName() {
4516        synchronized (mPackages) {
4517            return mRequiredInstallerPackage;
4518        }
4519    }
4520
4521    /**
4522     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4523     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4524     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4525     * @param message the message to log on security exception
4526     */
4527    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4528            boolean checkShell, String message) {
4529        if (userId < 0) {
4530            throw new IllegalArgumentException("Invalid userId " + userId);
4531        }
4532        if (checkShell) {
4533            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4534        }
4535        if (userId == UserHandle.getUserId(callingUid)) return;
4536        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4537            if (requireFullPermission) {
4538                mContext.enforceCallingOrSelfPermission(
4539                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4540            } else {
4541                try {
4542                    mContext.enforceCallingOrSelfPermission(
4543                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4544                } catch (SecurityException se) {
4545                    mContext.enforceCallingOrSelfPermission(
4546                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4547                }
4548            }
4549        }
4550    }
4551
4552    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4553        if (callingUid == Process.SHELL_UID) {
4554            if (userHandle >= 0
4555                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4556                throw new SecurityException("Shell does not have permission to access user "
4557                        + userHandle);
4558            } else if (userHandle < 0) {
4559                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4560                        + Debug.getCallers(3));
4561            }
4562        }
4563    }
4564
4565    private BasePermission findPermissionTreeLP(String permName) {
4566        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4567            if (permName.startsWith(bp.name) &&
4568                    permName.length() > bp.name.length() &&
4569                    permName.charAt(bp.name.length()) == '.') {
4570                return bp;
4571            }
4572        }
4573        return null;
4574    }
4575
4576    private BasePermission checkPermissionTreeLP(String permName) {
4577        if (permName != null) {
4578            BasePermission bp = findPermissionTreeLP(permName);
4579            if (bp != null) {
4580                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4581                    return bp;
4582                }
4583                throw new SecurityException("Calling uid "
4584                        + Binder.getCallingUid()
4585                        + " is not allowed to add to permission tree "
4586                        + bp.name + " owned by uid " + bp.uid);
4587            }
4588        }
4589        throw new SecurityException("No permission tree found for " + permName);
4590    }
4591
4592    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4593        if (s1 == null) {
4594            return s2 == null;
4595        }
4596        if (s2 == null) {
4597            return false;
4598        }
4599        if (s1.getClass() != s2.getClass()) {
4600            return false;
4601        }
4602        return s1.equals(s2);
4603    }
4604
4605    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4606        if (pi1.icon != pi2.icon) return false;
4607        if (pi1.logo != pi2.logo) return false;
4608        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4609        if (!compareStrings(pi1.name, pi2.name)) return false;
4610        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4611        // We'll take care of setting this one.
4612        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4613        // These are not currently stored in settings.
4614        //if (!compareStrings(pi1.group, pi2.group)) return false;
4615        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4616        //if (pi1.labelRes != pi2.labelRes) return false;
4617        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4618        return true;
4619    }
4620
4621    int permissionInfoFootprint(PermissionInfo info) {
4622        int size = info.name.length();
4623        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4624        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4625        return size;
4626    }
4627
4628    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4629        int size = 0;
4630        for (BasePermission perm : mSettings.mPermissions.values()) {
4631            if (perm.uid == tree.uid) {
4632                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4633            }
4634        }
4635        return size;
4636    }
4637
4638    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4639        // We calculate the max size of permissions defined by this uid and throw
4640        // if that plus the size of 'info' would exceed our stated maximum.
4641        if (tree.uid != Process.SYSTEM_UID) {
4642            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4643            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4644                throw new SecurityException("Permission tree size cap exceeded");
4645            }
4646        }
4647    }
4648
4649    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4650        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4651            throw new SecurityException("Label must be specified in permission");
4652        }
4653        BasePermission tree = checkPermissionTreeLP(info.name);
4654        BasePermission bp = mSettings.mPermissions.get(info.name);
4655        boolean added = bp == null;
4656        boolean changed = true;
4657        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4658        if (added) {
4659            enforcePermissionCapLocked(info, tree);
4660            bp = new BasePermission(info.name, tree.sourcePackage,
4661                    BasePermission.TYPE_DYNAMIC);
4662        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4663            throw new SecurityException(
4664                    "Not allowed to modify non-dynamic permission "
4665                    + info.name);
4666        } else {
4667            if (bp.protectionLevel == fixedLevel
4668                    && bp.perm.owner.equals(tree.perm.owner)
4669                    && bp.uid == tree.uid
4670                    && comparePermissionInfos(bp.perm.info, info)) {
4671                changed = false;
4672            }
4673        }
4674        bp.protectionLevel = fixedLevel;
4675        info = new PermissionInfo(info);
4676        info.protectionLevel = fixedLevel;
4677        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4678        bp.perm.info.packageName = tree.perm.info.packageName;
4679        bp.uid = tree.uid;
4680        if (added) {
4681            mSettings.mPermissions.put(info.name, bp);
4682        }
4683        if (changed) {
4684            if (!async) {
4685                mSettings.writeLPr();
4686            } else {
4687                scheduleWriteSettingsLocked();
4688            }
4689        }
4690        return added;
4691    }
4692
4693    @Override
4694    public boolean addPermission(PermissionInfo info) {
4695        synchronized (mPackages) {
4696            return addPermissionLocked(info, false);
4697        }
4698    }
4699
4700    @Override
4701    public boolean addPermissionAsync(PermissionInfo info) {
4702        synchronized (mPackages) {
4703            return addPermissionLocked(info, true);
4704        }
4705    }
4706
4707    @Override
4708    public void removePermission(String name) {
4709        synchronized (mPackages) {
4710            checkPermissionTreeLP(name);
4711            BasePermission bp = mSettings.mPermissions.get(name);
4712            if (bp != null) {
4713                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4714                    throw new SecurityException(
4715                            "Not allowed to modify non-dynamic permission "
4716                            + name);
4717                }
4718                mSettings.mPermissions.remove(name);
4719                mSettings.writeLPr();
4720            }
4721        }
4722    }
4723
4724    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4725            BasePermission bp) {
4726        int index = pkg.requestedPermissions.indexOf(bp.name);
4727        if (index == -1) {
4728            throw new SecurityException("Package " + pkg.packageName
4729                    + " has not requested permission " + bp.name);
4730        }
4731        if (!bp.isRuntime() && !bp.isDevelopment()) {
4732            throw new SecurityException("Permission " + bp.name
4733                    + " is not a changeable permission type");
4734        }
4735    }
4736
4737    @Override
4738    public void grantRuntimePermission(String packageName, String name, final int userId) {
4739        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4740    }
4741
4742    private void grantRuntimePermission(String packageName, String name, final int userId,
4743            boolean overridePolicy) {
4744        if (!sUserManager.exists(userId)) {
4745            Log.e(TAG, "No such user:" + userId);
4746            return;
4747        }
4748
4749        mContext.enforceCallingOrSelfPermission(
4750                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4751                "grantRuntimePermission");
4752
4753        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4754                true /* requireFullPermission */, true /* checkShell */,
4755                "grantRuntimePermission");
4756
4757        final int uid;
4758        final SettingBase sb;
4759
4760        synchronized (mPackages) {
4761            final PackageParser.Package pkg = mPackages.get(packageName);
4762            if (pkg == null) {
4763                throw new IllegalArgumentException("Unknown package: " + packageName);
4764            }
4765
4766            final BasePermission bp = mSettings.mPermissions.get(name);
4767            if (bp == null) {
4768                throw new IllegalArgumentException("Unknown permission: " + name);
4769            }
4770
4771            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4772
4773            // If a permission review is required for legacy apps we represent
4774            // their permissions as always granted runtime ones since we need
4775            // to keep the review required permission flag per user while an
4776            // install permission's state is shared across all users.
4777            if (mPermissionReviewRequired
4778                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4779                    && bp.isRuntime()) {
4780                return;
4781            }
4782
4783            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4784            sb = (SettingBase) pkg.mExtras;
4785            if (sb == null) {
4786                throw new IllegalArgumentException("Unknown package: " + packageName);
4787            }
4788
4789            final PermissionsState permissionsState = sb.getPermissionsState();
4790
4791            final int flags = permissionsState.getPermissionFlags(name, userId);
4792            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4793                throw new SecurityException("Cannot grant system fixed permission "
4794                        + name + " for package " + packageName);
4795            }
4796            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4797                throw new SecurityException("Cannot grant policy fixed permission "
4798                        + name + " for package " + packageName);
4799            }
4800
4801            if (bp.isDevelopment()) {
4802                // Development permissions must be handled specially, since they are not
4803                // normal runtime permissions.  For now they apply to all users.
4804                if (permissionsState.grantInstallPermission(bp) !=
4805                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4806                    scheduleWriteSettingsLocked();
4807                }
4808                return;
4809            }
4810
4811            final PackageSetting ps = mSettings.mPackages.get(packageName);
4812            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4813                throw new SecurityException("Cannot grant non-ephemeral permission"
4814                        + name + " for package " + packageName);
4815            }
4816
4817            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4818                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4819                return;
4820            }
4821
4822            final int result = permissionsState.grantRuntimePermission(bp, userId);
4823            switch (result) {
4824                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4825                    return;
4826                }
4827
4828                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4829                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4830                    mHandler.post(new Runnable() {
4831                        @Override
4832                        public void run() {
4833                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4834                        }
4835                    });
4836                }
4837                break;
4838            }
4839
4840            if (bp.isRuntime()) {
4841                logPermissionGranted(mContext, name, packageName);
4842            }
4843
4844            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4845
4846            // Not critical if that is lost - app has to request again.
4847            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4848        }
4849
4850        // Only need to do this if user is initialized. Otherwise it's a new user
4851        // and there are no processes running as the user yet and there's no need
4852        // to make an expensive call to remount processes for the changed permissions.
4853        if (READ_EXTERNAL_STORAGE.equals(name)
4854                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4855            final long token = Binder.clearCallingIdentity();
4856            try {
4857                if (sUserManager.isInitialized(userId)) {
4858                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4859                            StorageManagerInternal.class);
4860                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4861                }
4862            } finally {
4863                Binder.restoreCallingIdentity(token);
4864            }
4865        }
4866    }
4867
4868    @Override
4869    public void revokeRuntimePermission(String packageName, String name, int userId) {
4870        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4871    }
4872
4873    private void revokeRuntimePermission(String packageName, String name, int userId,
4874            boolean overridePolicy) {
4875        if (!sUserManager.exists(userId)) {
4876            Log.e(TAG, "No such user:" + userId);
4877            return;
4878        }
4879
4880        mContext.enforceCallingOrSelfPermission(
4881                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4882                "revokeRuntimePermission");
4883
4884        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4885                true /* requireFullPermission */, true /* checkShell */,
4886                "revokeRuntimePermission");
4887
4888        final int appId;
4889
4890        synchronized (mPackages) {
4891            final PackageParser.Package pkg = mPackages.get(packageName);
4892            if (pkg == null) {
4893                throw new IllegalArgumentException("Unknown package: " + packageName);
4894            }
4895
4896            final BasePermission bp = mSettings.mPermissions.get(name);
4897            if (bp == null) {
4898                throw new IllegalArgumentException("Unknown permission: " + name);
4899            }
4900
4901            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4902
4903            // If a permission review is required for legacy apps we represent
4904            // their permissions as always granted runtime ones since we need
4905            // to keep the review required permission flag per user while an
4906            // install permission's state is shared across all users.
4907            if (mPermissionReviewRequired
4908                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4909                    && bp.isRuntime()) {
4910                return;
4911            }
4912
4913            SettingBase sb = (SettingBase) pkg.mExtras;
4914            if (sb == null) {
4915                throw new IllegalArgumentException("Unknown package: " + packageName);
4916            }
4917
4918            final PermissionsState permissionsState = sb.getPermissionsState();
4919
4920            final int flags = permissionsState.getPermissionFlags(name, userId);
4921            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4922                throw new SecurityException("Cannot revoke system fixed permission "
4923                        + name + " for package " + packageName);
4924            }
4925            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4926                throw new SecurityException("Cannot revoke policy fixed permission "
4927                        + name + " for package " + packageName);
4928            }
4929
4930            if (bp.isDevelopment()) {
4931                // Development permissions must be handled specially, since they are not
4932                // normal runtime permissions.  For now they apply to all users.
4933                if (permissionsState.revokeInstallPermission(bp) !=
4934                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4935                    scheduleWriteSettingsLocked();
4936                }
4937                return;
4938            }
4939
4940            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4941                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4942                return;
4943            }
4944
4945            if (bp.isRuntime()) {
4946                logPermissionRevoked(mContext, name, packageName);
4947            }
4948
4949            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4950
4951            // Critical, after this call app should never have the permission.
4952            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4953
4954            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4955        }
4956
4957        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4958    }
4959
4960    /**
4961     * Get the first event id for the permission.
4962     *
4963     * <p>There are four events for each permission: <ul>
4964     *     <li>Request permission: first id + 0</li>
4965     *     <li>Grant permission: first id + 1</li>
4966     *     <li>Request for permission denied: first id + 2</li>
4967     *     <li>Revoke permission: first id + 3</li>
4968     * </ul></p>
4969     *
4970     * @param name name of the permission
4971     *
4972     * @return The first event id for the permission
4973     */
4974    private static int getBaseEventId(@NonNull String name) {
4975        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4976
4977        if (eventIdIndex == -1) {
4978            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4979                    || "user".equals(Build.TYPE)) {
4980                Log.i(TAG, "Unknown permission " + name);
4981
4982                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4983            } else {
4984                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4985                //
4986                // Also update
4987                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4988                // - metrics_constants.proto
4989                throw new IllegalStateException("Unknown permission " + name);
4990            }
4991        }
4992
4993        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4994    }
4995
4996    /**
4997     * Log that a permission was revoked.
4998     *
4999     * @param context Context of the caller
5000     * @param name name of the permission
5001     * @param packageName package permission if for
5002     */
5003    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5004            @NonNull String packageName) {
5005        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5006    }
5007
5008    /**
5009     * Log that a permission request was granted.
5010     *
5011     * @param context Context of the caller
5012     * @param name name of the permission
5013     * @param packageName package permission if for
5014     */
5015    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5016            @NonNull String packageName) {
5017        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5018    }
5019
5020    @Override
5021    public void resetRuntimePermissions() {
5022        mContext.enforceCallingOrSelfPermission(
5023                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5024                "revokeRuntimePermission");
5025
5026        int callingUid = Binder.getCallingUid();
5027        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5028            mContext.enforceCallingOrSelfPermission(
5029                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5030                    "resetRuntimePermissions");
5031        }
5032
5033        synchronized (mPackages) {
5034            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5035            for (int userId : UserManagerService.getInstance().getUserIds()) {
5036                final int packageCount = mPackages.size();
5037                for (int i = 0; i < packageCount; i++) {
5038                    PackageParser.Package pkg = mPackages.valueAt(i);
5039                    if (!(pkg.mExtras instanceof PackageSetting)) {
5040                        continue;
5041                    }
5042                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5043                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5044                }
5045            }
5046        }
5047    }
5048
5049    @Override
5050    public int getPermissionFlags(String name, String packageName, int userId) {
5051        if (!sUserManager.exists(userId)) {
5052            return 0;
5053        }
5054
5055        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5056
5057        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5058                true /* requireFullPermission */, false /* checkShell */,
5059                "getPermissionFlags");
5060
5061        synchronized (mPackages) {
5062            final PackageParser.Package pkg = mPackages.get(packageName);
5063            if (pkg == null) {
5064                return 0;
5065            }
5066
5067            final BasePermission bp = mSettings.mPermissions.get(name);
5068            if (bp == null) {
5069                return 0;
5070            }
5071
5072            SettingBase sb = (SettingBase) pkg.mExtras;
5073            if (sb == null) {
5074                return 0;
5075            }
5076
5077            PermissionsState permissionsState = sb.getPermissionsState();
5078            return permissionsState.getPermissionFlags(name, userId);
5079        }
5080    }
5081
5082    @Override
5083    public void updatePermissionFlags(String name, String packageName, int flagMask,
5084            int flagValues, int userId) {
5085        if (!sUserManager.exists(userId)) {
5086            return;
5087        }
5088
5089        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5090
5091        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5092                true /* requireFullPermission */, true /* checkShell */,
5093                "updatePermissionFlags");
5094
5095        // Only the system can change these flags and nothing else.
5096        if (getCallingUid() != Process.SYSTEM_UID) {
5097            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5098            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5099            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5100            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5101            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5102        }
5103
5104        synchronized (mPackages) {
5105            final PackageParser.Package pkg = mPackages.get(packageName);
5106            if (pkg == null) {
5107                throw new IllegalArgumentException("Unknown package: " + packageName);
5108            }
5109
5110            final BasePermission bp = mSettings.mPermissions.get(name);
5111            if (bp == null) {
5112                throw new IllegalArgumentException("Unknown permission: " + name);
5113            }
5114
5115            SettingBase sb = (SettingBase) pkg.mExtras;
5116            if (sb == null) {
5117                throw new IllegalArgumentException("Unknown package: " + packageName);
5118            }
5119
5120            PermissionsState permissionsState = sb.getPermissionsState();
5121
5122            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5123
5124            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5125                // Install and runtime permissions are stored in different places,
5126                // so figure out what permission changed and persist the change.
5127                if (permissionsState.getInstallPermissionState(name) != null) {
5128                    scheduleWriteSettingsLocked();
5129                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5130                        || hadState) {
5131                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5132                }
5133            }
5134        }
5135    }
5136
5137    /**
5138     * Update the permission flags for all packages and runtime permissions of a user in order
5139     * to allow device or profile owner to remove POLICY_FIXED.
5140     */
5141    @Override
5142    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5143        if (!sUserManager.exists(userId)) {
5144            return;
5145        }
5146
5147        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5148
5149        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5150                true /* requireFullPermission */, true /* checkShell */,
5151                "updatePermissionFlagsForAllApps");
5152
5153        // Only the system can change system fixed flags.
5154        if (getCallingUid() != Process.SYSTEM_UID) {
5155            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5156            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5157        }
5158
5159        synchronized (mPackages) {
5160            boolean changed = false;
5161            final int packageCount = mPackages.size();
5162            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5163                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5164                SettingBase sb = (SettingBase) pkg.mExtras;
5165                if (sb == null) {
5166                    continue;
5167                }
5168                PermissionsState permissionsState = sb.getPermissionsState();
5169                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5170                        userId, flagMask, flagValues);
5171            }
5172            if (changed) {
5173                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5174            }
5175        }
5176    }
5177
5178    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5179        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5180                != PackageManager.PERMISSION_GRANTED
5181            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5182                != PackageManager.PERMISSION_GRANTED) {
5183            throw new SecurityException(message + " requires "
5184                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5185                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5186        }
5187    }
5188
5189    @Override
5190    public boolean shouldShowRequestPermissionRationale(String permissionName,
5191            String packageName, int userId) {
5192        if (UserHandle.getCallingUserId() != userId) {
5193            mContext.enforceCallingPermission(
5194                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5195                    "canShowRequestPermissionRationale for user " + userId);
5196        }
5197
5198        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5199        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5200            return false;
5201        }
5202
5203        if (checkPermission(permissionName, packageName, userId)
5204                == PackageManager.PERMISSION_GRANTED) {
5205            return false;
5206        }
5207
5208        final int flags;
5209
5210        final long identity = Binder.clearCallingIdentity();
5211        try {
5212            flags = getPermissionFlags(permissionName,
5213                    packageName, userId);
5214        } finally {
5215            Binder.restoreCallingIdentity(identity);
5216        }
5217
5218        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5219                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5220                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5221
5222        if ((flags & fixedFlags) != 0) {
5223            return false;
5224        }
5225
5226        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5227    }
5228
5229    @Override
5230    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5231        mContext.enforceCallingOrSelfPermission(
5232                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5233                "addOnPermissionsChangeListener");
5234
5235        synchronized (mPackages) {
5236            mOnPermissionChangeListeners.addListenerLocked(listener);
5237        }
5238    }
5239
5240    @Override
5241    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5242        synchronized (mPackages) {
5243            mOnPermissionChangeListeners.removeListenerLocked(listener);
5244        }
5245    }
5246
5247    @Override
5248    public boolean isProtectedBroadcast(String actionName) {
5249        synchronized (mPackages) {
5250            if (mProtectedBroadcasts.contains(actionName)) {
5251                return true;
5252            } else if (actionName != null) {
5253                // TODO: remove these terrible hacks
5254                if (actionName.startsWith("android.net.netmon.lingerExpired")
5255                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5256                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5257                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5258                    return true;
5259                }
5260            }
5261        }
5262        return false;
5263    }
5264
5265    @Override
5266    public int checkSignatures(String pkg1, String pkg2) {
5267        synchronized (mPackages) {
5268            final PackageParser.Package p1 = mPackages.get(pkg1);
5269            final PackageParser.Package p2 = mPackages.get(pkg2);
5270            if (p1 == null || p1.mExtras == null
5271                    || p2 == null || p2.mExtras == null) {
5272                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5273            }
5274            return compareSignatures(p1.mSignatures, p2.mSignatures);
5275        }
5276    }
5277
5278    @Override
5279    public int checkUidSignatures(int uid1, int uid2) {
5280        // Map to base uids.
5281        uid1 = UserHandle.getAppId(uid1);
5282        uid2 = UserHandle.getAppId(uid2);
5283        // reader
5284        synchronized (mPackages) {
5285            Signature[] s1;
5286            Signature[] s2;
5287            Object obj = mSettings.getUserIdLPr(uid1);
5288            if (obj != null) {
5289                if (obj instanceof SharedUserSetting) {
5290                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5291                } else if (obj instanceof PackageSetting) {
5292                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5293                } else {
5294                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5295                }
5296            } else {
5297                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5298            }
5299            obj = mSettings.getUserIdLPr(uid2);
5300            if (obj != null) {
5301                if (obj instanceof SharedUserSetting) {
5302                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5303                } else if (obj instanceof PackageSetting) {
5304                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5305                } else {
5306                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5307                }
5308            } else {
5309                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5310            }
5311            return compareSignatures(s1, s2);
5312        }
5313    }
5314
5315    /**
5316     * This method should typically only be used when granting or revoking
5317     * permissions, since the app may immediately restart after this call.
5318     * <p>
5319     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5320     * guard your work against the app being relaunched.
5321     */
5322    private void killUid(int appId, int userId, String reason) {
5323        final long identity = Binder.clearCallingIdentity();
5324        try {
5325            IActivityManager am = ActivityManager.getService();
5326            if (am != null) {
5327                try {
5328                    am.killUid(appId, userId, reason);
5329                } catch (RemoteException e) {
5330                    /* ignore - same process */
5331                }
5332            }
5333        } finally {
5334            Binder.restoreCallingIdentity(identity);
5335        }
5336    }
5337
5338    /**
5339     * Compares two sets of signatures. Returns:
5340     * <br />
5341     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5342     * <br />
5343     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5344     * <br />
5345     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5346     * <br />
5347     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5348     * <br />
5349     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5350     */
5351    static int compareSignatures(Signature[] s1, Signature[] s2) {
5352        if (s1 == null) {
5353            return s2 == null
5354                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5355                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5356        }
5357
5358        if (s2 == null) {
5359            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5360        }
5361
5362        if (s1.length != s2.length) {
5363            return PackageManager.SIGNATURE_NO_MATCH;
5364        }
5365
5366        // Since both signature sets are of size 1, we can compare without HashSets.
5367        if (s1.length == 1) {
5368            return s1[0].equals(s2[0]) ?
5369                    PackageManager.SIGNATURE_MATCH :
5370                    PackageManager.SIGNATURE_NO_MATCH;
5371        }
5372
5373        ArraySet<Signature> set1 = new ArraySet<Signature>();
5374        for (Signature sig : s1) {
5375            set1.add(sig);
5376        }
5377        ArraySet<Signature> set2 = new ArraySet<Signature>();
5378        for (Signature sig : s2) {
5379            set2.add(sig);
5380        }
5381        // Make sure s2 contains all signatures in s1.
5382        if (set1.equals(set2)) {
5383            return PackageManager.SIGNATURE_MATCH;
5384        }
5385        return PackageManager.SIGNATURE_NO_MATCH;
5386    }
5387
5388    /**
5389     * If the database version for this type of package (internal storage or
5390     * external storage) is less than the version where package signatures
5391     * were updated, return true.
5392     */
5393    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5394        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5395        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5396    }
5397
5398    /**
5399     * Used for backward compatibility to make sure any packages with
5400     * certificate chains get upgraded to the new style. {@code existingSigs}
5401     * will be in the old format (since they were stored on disk from before the
5402     * system upgrade) and {@code scannedSigs} will be in the newer format.
5403     */
5404    private int compareSignaturesCompat(PackageSignatures existingSigs,
5405            PackageParser.Package scannedPkg) {
5406        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5407            return PackageManager.SIGNATURE_NO_MATCH;
5408        }
5409
5410        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5411        for (Signature sig : existingSigs.mSignatures) {
5412            existingSet.add(sig);
5413        }
5414        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5415        for (Signature sig : scannedPkg.mSignatures) {
5416            try {
5417                Signature[] chainSignatures = sig.getChainSignatures();
5418                for (Signature chainSig : chainSignatures) {
5419                    scannedCompatSet.add(chainSig);
5420                }
5421            } catch (CertificateEncodingException e) {
5422                scannedCompatSet.add(sig);
5423            }
5424        }
5425        /*
5426         * Make sure the expanded scanned set contains all signatures in the
5427         * existing one.
5428         */
5429        if (scannedCompatSet.equals(existingSet)) {
5430            // Migrate the old signatures to the new scheme.
5431            existingSigs.assignSignatures(scannedPkg.mSignatures);
5432            // The new KeySets will be re-added later in the scanning process.
5433            synchronized (mPackages) {
5434                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5435            }
5436            return PackageManager.SIGNATURE_MATCH;
5437        }
5438        return PackageManager.SIGNATURE_NO_MATCH;
5439    }
5440
5441    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5442        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5443        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5444    }
5445
5446    private int compareSignaturesRecover(PackageSignatures existingSigs,
5447            PackageParser.Package scannedPkg) {
5448        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5449            return PackageManager.SIGNATURE_NO_MATCH;
5450        }
5451
5452        String msg = null;
5453        try {
5454            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5455                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5456                        + scannedPkg.packageName);
5457                return PackageManager.SIGNATURE_MATCH;
5458            }
5459        } catch (CertificateException e) {
5460            msg = e.getMessage();
5461        }
5462
5463        logCriticalInfo(Log.INFO,
5464                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5465        return PackageManager.SIGNATURE_NO_MATCH;
5466    }
5467
5468    @Override
5469    public List<String> getAllPackages() {
5470        synchronized (mPackages) {
5471            return new ArrayList<String>(mPackages.keySet());
5472        }
5473    }
5474
5475    @Override
5476    public String[] getPackagesForUid(int uid) {
5477        final int userId = UserHandle.getUserId(uid);
5478        uid = UserHandle.getAppId(uid);
5479        // reader
5480        synchronized (mPackages) {
5481            Object obj = mSettings.getUserIdLPr(uid);
5482            if (obj instanceof SharedUserSetting) {
5483                final SharedUserSetting sus = (SharedUserSetting) obj;
5484                final int N = sus.packages.size();
5485                String[] res = new String[N];
5486                final Iterator<PackageSetting> it = sus.packages.iterator();
5487                int i = 0;
5488                while (it.hasNext()) {
5489                    PackageSetting ps = it.next();
5490                    if (ps.getInstalled(userId)) {
5491                        res[i++] = ps.name;
5492                    } else {
5493                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5494                    }
5495                }
5496                return res;
5497            } else if (obj instanceof PackageSetting) {
5498                final PackageSetting ps = (PackageSetting) obj;
5499                if (ps.getInstalled(userId)) {
5500                    return new String[]{ps.name};
5501                }
5502            }
5503        }
5504        return null;
5505    }
5506
5507    @Override
5508    public String getNameForUid(int uid) {
5509        // reader
5510        synchronized (mPackages) {
5511            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5512            if (obj instanceof SharedUserSetting) {
5513                final SharedUserSetting sus = (SharedUserSetting) obj;
5514                return sus.name + ":" + sus.userId;
5515            } else if (obj instanceof PackageSetting) {
5516                final PackageSetting ps = (PackageSetting) obj;
5517                return ps.name;
5518            }
5519        }
5520        return null;
5521    }
5522
5523    @Override
5524    public int getUidForSharedUser(String sharedUserName) {
5525        if(sharedUserName == null) {
5526            return -1;
5527        }
5528        // reader
5529        synchronized (mPackages) {
5530            SharedUserSetting suid;
5531            try {
5532                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5533                if (suid != null) {
5534                    return suid.userId;
5535                }
5536            } catch (PackageManagerException ignore) {
5537                // can't happen, but, still need to catch it
5538            }
5539            return -1;
5540        }
5541    }
5542
5543    @Override
5544    public int getFlagsForUid(int uid) {
5545        synchronized (mPackages) {
5546            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5547            if (obj instanceof SharedUserSetting) {
5548                final SharedUserSetting sus = (SharedUserSetting) obj;
5549                return sus.pkgFlags;
5550            } else if (obj instanceof PackageSetting) {
5551                final PackageSetting ps = (PackageSetting) obj;
5552                return ps.pkgFlags;
5553            }
5554        }
5555        return 0;
5556    }
5557
5558    @Override
5559    public int getPrivateFlagsForUid(int uid) {
5560        synchronized (mPackages) {
5561            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5562            if (obj instanceof SharedUserSetting) {
5563                final SharedUserSetting sus = (SharedUserSetting) obj;
5564                return sus.pkgPrivateFlags;
5565            } else if (obj instanceof PackageSetting) {
5566                final PackageSetting ps = (PackageSetting) obj;
5567                return ps.pkgPrivateFlags;
5568            }
5569        }
5570        return 0;
5571    }
5572
5573    @Override
5574    public boolean isUidPrivileged(int uid) {
5575        uid = UserHandle.getAppId(uid);
5576        // reader
5577        synchronized (mPackages) {
5578            Object obj = mSettings.getUserIdLPr(uid);
5579            if (obj instanceof SharedUserSetting) {
5580                final SharedUserSetting sus = (SharedUserSetting) obj;
5581                final Iterator<PackageSetting> it = sus.packages.iterator();
5582                while (it.hasNext()) {
5583                    if (it.next().isPrivileged()) {
5584                        return true;
5585                    }
5586                }
5587            } else if (obj instanceof PackageSetting) {
5588                final PackageSetting ps = (PackageSetting) obj;
5589                return ps.isPrivileged();
5590            }
5591        }
5592        return false;
5593    }
5594
5595    @Override
5596    public String[] getAppOpPermissionPackages(String permissionName) {
5597        synchronized (mPackages) {
5598            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5599            if (pkgs == null) {
5600                return null;
5601            }
5602            return pkgs.toArray(new String[pkgs.size()]);
5603        }
5604    }
5605
5606    @Override
5607    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5608            int flags, int userId) {
5609        return resolveIntentInternal(
5610                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5611    }
5612
5613    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5614            int flags, int userId, boolean includeInstantApp) {
5615        try {
5616            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5617
5618            if (!sUserManager.exists(userId)) return null;
5619            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5620            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5621                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5622
5623            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5624            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5625                    flags, userId, includeInstantApp);
5626            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5627
5628            final ResolveInfo bestChoice =
5629                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5630            return bestChoice;
5631        } finally {
5632            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5633        }
5634    }
5635
5636    @Override
5637    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5638        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5639            throw new SecurityException(
5640                    "findPersistentPreferredActivity can only be run by the system");
5641        }
5642        if (!sUserManager.exists(userId)) {
5643            return null;
5644        }
5645        intent = updateIntentForResolve(intent);
5646        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5647        final int flags = updateFlagsForResolve(0, userId, intent, false);
5648        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5649                userId);
5650        synchronized (mPackages) {
5651            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5652                    userId);
5653        }
5654    }
5655
5656    @Override
5657    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5658            IntentFilter filter, int match, ComponentName activity) {
5659        final int userId = UserHandle.getCallingUserId();
5660        if (DEBUG_PREFERRED) {
5661            Log.v(TAG, "setLastChosenActivity intent=" + intent
5662                + " resolvedType=" + resolvedType
5663                + " flags=" + flags
5664                + " filter=" + filter
5665                + " match=" + match
5666                + " activity=" + activity);
5667            filter.dump(new PrintStreamPrinter(System.out), "    ");
5668        }
5669        intent.setComponent(null);
5670        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5671                userId);
5672        // Find any earlier preferred or last chosen entries and nuke them
5673        findPreferredActivity(intent, resolvedType,
5674                flags, query, 0, false, true, false, userId);
5675        // Add the new activity as the last chosen for this filter
5676        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5677                "Setting last chosen");
5678    }
5679
5680    @Override
5681    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5682        final int userId = UserHandle.getCallingUserId();
5683        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5684        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5685                userId);
5686        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5687                false, false, false, userId);
5688    }
5689
5690    /**
5691     * Returns whether or not instant apps have been disabled remotely.
5692     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5693     * held. Otherwise we run the risk of deadlock.
5694     */
5695    private boolean isEphemeralDisabled() {
5696        // ephemeral apps have been disabled across the board
5697        if (DISABLE_EPHEMERAL_APPS) {
5698            return true;
5699        }
5700        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5701        if (!mSystemReady) {
5702            return true;
5703        }
5704        // we can't get a content resolver until the system is ready; these checks must happen last
5705        final ContentResolver resolver = mContext.getContentResolver();
5706        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5707            return true;
5708        }
5709        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5710    }
5711
5712    private boolean isEphemeralAllowed(
5713            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5714            boolean skipPackageCheck) {
5715        final int callingUser = UserHandle.getCallingUserId();
5716        if (callingUser != UserHandle.USER_SYSTEM) {
5717            return false;
5718        }
5719        if (mInstantAppResolverConnection == null) {
5720            return false;
5721        }
5722        if (mInstantAppInstallerComponent == null) {
5723            return false;
5724        }
5725        if (intent.getComponent() != null) {
5726            return false;
5727        }
5728        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5729            return false;
5730        }
5731        if (!skipPackageCheck && intent.getPackage() != null) {
5732            return false;
5733        }
5734        final boolean isWebUri = hasWebURI(intent);
5735        if (!isWebUri || intent.getData().getHost() == null) {
5736            return false;
5737        }
5738        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5739        // Or if there's already an ephemeral app installed that handles the action
5740        synchronized (mPackages) {
5741            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5742            for (int n = 0; n < count; n++) {
5743                ResolveInfo info = resolvedActivities.get(n);
5744                String packageName = info.activityInfo.packageName;
5745                PackageSetting ps = mSettings.mPackages.get(packageName);
5746                if (ps != null) {
5747                    // Try to get the status from User settings first
5748                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5749                    int status = (int) (packedStatus >> 32);
5750                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5751                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5752                        if (DEBUG_EPHEMERAL) {
5753                            Slog.v(TAG, "DENY ephemeral apps;"
5754                                + " pkg: " + packageName + ", status: " + status);
5755                        }
5756                        return false;
5757                    }
5758                    if (ps.getInstantApp(userId)) {
5759                        return false;
5760                    }
5761                }
5762            }
5763        }
5764        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5765        return true;
5766    }
5767
5768    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5769            Intent origIntent, String resolvedType, String callingPackage,
5770            int userId) {
5771        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5772                new InstantAppRequest(responseObj, origIntent, resolvedType,
5773                        callingPackage, userId));
5774        mHandler.sendMessage(msg);
5775    }
5776
5777    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5778            int flags, List<ResolveInfo> query, int userId) {
5779        if (query != null) {
5780            final int N = query.size();
5781            if (N == 1) {
5782                return query.get(0);
5783            } else if (N > 1) {
5784                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5785                // If there is more than one activity with the same priority,
5786                // then let the user decide between them.
5787                ResolveInfo r0 = query.get(0);
5788                ResolveInfo r1 = query.get(1);
5789                if (DEBUG_INTENT_MATCHING || debug) {
5790                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5791                            + r1.activityInfo.name + "=" + r1.priority);
5792                }
5793                // If the first activity has a higher priority, or a different
5794                // default, then it is always desirable to pick it.
5795                if (r0.priority != r1.priority
5796                        || r0.preferredOrder != r1.preferredOrder
5797                        || r0.isDefault != r1.isDefault) {
5798                    return query.get(0);
5799                }
5800                // If we have saved a preference for a preferred activity for
5801                // this Intent, use that.
5802                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5803                        flags, query, r0.priority, true, false, debug, userId);
5804                if (ri != null) {
5805                    return ri;
5806                }
5807                // If we have an ephemeral app, use it
5808                for (int i = 0; i < N; i++) {
5809                    ri = query.get(i);
5810                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5811                        return ri;
5812                    }
5813                }
5814                ri = new ResolveInfo(mResolveInfo);
5815                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5816                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5817                // If all of the options come from the same package, show the application's
5818                // label and icon instead of the generic resolver's.
5819                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5820                // and then throw away the ResolveInfo itself, meaning that the caller loses
5821                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5822                // a fallback for this case; we only set the target package's resources on
5823                // the ResolveInfo, not the ActivityInfo.
5824                final String intentPackage = intent.getPackage();
5825                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5826                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5827                    ri.resolvePackageName = intentPackage;
5828                    if (userNeedsBadging(userId)) {
5829                        ri.noResourceId = true;
5830                    } else {
5831                        ri.icon = appi.icon;
5832                    }
5833                    ri.iconResourceId = appi.icon;
5834                    ri.labelRes = appi.labelRes;
5835                }
5836                ri.activityInfo.applicationInfo = new ApplicationInfo(
5837                        ri.activityInfo.applicationInfo);
5838                if (userId != 0) {
5839                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5840                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5841                }
5842                // Make sure that the resolver is displayable in car mode
5843                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5844                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5845                return ri;
5846            }
5847        }
5848        return null;
5849    }
5850
5851    /**
5852     * Return true if the given list is not empty and all of its contents have
5853     * an activityInfo with the given package name.
5854     */
5855    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5856        if (ArrayUtils.isEmpty(list)) {
5857            return false;
5858        }
5859        for (int i = 0, N = list.size(); i < N; i++) {
5860            final ResolveInfo ri = list.get(i);
5861            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5862            if (ai == null || !packageName.equals(ai.packageName)) {
5863                return false;
5864            }
5865        }
5866        return true;
5867    }
5868
5869    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5870            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5871        final int N = query.size();
5872        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5873                .get(userId);
5874        // Get the list of persistent preferred activities that handle the intent
5875        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5876        List<PersistentPreferredActivity> pprefs = ppir != null
5877                ? ppir.queryIntent(intent, resolvedType,
5878                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5879                        userId)
5880                : null;
5881        if (pprefs != null && pprefs.size() > 0) {
5882            final int M = pprefs.size();
5883            for (int i=0; i<M; i++) {
5884                final PersistentPreferredActivity ppa = pprefs.get(i);
5885                if (DEBUG_PREFERRED || debug) {
5886                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5887                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5888                            + "\n  component=" + ppa.mComponent);
5889                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5890                }
5891                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5892                        flags | MATCH_DISABLED_COMPONENTS, userId);
5893                if (DEBUG_PREFERRED || debug) {
5894                    Slog.v(TAG, "Found persistent preferred activity:");
5895                    if (ai != null) {
5896                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5897                    } else {
5898                        Slog.v(TAG, "  null");
5899                    }
5900                }
5901                if (ai == null) {
5902                    // This previously registered persistent preferred activity
5903                    // component is no longer known. Ignore it and do NOT remove it.
5904                    continue;
5905                }
5906                for (int j=0; j<N; j++) {
5907                    final ResolveInfo ri = query.get(j);
5908                    if (!ri.activityInfo.applicationInfo.packageName
5909                            .equals(ai.applicationInfo.packageName)) {
5910                        continue;
5911                    }
5912                    if (!ri.activityInfo.name.equals(ai.name)) {
5913                        continue;
5914                    }
5915                    //  Found a persistent preference that can handle the intent.
5916                    if (DEBUG_PREFERRED || debug) {
5917                        Slog.v(TAG, "Returning persistent preferred activity: " +
5918                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5919                    }
5920                    return ri;
5921                }
5922            }
5923        }
5924        return null;
5925    }
5926
5927    // TODO: handle preferred activities missing while user has amnesia
5928    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5929            List<ResolveInfo> query, int priority, boolean always,
5930            boolean removeMatches, boolean debug, int userId) {
5931        if (!sUserManager.exists(userId)) return null;
5932        flags = updateFlagsForResolve(flags, userId, intent, false);
5933        intent = updateIntentForResolve(intent);
5934        // writer
5935        synchronized (mPackages) {
5936            // Try to find a matching persistent preferred activity.
5937            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5938                    debug, userId);
5939
5940            // If a persistent preferred activity matched, use it.
5941            if (pri != null) {
5942                return pri;
5943            }
5944
5945            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5946            // Get the list of preferred activities that handle the intent
5947            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5948            List<PreferredActivity> prefs = pir != null
5949                    ? pir.queryIntent(intent, resolvedType,
5950                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5951                            userId)
5952                    : null;
5953            if (prefs != null && prefs.size() > 0) {
5954                boolean changed = false;
5955                try {
5956                    // First figure out how good the original match set is.
5957                    // We will only allow preferred activities that came
5958                    // from the same match quality.
5959                    int match = 0;
5960
5961                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5962
5963                    final int N = query.size();
5964                    for (int j=0; j<N; j++) {
5965                        final ResolveInfo ri = query.get(j);
5966                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5967                                + ": 0x" + Integer.toHexString(match));
5968                        if (ri.match > match) {
5969                            match = ri.match;
5970                        }
5971                    }
5972
5973                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5974                            + Integer.toHexString(match));
5975
5976                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5977                    final int M = prefs.size();
5978                    for (int i=0; i<M; i++) {
5979                        final PreferredActivity pa = prefs.get(i);
5980                        if (DEBUG_PREFERRED || debug) {
5981                            Slog.v(TAG, "Checking PreferredActivity ds="
5982                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5983                                    + "\n  component=" + pa.mPref.mComponent);
5984                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5985                        }
5986                        if (pa.mPref.mMatch != match) {
5987                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5988                                    + Integer.toHexString(pa.mPref.mMatch));
5989                            continue;
5990                        }
5991                        // If it's not an "always" type preferred activity and that's what we're
5992                        // looking for, skip it.
5993                        if (always && !pa.mPref.mAlways) {
5994                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5995                            continue;
5996                        }
5997                        final ActivityInfo ai = getActivityInfo(
5998                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5999                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6000                                userId);
6001                        if (DEBUG_PREFERRED || debug) {
6002                            Slog.v(TAG, "Found preferred activity:");
6003                            if (ai != null) {
6004                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6005                            } else {
6006                                Slog.v(TAG, "  null");
6007                            }
6008                        }
6009                        if (ai == null) {
6010                            // This previously registered preferred activity
6011                            // component is no longer known.  Most likely an update
6012                            // to the app was installed and in the new version this
6013                            // component no longer exists.  Clean it up by removing
6014                            // it from the preferred activities list, and skip it.
6015                            Slog.w(TAG, "Removing dangling preferred activity: "
6016                                    + pa.mPref.mComponent);
6017                            pir.removeFilter(pa);
6018                            changed = true;
6019                            continue;
6020                        }
6021                        for (int j=0; j<N; j++) {
6022                            final ResolveInfo ri = query.get(j);
6023                            if (!ri.activityInfo.applicationInfo.packageName
6024                                    .equals(ai.applicationInfo.packageName)) {
6025                                continue;
6026                            }
6027                            if (!ri.activityInfo.name.equals(ai.name)) {
6028                                continue;
6029                            }
6030
6031                            if (removeMatches) {
6032                                pir.removeFilter(pa);
6033                                changed = true;
6034                                if (DEBUG_PREFERRED) {
6035                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6036                                }
6037                                break;
6038                            }
6039
6040                            // Okay we found a previously set preferred or last chosen app.
6041                            // If the result set is different from when this
6042                            // was created, we need to clear it and re-ask the
6043                            // user their preference, if we're looking for an "always" type entry.
6044                            if (always && !pa.mPref.sameSet(query)) {
6045                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6046                                        + intent + " type " + resolvedType);
6047                                if (DEBUG_PREFERRED) {
6048                                    Slog.v(TAG, "Removing preferred activity since set changed "
6049                                            + pa.mPref.mComponent);
6050                                }
6051                                pir.removeFilter(pa);
6052                                // Re-add the filter as a "last chosen" entry (!always)
6053                                PreferredActivity lastChosen = new PreferredActivity(
6054                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6055                                pir.addFilter(lastChosen);
6056                                changed = true;
6057                                return null;
6058                            }
6059
6060                            // Yay! Either the set matched or we're looking for the last chosen
6061                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6062                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6063                            return ri;
6064                        }
6065                    }
6066                } finally {
6067                    if (changed) {
6068                        if (DEBUG_PREFERRED) {
6069                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6070                        }
6071                        scheduleWritePackageRestrictionsLocked(userId);
6072                    }
6073                }
6074            }
6075        }
6076        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6077        return null;
6078    }
6079
6080    /*
6081     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6082     */
6083    @Override
6084    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6085            int targetUserId) {
6086        mContext.enforceCallingOrSelfPermission(
6087                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6088        List<CrossProfileIntentFilter> matches =
6089                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6090        if (matches != null) {
6091            int size = matches.size();
6092            for (int i = 0; i < size; i++) {
6093                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6094            }
6095        }
6096        if (hasWebURI(intent)) {
6097            // cross-profile app linking works only towards the parent.
6098            final UserInfo parent = getProfileParent(sourceUserId);
6099            synchronized(mPackages) {
6100                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6101                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6102                        intent, resolvedType, flags, sourceUserId, parent.id);
6103                return xpDomainInfo != null;
6104            }
6105        }
6106        return false;
6107    }
6108
6109    private UserInfo getProfileParent(int userId) {
6110        final long identity = Binder.clearCallingIdentity();
6111        try {
6112            return sUserManager.getProfileParent(userId);
6113        } finally {
6114            Binder.restoreCallingIdentity(identity);
6115        }
6116    }
6117
6118    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6119            String resolvedType, int userId) {
6120        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6121        if (resolver != null) {
6122            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6123        }
6124        return null;
6125    }
6126
6127    @Override
6128    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6129            String resolvedType, int flags, int userId) {
6130        try {
6131            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6132
6133            return new ParceledListSlice<>(
6134                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6135        } finally {
6136            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6137        }
6138    }
6139
6140    /**
6141     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6142     * instant, returns {@code null}.
6143     */
6144    private String getInstantAppPackageName(int callingUid) {
6145        final int appId = UserHandle.getAppId(callingUid);
6146        synchronized (mPackages) {
6147            final Object obj = mSettings.getUserIdLPr(appId);
6148            if (obj instanceof PackageSetting) {
6149                final PackageSetting ps = (PackageSetting) obj;
6150                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6151                return isInstantApp ? ps.pkg.packageName : null;
6152            }
6153        }
6154        return null;
6155    }
6156
6157    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6158            String resolvedType, int flags, int userId) {
6159        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6160    }
6161
6162    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6163            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6164        if (!sUserManager.exists(userId)) return Collections.emptyList();
6165        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6166        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6167        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6168                false /* requireFullPermission */, false /* checkShell */,
6169                "query intent activities");
6170        ComponentName comp = intent.getComponent();
6171        if (comp == null) {
6172            if (intent.getSelector() != null) {
6173                intent = intent.getSelector();
6174                comp = intent.getComponent();
6175            }
6176        }
6177
6178        if (comp != null) {
6179            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6180            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6181            if (ai != null) {
6182                // When specifying an explicit component, we prevent the activity from being
6183                // used when either 1) the calling package is normal and the activity is within
6184                // an ephemeral application or 2) the calling package is ephemeral and the
6185                // activity is not visible to ephemeral applications.
6186                final boolean matchInstantApp =
6187                        (flags & PackageManager.MATCH_INSTANT) != 0;
6188                final boolean matchVisibleToInstantAppOnly =
6189                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6190                final boolean isCallerInstantApp =
6191                        instantAppPkgName != null;
6192                final boolean isTargetSameInstantApp =
6193                        comp.getPackageName().equals(instantAppPkgName);
6194                final boolean isTargetInstantApp =
6195                        (ai.applicationInfo.privateFlags
6196                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6197                final boolean isTargetHiddenFromInstantApp =
6198                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6199                final boolean blockResolution =
6200                        !isTargetSameInstantApp
6201                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6202                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6203                                        && isTargetHiddenFromInstantApp));
6204                if (!blockResolution) {
6205                    final ResolveInfo ri = new ResolveInfo();
6206                    ri.activityInfo = ai;
6207                    list.add(ri);
6208                }
6209            }
6210            return applyPostResolutionFilter(list, instantAppPkgName);
6211        }
6212
6213        // reader
6214        boolean sortResult = false;
6215        boolean addEphemeral = false;
6216        List<ResolveInfo> result;
6217        final String pkgName = intent.getPackage();
6218        final boolean ephemeralDisabled = isEphemeralDisabled();
6219        synchronized (mPackages) {
6220            if (pkgName == null) {
6221                List<CrossProfileIntentFilter> matchingFilters =
6222                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6223                // Check for results that need to skip the current profile.
6224                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6225                        resolvedType, flags, userId);
6226                if (xpResolveInfo != null) {
6227                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6228                    xpResult.add(xpResolveInfo);
6229                    return applyPostResolutionFilter(
6230                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6231                }
6232
6233                // Check for results in the current profile.
6234                result = filterIfNotSystemUser(mActivities.queryIntent(
6235                        intent, resolvedType, flags, userId), userId);
6236                addEphemeral = !ephemeralDisabled
6237                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6238
6239                // Check for cross profile results.
6240                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6241                xpResolveInfo = queryCrossProfileIntents(
6242                        matchingFilters, intent, resolvedType, flags, userId,
6243                        hasNonNegativePriorityResult);
6244                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6245                    boolean isVisibleToUser = filterIfNotSystemUser(
6246                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6247                    if (isVisibleToUser) {
6248                        result.add(xpResolveInfo);
6249                        sortResult = true;
6250                    }
6251                }
6252                if (hasWebURI(intent)) {
6253                    CrossProfileDomainInfo xpDomainInfo = null;
6254                    final UserInfo parent = getProfileParent(userId);
6255                    if (parent != null) {
6256                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6257                                flags, userId, parent.id);
6258                    }
6259                    if (xpDomainInfo != null) {
6260                        if (xpResolveInfo != null) {
6261                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6262                            // in the result.
6263                            result.remove(xpResolveInfo);
6264                        }
6265                        if (result.size() == 0 && !addEphemeral) {
6266                            // No result in current profile, but found candidate in parent user.
6267                            // And we are not going to add emphemeral app, so we can return the
6268                            // result straight away.
6269                            result.add(xpDomainInfo.resolveInfo);
6270                            return applyPostResolutionFilter(result, instantAppPkgName);
6271                        }
6272                    } else if (result.size() <= 1 && !addEphemeral) {
6273                        // No result in parent user and <= 1 result in current profile, and we
6274                        // are not going to add emphemeral app, so we can return the result without
6275                        // further processing.
6276                        return applyPostResolutionFilter(result, instantAppPkgName);
6277                    }
6278                    // We have more than one candidate (combining results from current and parent
6279                    // profile), so we need filtering and sorting.
6280                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6281                            intent, flags, result, xpDomainInfo, userId);
6282                    sortResult = true;
6283                }
6284            } else {
6285                final PackageParser.Package pkg = mPackages.get(pkgName);
6286                if (pkg != null) {
6287                    result = applyPostResolutionFilter(filterIfNotSystemUser(
6288                            mActivities.queryIntentForPackage(
6289                                    intent, resolvedType, flags, pkg.activities, userId),
6290                            userId), instantAppPkgName);
6291                } else {
6292                    // the caller wants to resolve for a particular package; however, there
6293                    // were no installed results, so, try to find an ephemeral result
6294                    addEphemeral =  !ephemeralDisabled
6295                            && isEphemeralAllowed(
6296                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6297                    result = new ArrayList<ResolveInfo>();
6298                }
6299            }
6300        }
6301        if (addEphemeral) {
6302            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6303            final InstantAppRequest requestObject = new InstantAppRequest(
6304                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6305                    null /*callingPackage*/, userId);
6306            final AuxiliaryResolveInfo auxiliaryResponse =
6307                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6308                            mContext, mInstantAppResolverConnection, requestObject);
6309            if (auxiliaryResponse != null) {
6310                if (DEBUG_EPHEMERAL) {
6311                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6312                }
6313                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6314                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6315                // make sure this resolver is the default
6316                ephemeralInstaller.isDefault = true;
6317                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6318                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6319                // add a non-generic filter
6320                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6321                ephemeralInstaller.filter.addDataPath(
6322                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6323                ephemeralInstaller.instantAppAvailable = true;
6324                result.add(ephemeralInstaller);
6325            }
6326            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6327        }
6328        if (sortResult) {
6329            Collections.sort(result, mResolvePrioritySorter);
6330        }
6331        return applyPostResolutionFilter(result, instantAppPkgName);
6332    }
6333
6334    private static class CrossProfileDomainInfo {
6335        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6336        ResolveInfo resolveInfo;
6337        /* Best domain verification status of the activities found in the other profile */
6338        int bestDomainVerificationStatus;
6339    }
6340
6341    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6342            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6343        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6344                sourceUserId)) {
6345            return null;
6346        }
6347        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6348                resolvedType, flags, parentUserId);
6349
6350        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6351            return null;
6352        }
6353        CrossProfileDomainInfo result = null;
6354        int size = resultTargetUser.size();
6355        for (int i = 0; i < size; i++) {
6356            ResolveInfo riTargetUser = resultTargetUser.get(i);
6357            // Intent filter verification is only for filters that specify a host. So don't return
6358            // those that handle all web uris.
6359            if (riTargetUser.handleAllWebDataURI) {
6360                continue;
6361            }
6362            String packageName = riTargetUser.activityInfo.packageName;
6363            PackageSetting ps = mSettings.mPackages.get(packageName);
6364            if (ps == null) {
6365                continue;
6366            }
6367            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6368            int status = (int)(verificationState >> 32);
6369            if (result == null) {
6370                result = new CrossProfileDomainInfo();
6371                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6372                        sourceUserId, parentUserId);
6373                result.bestDomainVerificationStatus = status;
6374            } else {
6375                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6376                        result.bestDomainVerificationStatus);
6377            }
6378        }
6379        // Don't consider matches with status NEVER across profiles.
6380        if (result != null && result.bestDomainVerificationStatus
6381                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6382            return null;
6383        }
6384        return result;
6385    }
6386
6387    /**
6388     * Verification statuses are ordered from the worse to the best, except for
6389     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6390     */
6391    private int bestDomainVerificationStatus(int status1, int status2) {
6392        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6393            return status2;
6394        }
6395        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6396            return status1;
6397        }
6398        return (int) MathUtils.max(status1, status2);
6399    }
6400
6401    private boolean isUserEnabled(int userId) {
6402        long callingId = Binder.clearCallingIdentity();
6403        try {
6404            UserInfo userInfo = sUserManager.getUserInfo(userId);
6405            return userInfo != null && userInfo.isEnabled();
6406        } finally {
6407            Binder.restoreCallingIdentity(callingId);
6408        }
6409    }
6410
6411    /**
6412     * Filter out activities with systemUserOnly flag set, when current user is not System.
6413     *
6414     * @return filtered list
6415     */
6416    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6417        if (userId == UserHandle.USER_SYSTEM) {
6418            return resolveInfos;
6419        }
6420        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6421            ResolveInfo info = resolveInfos.get(i);
6422            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6423                resolveInfos.remove(i);
6424            }
6425        }
6426        return resolveInfos;
6427    }
6428
6429    /**
6430     * Filters out ephemeral activities.
6431     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6432     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6433     *
6434     * @param resolveInfos The pre-filtered list of resolved activities
6435     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6436     *          is performed.
6437     * @return A filtered list of resolved activities.
6438     */
6439    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6440            String ephemeralPkgName) {
6441        // TODO: When adding on-demand split support for non-instant apps, remove this check
6442        // and always apply post filtering
6443        if (ephemeralPkgName == null) {
6444            return resolveInfos;
6445        }
6446        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6447            final ResolveInfo info = resolveInfos.get(i);
6448            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6449            // allow activities that are defined in the provided package
6450            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6451                if (info.activityInfo.splitName != null
6452                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6453                                info.activityInfo.splitName)) {
6454                    // requested activity is defined in a split that hasn't been installed yet.
6455                    // add the installer to the resolve list
6456                    if (DEBUG_EPHEMERAL) {
6457                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6458                    }
6459                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6460                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6461                            info.activityInfo.packageName, info.activityInfo.splitName,
6462                            info.activityInfo.applicationInfo.versionCode);
6463                    // make sure this resolver is the default
6464                    installerInfo.isDefault = true;
6465                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6466                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6467                    // add a non-generic filter
6468                    installerInfo.filter = new IntentFilter();
6469                    // load resources from the correct package
6470                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6471                    resolveInfos.set(i, installerInfo);
6472                }
6473                continue;
6474            }
6475            // allow activities that have been explicitly exposed to ephemeral apps
6476            if (!isEphemeralApp
6477                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6478                continue;
6479            }
6480            resolveInfos.remove(i);
6481        }
6482        return resolveInfos;
6483    }
6484
6485    /**
6486     * @param resolveInfos list of resolve infos in descending priority order
6487     * @return if the list contains a resolve info with non-negative priority
6488     */
6489    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6490        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6491    }
6492
6493    private static boolean hasWebURI(Intent intent) {
6494        if (intent.getData() == null) {
6495            return false;
6496        }
6497        final String scheme = intent.getScheme();
6498        if (TextUtils.isEmpty(scheme)) {
6499            return false;
6500        }
6501        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6502    }
6503
6504    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6505            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6506            int userId) {
6507        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6508
6509        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6510            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6511                    candidates.size());
6512        }
6513
6514        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6515        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6516        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6517        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6518        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6519        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6520
6521        synchronized (mPackages) {
6522            final int count = candidates.size();
6523            // First, try to use linked apps. Partition the candidates into four lists:
6524            // one for the final results, one for the "do not use ever", one for "undefined status"
6525            // and finally one for "browser app type".
6526            for (int n=0; n<count; n++) {
6527                ResolveInfo info = candidates.get(n);
6528                String packageName = info.activityInfo.packageName;
6529                PackageSetting ps = mSettings.mPackages.get(packageName);
6530                if (ps != null) {
6531                    // Add to the special match all list (Browser use case)
6532                    if (info.handleAllWebDataURI) {
6533                        matchAllList.add(info);
6534                        continue;
6535                    }
6536                    // Try to get the status from User settings first
6537                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6538                    int status = (int)(packedStatus >> 32);
6539                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6540                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6541                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6542                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6543                                    + " : linkgen=" + linkGeneration);
6544                        }
6545                        // Use link-enabled generation as preferredOrder, i.e.
6546                        // prefer newly-enabled over earlier-enabled.
6547                        info.preferredOrder = linkGeneration;
6548                        alwaysList.add(info);
6549                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6550                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6551                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6552                        }
6553                        neverList.add(info);
6554                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6555                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6556                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6557                        }
6558                        alwaysAskList.add(info);
6559                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6560                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6561                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6562                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6563                        }
6564                        undefinedList.add(info);
6565                    }
6566                }
6567            }
6568
6569            // We'll want to include browser possibilities in a few cases
6570            boolean includeBrowser = false;
6571
6572            // First try to add the "always" resolution(s) for the current user, if any
6573            if (alwaysList.size() > 0) {
6574                result.addAll(alwaysList);
6575            } else {
6576                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6577                result.addAll(undefinedList);
6578                // Maybe add one for the other profile.
6579                if (xpDomainInfo != null && (
6580                        xpDomainInfo.bestDomainVerificationStatus
6581                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6582                    result.add(xpDomainInfo.resolveInfo);
6583                }
6584                includeBrowser = true;
6585            }
6586
6587            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6588            // If there were 'always' entries their preferred order has been set, so we also
6589            // back that off to make the alternatives equivalent
6590            if (alwaysAskList.size() > 0) {
6591                for (ResolveInfo i : result) {
6592                    i.preferredOrder = 0;
6593                }
6594                result.addAll(alwaysAskList);
6595                includeBrowser = true;
6596            }
6597
6598            if (includeBrowser) {
6599                // Also add browsers (all of them or only the default one)
6600                if (DEBUG_DOMAIN_VERIFICATION) {
6601                    Slog.v(TAG, "   ...including browsers in candidate set");
6602                }
6603                if ((matchFlags & MATCH_ALL) != 0) {
6604                    result.addAll(matchAllList);
6605                } else {
6606                    // Browser/generic handling case.  If there's a default browser, go straight
6607                    // to that (but only if there is no other higher-priority match).
6608                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6609                    int maxMatchPrio = 0;
6610                    ResolveInfo defaultBrowserMatch = null;
6611                    final int numCandidates = matchAllList.size();
6612                    for (int n = 0; n < numCandidates; n++) {
6613                        ResolveInfo info = matchAllList.get(n);
6614                        // track the highest overall match priority...
6615                        if (info.priority > maxMatchPrio) {
6616                            maxMatchPrio = info.priority;
6617                        }
6618                        // ...and the highest-priority default browser match
6619                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6620                            if (defaultBrowserMatch == null
6621                                    || (defaultBrowserMatch.priority < info.priority)) {
6622                                if (debug) {
6623                                    Slog.v(TAG, "Considering default browser match " + info);
6624                                }
6625                                defaultBrowserMatch = info;
6626                            }
6627                        }
6628                    }
6629                    if (defaultBrowserMatch != null
6630                            && defaultBrowserMatch.priority >= maxMatchPrio
6631                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6632                    {
6633                        if (debug) {
6634                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6635                        }
6636                        result.add(defaultBrowserMatch);
6637                    } else {
6638                        result.addAll(matchAllList);
6639                    }
6640                }
6641
6642                // If there is nothing selected, add all candidates and remove the ones that the user
6643                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6644                if (result.size() == 0) {
6645                    result.addAll(candidates);
6646                    result.removeAll(neverList);
6647                }
6648            }
6649        }
6650        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6651            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6652                    result.size());
6653            for (ResolveInfo info : result) {
6654                Slog.v(TAG, "  + " + info.activityInfo);
6655            }
6656        }
6657        return result;
6658    }
6659
6660    // Returns a packed value as a long:
6661    //
6662    // high 'int'-sized word: link status: undefined/ask/never/always.
6663    // low 'int'-sized word: relative priority among 'always' results.
6664    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6665        long result = ps.getDomainVerificationStatusForUser(userId);
6666        // if none available, get the master status
6667        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6668            if (ps.getIntentFilterVerificationInfo() != null) {
6669                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6670            }
6671        }
6672        return result;
6673    }
6674
6675    private ResolveInfo querySkipCurrentProfileIntents(
6676            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6677            int flags, int sourceUserId) {
6678        if (matchingFilters != null) {
6679            int size = matchingFilters.size();
6680            for (int i = 0; i < size; i ++) {
6681                CrossProfileIntentFilter filter = matchingFilters.get(i);
6682                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6683                    // Checking if there are activities in the target user that can handle the
6684                    // intent.
6685                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6686                            resolvedType, flags, sourceUserId);
6687                    if (resolveInfo != null) {
6688                        return resolveInfo;
6689                    }
6690                }
6691            }
6692        }
6693        return null;
6694    }
6695
6696    // Return matching ResolveInfo in target user if any.
6697    private ResolveInfo queryCrossProfileIntents(
6698            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6699            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6700        if (matchingFilters != null) {
6701            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6702            // match the same intent. For performance reasons, it is better not to
6703            // run queryIntent twice for the same userId
6704            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6705            int size = matchingFilters.size();
6706            for (int i = 0; i < size; i++) {
6707                CrossProfileIntentFilter filter = matchingFilters.get(i);
6708                int targetUserId = filter.getTargetUserId();
6709                boolean skipCurrentProfile =
6710                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6711                boolean skipCurrentProfileIfNoMatchFound =
6712                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6713                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6714                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6715                    // Checking if there are activities in the target user that can handle the
6716                    // intent.
6717                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6718                            resolvedType, flags, sourceUserId);
6719                    if (resolveInfo != null) return resolveInfo;
6720                    alreadyTriedUserIds.put(targetUserId, true);
6721                }
6722            }
6723        }
6724        return null;
6725    }
6726
6727    /**
6728     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6729     * will forward the intent to the filter's target user.
6730     * Otherwise, returns null.
6731     */
6732    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6733            String resolvedType, int flags, int sourceUserId) {
6734        int targetUserId = filter.getTargetUserId();
6735        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6736                resolvedType, flags, targetUserId);
6737        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6738            // If all the matches in the target profile are suspended, return null.
6739            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6740                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6741                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6742                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6743                            targetUserId);
6744                }
6745            }
6746        }
6747        return null;
6748    }
6749
6750    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6751            int sourceUserId, int targetUserId) {
6752        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6753        long ident = Binder.clearCallingIdentity();
6754        boolean targetIsProfile;
6755        try {
6756            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6757        } finally {
6758            Binder.restoreCallingIdentity(ident);
6759        }
6760        String className;
6761        if (targetIsProfile) {
6762            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6763        } else {
6764            className = FORWARD_INTENT_TO_PARENT;
6765        }
6766        ComponentName forwardingActivityComponentName = new ComponentName(
6767                mAndroidApplication.packageName, className);
6768        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6769                sourceUserId);
6770        if (!targetIsProfile) {
6771            forwardingActivityInfo.showUserIcon = targetUserId;
6772            forwardingResolveInfo.noResourceId = true;
6773        }
6774        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6775        forwardingResolveInfo.priority = 0;
6776        forwardingResolveInfo.preferredOrder = 0;
6777        forwardingResolveInfo.match = 0;
6778        forwardingResolveInfo.isDefault = true;
6779        forwardingResolveInfo.filter = filter;
6780        forwardingResolveInfo.targetUserId = targetUserId;
6781        return forwardingResolveInfo;
6782    }
6783
6784    @Override
6785    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6786            Intent[] specifics, String[] specificTypes, Intent intent,
6787            String resolvedType, int flags, int userId) {
6788        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6789                specificTypes, intent, resolvedType, flags, userId));
6790    }
6791
6792    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6793            Intent[] specifics, String[] specificTypes, Intent intent,
6794            String resolvedType, int flags, int userId) {
6795        if (!sUserManager.exists(userId)) return Collections.emptyList();
6796        flags = updateFlagsForResolve(flags, userId, intent, false);
6797        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6798                false /* requireFullPermission */, false /* checkShell */,
6799                "query intent activity options");
6800        final String resultsAction = intent.getAction();
6801
6802        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6803                | PackageManager.GET_RESOLVED_FILTER, userId);
6804
6805        if (DEBUG_INTENT_MATCHING) {
6806            Log.v(TAG, "Query " + intent + ": " + results);
6807        }
6808
6809        int specificsPos = 0;
6810        int N;
6811
6812        // todo: note that the algorithm used here is O(N^2).  This
6813        // isn't a problem in our current environment, but if we start running
6814        // into situations where we have more than 5 or 10 matches then this
6815        // should probably be changed to something smarter...
6816
6817        // First we go through and resolve each of the specific items
6818        // that were supplied, taking care of removing any corresponding
6819        // duplicate items in the generic resolve list.
6820        if (specifics != null) {
6821            for (int i=0; i<specifics.length; i++) {
6822                final Intent sintent = specifics[i];
6823                if (sintent == null) {
6824                    continue;
6825                }
6826
6827                if (DEBUG_INTENT_MATCHING) {
6828                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6829                }
6830
6831                String action = sintent.getAction();
6832                if (resultsAction != null && resultsAction.equals(action)) {
6833                    // If this action was explicitly requested, then don't
6834                    // remove things that have it.
6835                    action = null;
6836                }
6837
6838                ResolveInfo ri = null;
6839                ActivityInfo ai = null;
6840
6841                ComponentName comp = sintent.getComponent();
6842                if (comp == null) {
6843                    ri = resolveIntent(
6844                        sintent,
6845                        specificTypes != null ? specificTypes[i] : null,
6846                            flags, userId);
6847                    if (ri == null) {
6848                        continue;
6849                    }
6850                    if (ri == mResolveInfo) {
6851                        // ACK!  Must do something better with this.
6852                    }
6853                    ai = ri.activityInfo;
6854                    comp = new ComponentName(ai.applicationInfo.packageName,
6855                            ai.name);
6856                } else {
6857                    ai = getActivityInfo(comp, flags, userId);
6858                    if (ai == null) {
6859                        continue;
6860                    }
6861                }
6862
6863                // Look for any generic query activities that are duplicates
6864                // of this specific one, and remove them from the results.
6865                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6866                N = results.size();
6867                int j;
6868                for (j=specificsPos; j<N; j++) {
6869                    ResolveInfo sri = results.get(j);
6870                    if ((sri.activityInfo.name.equals(comp.getClassName())
6871                            && sri.activityInfo.applicationInfo.packageName.equals(
6872                                    comp.getPackageName()))
6873                        || (action != null && sri.filter.matchAction(action))) {
6874                        results.remove(j);
6875                        if (DEBUG_INTENT_MATCHING) Log.v(
6876                            TAG, "Removing duplicate item from " + j
6877                            + " due to specific " + specificsPos);
6878                        if (ri == null) {
6879                            ri = sri;
6880                        }
6881                        j--;
6882                        N--;
6883                    }
6884                }
6885
6886                // Add this specific item to its proper place.
6887                if (ri == null) {
6888                    ri = new ResolveInfo();
6889                    ri.activityInfo = ai;
6890                }
6891                results.add(specificsPos, ri);
6892                ri.specificIndex = i;
6893                specificsPos++;
6894            }
6895        }
6896
6897        // Now we go through the remaining generic results and remove any
6898        // duplicate actions that are found here.
6899        N = results.size();
6900        for (int i=specificsPos; i<N-1; i++) {
6901            final ResolveInfo rii = results.get(i);
6902            if (rii.filter == null) {
6903                continue;
6904            }
6905
6906            // Iterate over all of the actions of this result's intent
6907            // filter...  typically this should be just one.
6908            final Iterator<String> it = rii.filter.actionsIterator();
6909            if (it == null) {
6910                continue;
6911            }
6912            while (it.hasNext()) {
6913                final String action = it.next();
6914                if (resultsAction != null && resultsAction.equals(action)) {
6915                    // If this action was explicitly requested, then don't
6916                    // remove things that have it.
6917                    continue;
6918                }
6919                for (int j=i+1; j<N; j++) {
6920                    final ResolveInfo rij = results.get(j);
6921                    if (rij.filter != null && rij.filter.hasAction(action)) {
6922                        results.remove(j);
6923                        if (DEBUG_INTENT_MATCHING) Log.v(
6924                            TAG, "Removing duplicate item from " + j
6925                            + " due to action " + action + " at " + i);
6926                        j--;
6927                        N--;
6928                    }
6929                }
6930            }
6931
6932            // If the caller didn't request filter information, drop it now
6933            // so we don't have to marshall/unmarshall it.
6934            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6935                rii.filter = null;
6936            }
6937        }
6938
6939        // Filter out the caller activity if so requested.
6940        if (caller != null) {
6941            N = results.size();
6942            for (int i=0; i<N; i++) {
6943                ActivityInfo ainfo = results.get(i).activityInfo;
6944                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6945                        && caller.getClassName().equals(ainfo.name)) {
6946                    results.remove(i);
6947                    break;
6948                }
6949            }
6950        }
6951
6952        // If the caller didn't request filter information,
6953        // drop them now so we don't have to
6954        // marshall/unmarshall it.
6955        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6956            N = results.size();
6957            for (int i=0; i<N; i++) {
6958                results.get(i).filter = null;
6959            }
6960        }
6961
6962        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6963        return results;
6964    }
6965
6966    @Override
6967    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6968            String resolvedType, int flags, int userId) {
6969        return new ParceledListSlice<>(
6970                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6971    }
6972
6973    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6974            String resolvedType, int flags, int userId) {
6975        if (!sUserManager.exists(userId)) return Collections.emptyList();
6976        flags = updateFlagsForResolve(flags, userId, intent, false);
6977        ComponentName comp = intent.getComponent();
6978        if (comp == null) {
6979            if (intent.getSelector() != null) {
6980                intent = intent.getSelector();
6981                comp = intent.getComponent();
6982            }
6983        }
6984        if (comp != null) {
6985            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6986            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6987            if (ai != null) {
6988                ResolveInfo ri = new ResolveInfo();
6989                ri.activityInfo = ai;
6990                list.add(ri);
6991            }
6992            return list;
6993        }
6994
6995        // reader
6996        synchronized (mPackages) {
6997            String pkgName = intent.getPackage();
6998            if (pkgName == null) {
6999                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7000            }
7001            final PackageParser.Package pkg = mPackages.get(pkgName);
7002            if (pkg != null) {
7003                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7004                        userId);
7005            }
7006            return Collections.emptyList();
7007        }
7008    }
7009
7010    @Override
7011    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7012        if (!sUserManager.exists(userId)) return null;
7013        flags = updateFlagsForResolve(flags, userId, intent, false);
7014        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
7015        if (query != null) {
7016            if (query.size() >= 1) {
7017                // If there is more than one service with the same priority,
7018                // just arbitrarily pick the first one.
7019                return query.get(0);
7020            }
7021        }
7022        return null;
7023    }
7024
7025    @Override
7026    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7027            String resolvedType, int flags, int userId) {
7028        return new ParceledListSlice<>(
7029                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7030    }
7031
7032    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7033            String resolvedType, int flags, int userId) {
7034        if (!sUserManager.exists(userId)) return Collections.emptyList();
7035        flags = updateFlagsForResolve(flags, userId, intent, false);
7036        ComponentName comp = intent.getComponent();
7037        if (comp == null) {
7038            if (intent.getSelector() != null) {
7039                intent = intent.getSelector();
7040                comp = intent.getComponent();
7041            }
7042        }
7043        if (comp != null) {
7044            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7045            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7046            if (si != null) {
7047                final ResolveInfo ri = new ResolveInfo();
7048                ri.serviceInfo = si;
7049                list.add(ri);
7050            }
7051            return list;
7052        }
7053
7054        // reader
7055        synchronized (mPackages) {
7056            String pkgName = intent.getPackage();
7057            if (pkgName == null) {
7058                return mServices.queryIntent(intent, resolvedType, flags, userId);
7059            }
7060            final PackageParser.Package pkg = mPackages.get(pkgName);
7061            if (pkg != null) {
7062                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7063                        userId);
7064            }
7065            return Collections.emptyList();
7066        }
7067    }
7068
7069    @Override
7070    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7071            String resolvedType, int flags, int userId) {
7072        return new ParceledListSlice<>(
7073                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7074    }
7075
7076    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7077            Intent intent, String resolvedType, int flags, int userId) {
7078        if (!sUserManager.exists(userId)) return Collections.emptyList();
7079        flags = updateFlagsForResolve(flags, userId, intent, false);
7080        ComponentName comp = intent.getComponent();
7081        if (comp == null) {
7082            if (intent.getSelector() != null) {
7083                intent = intent.getSelector();
7084                comp = intent.getComponent();
7085            }
7086        }
7087        if (comp != null) {
7088            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7089            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7090            if (pi != null) {
7091                final ResolveInfo ri = new ResolveInfo();
7092                ri.providerInfo = pi;
7093                list.add(ri);
7094            }
7095            return list;
7096        }
7097
7098        // reader
7099        synchronized (mPackages) {
7100            String pkgName = intent.getPackage();
7101            if (pkgName == null) {
7102                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7103            }
7104            final PackageParser.Package pkg = mPackages.get(pkgName);
7105            if (pkg != null) {
7106                return mProviders.queryIntentForPackage(
7107                        intent, resolvedType, flags, pkg.providers, userId);
7108            }
7109            return Collections.emptyList();
7110        }
7111    }
7112
7113    @Override
7114    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7115        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7116        flags = updateFlagsForPackage(flags, userId, null);
7117        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7118        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7119                true /* requireFullPermission */, false /* checkShell */,
7120                "get installed packages");
7121
7122        // writer
7123        synchronized (mPackages) {
7124            ArrayList<PackageInfo> list;
7125            if (listUninstalled) {
7126                list = new ArrayList<>(mSettings.mPackages.size());
7127                for (PackageSetting ps : mSettings.mPackages.values()) {
7128                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7129                        continue;
7130                    }
7131                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7132                    if (pi != null) {
7133                        list.add(pi);
7134                    }
7135                }
7136            } else {
7137                list = new ArrayList<>(mPackages.size());
7138                for (PackageParser.Package p : mPackages.values()) {
7139                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7140                            Binder.getCallingUid(), userId)) {
7141                        continue;
7142                    }
7143                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7144                            p.mExtras, flags, userId);
7145                    if (pi != null) {
7146                        list.add(pi);
7147                    }
7148                }
7149            }
7150
7151            return new ParceledListSlice<>(list);
7152        }
7153    }
7154
7155    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7156            String[] permissions, boolean[] tmp, int flags, int userId) {
7157        int numMatch = 0;
7158        final PermissionsState permissionsState = ps.getPermissionsState();
7159        for (int i=0; i<permissions.length; i++) {
7160            final String permission = permissions[i];
7161            if (permissionsState.hasPermission(permission, userId)) {
7162                tmp[i] = true;
7163                numMatch++;
7164            } else {
7165                tmp[i] = false;
7166            }
7167        }
7168        if (numMatch == 0) {
7169            return;
7170        }
7171        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7172
7173        // The above might return null in cases of uninstalled apps or install-state
7174        // skew across users/profiles.
7175        if (pi != null) {
7176            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7177                if (numMatch == permissions.length) {
7178                    pi.requestedPermissions = permissions;
7179                } else {
7180                    pi.requestedPermissions = new String[numMatch];
7181                    numMatch = 0;
7182                    for (int i=0; i<permissions.length; i++) {
7183                        if (tmp[i]) {
7184                            pi.requestedPermissions[numMatch] = permissions[i];
7185                            numMatch++;
7186                        }
7187                    }
7188                }
7189            }
7190            list.add(pi);
7191        }
7192    }
7193
7194    @Override
7195    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7196            String[] permissions, int flags, int userId) {
7197        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7198        flags = updateFlagsForPackage(flags, userId, permissions);
7199        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7200                true /* requireFullPermission */, false /* checkShell */,
7201                "get packages holding permissions");
7202        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7203
7204        // writer
7205        synchronized (mPackages) {
7206            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7207            boolean[] tmpBools = new boolean[permissions.length];
7208            if (listUninstalled) {
7209                for (PackageSetting ps : mSettings.mPackages.values()) {
7210                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7211                            userId);
7212                }
7213            } else {
7214                for (PackageParser.Package pkg : mPackages.values()) {
7215                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7216                    if (ps != null) {
7217                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7218                                userId);
7219                    }
7220                }
7221            }
7222
7223            return new ParceledListSlice<PackageInfo>(list);
7224        }
7225    }
7226
7227    @Override
7228    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7229        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7230        flags = updateFlagsForApplication(flags, userId, null);
7231        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7232
7233        // writer
7234        synchronized (mPackages) {
7235            ArrayList<ApplicationInfo> list;
7236            if (listUninstalled) {
7237                list = new ArrayList<>(mSettings.mPackages.size());
7238                for (PackageSetting ps : mSettings.mPackages.values()) {
7239                    ApplicationInfo ai;
7240                    int effectiveFlags = flags;
7241                    if (ps.isSystem()) {
7242                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7243                    }
7244                    if (ps.pkg != null) {
7245                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7246                            continue;
7247                        }
7248                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7249                                ps.readUserState(userId), userId);
7250                        if (ai != null) {
7251                            rebaseEnabledOverlays(ai, userId);
7252                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7253                        }
7254                    } else {
7255                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7256                        // and already converts to externally visible package name
7257                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7258                                Binder.getCallingUid(), effectiveFlags, userId);
7259                    }
7260                    if (ai != null) {
7261                        list.add(ai);
7262                    }
7263                }
7264            } else {
7265                list = new ArrayList<>(mPackages.size());
7266                for (PackageParser.Package p : mPackages.values()) {
7267                    if (p.mExtras != null) {
7268                        PackageSetting ps = (PackageSetting) p.mExtras;
7269                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7270                            continue;
7271                        }
7272                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7273                                ps.readUserState(userId), userId);
7274                        if (ai != null) {
7275                            rebaseEnabledOverlays(ai, userId);
7276                            ai.packageName = resolveExternalPackageNameLPr(p);
7277                            list.add(ai);
7278                        }
7279                    }
7280                }
7281            }
7282
7283            return new ParceledListSlice<>(list);
7284        }
7285    }
7286
7287    @Override
7288    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7289        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7290            return null;
7291        }
7292
7293        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7294                "getEphemeralApplications");
7295        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7296                true /* requireFullPermission */, false /* checkShell */,
7297                "getEphemeralApplications");
7298        synchronized (mPackages) {
7299            List<InstantAppInfo> instantApps = mInstantAppRegistry
7300                    .getInstantAppsLPr(userId);
7301            if (instantApps != null) {
7302                return new ParceledListSlice<>(instantApps);
7303            }
7304        }
7305        return null;
7306    }
7307
7308    @Override
7309    public boolean isInstantApp(String packageName, int userId) {
7310        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7311                true /* requireFullPermission */, false /* checkShell */,
7312                "isInstantApp");
7313        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7314            return false;
7315        }
7316
7317        synchronized (mPackages) {
7318            final PackageSetting ps = mSettings.mPackages.get(packageName);
7319            final boolean returnAllowed =
7320                    ps != null
7321                    && (isCallerSameApp(packageName)
7322                            || mContext.checkCallingOrSelfPermission(
7323                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7324                                            == PERMISSION_GRANTED
7325                            || mInstantAppRegistry.isInstantAccessGranted(
7326                                    userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId));
7327            if (returnAllowed) {
7328                return ps.getInstantApp(userId);
7329            }
7330        }
7331        return false;
7332    }
7333
7334    @Override
7335    public byte[] getInstantAppCookie(String packageName, int userId) {
7336        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7337            return null;
7338        }
7339
7340        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7341                true /* requireFullPermission */, false /* checkShell */,
7342                "getInstantAppCookie");
7343        if (!isCallerSameApp(packageName)) {
7344            return null;
7345        }
7346        synchronized (mPackages) {
7347            return mInstantAppRegistry.getInstantAppCookieLPw(
7348                    packageName, userId);
7349        }
7350    }
7351
7352    @Override
7353    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7354        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7355            return true;
7356        }
7357
7358        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7359                true /* requireFullPermission */, true /* checkShell */,
7360                "setInstantAppCookie");
7361        if (!isCallerSameApp(packageName)) {
7362            return false;
7363        }
7364        synchronized (mPackages) {
7365            return mInstantAppRegistry.setInstantAppCookieLPw(
7366                    packageName, cookie, userId);
7367        }
7368    }
7369
7370    @Override
7371    public Bitmap getInstantAppIcon(String packageName, int userId) {
7372        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7373            return null;
7374        }
7375
7376        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7377                "getInstantAppIcon");
7378
7379        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7380                true /* requireFullPermission */, false /* checkShell */,
7381                "getInstantAppIcon");
7382
7383        synchronized (mPackages) {
7384            return mInstantAppRegistry.getInstantAppIconLPw(
7385                    packageName, userId);
7386        }
7387    }
7388
7389    private boolean isCallerSameApp(String packageName) {
7390        PackageParser.Package pkg = mPackages.get(packageName);
7391        return pkg != null
7392                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7393    }
7394
7395    @Override
7396    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7397        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7398    }
7399
7400    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7401        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7402
7403        // reader
7404        synchronized (mPackages) {
7405            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7406            final int userId = UserHandle.getCallingUserId();
7407            while (i.hasNext()) {
7408                final PackageParser.Package p = i.next();
7409                if (p.applicationInfo == null) continue;
7410
7411                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7412                        && !p.applicationInfo.isDirectBootAware();
7413                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7414                        && p.applicationInfo.isDirectBootAware();
7415
7416                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7417                        && (!mSafeMode || isSystemApp(p))
7418                        && (matchesUnaware || matchesAware)) {
7419                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7420                    if (ps != null) {
7421                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7422                                ps.readUserState(userId), userId);
7423                        if (ai != null) {
7424                            rebaseEnabledOverlays(ai, userId);
7425                            finalList.add(ai);
7426                        }
7427                    }
7428                }
7429            }
7430        }
7431
7432        return finalList;
7433    }
7434
7435    @Override
7436    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7437        if (!sUserManager.exists(userId)) return null;
7438        flags = updateFlagsForComponent(flags, userId, name);
7439        // reader
7440        synchronized (mPackages) {
7441            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7442            PackageSetting ps = provider != null
7443                    ? mSettings.mPackages.get(provider.owner.packageName)
7444                    : null;
7445            return ps != null
7446                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7447                    ? PackageParser.generateProviderInfo(provider, flags,
7448                            ps.readUserState(userId), userId)
7449                    : null;
7450        }
7451    }
7452
7453    /**
7454     * @deprecated
7455     */
7456    @Deprecated
7457    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7458        // reader
7459        synchronized (mPackages) {
7460            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7461                    .entrySet().iterator();
7462            final int userId = UserHandle.getCallingUserId();
7463            while (i.hasNext()) {
7464                Map.Entry<String, PackageParser.Provider> entry = i.next();
7465                PackageParser.Provider p = entry.getValue();
7466                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7467
7468                if (ps != null && p.syncable
7469                        && (!mSafeMode || (p.info.applicationInfo.flags
7470                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7471                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7472                            ps.readUserState(userId), userId);
7473                    if (info != null) {
7474                        outNames.add(entry.getKey());
7475                        outInfo.add(info);
7476                    }
7477                }
7478            }
7479        }
7480    }
7481
7482    @Override
7483    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7484            int uid, int flags, String metaDataKey) {
7485        final int userId = processName != null ? UserHandle.getUserId(uid)
7486                : UserHandle.getCallingUserId();
7487        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7488        flags = updateFlagsForComponent(flags, userId, processName);
7489
7490        ArrayList<ProviderInfo> finalList = null;
7491        // reader
7492        synchronized (mPackages) {
7493            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7494            while (i.hasNext()) {
7495                final PackageParser.Provider p = i.next();
7496                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7497                if (ps != null && p.info.authority != null
7498                        && (processName == null
7499                                || (p.info.processName.equals(processName)
7500                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7501                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7502
7503                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7504                    // parameter.
7505                    if (metaDataKey != null
7506                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7507                        continue;
7508                    }
7509
7510                    if (finalList == null) {
7511                        finalList = new ArrayList<ProviderInfo>(3);
7512                    }
7513                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7514                            ps.readUserState(userId), userId);
7515                    if (info != null) {
7516                        finalList.add(info);
7517                    }
7518                }
7519            }
7520        }
7521
7522        if (finalList != null) {
7523            Collections.sort(finalList, mProviderInitOrderSorter);
7524            return new ParceledListSlice<ProviderInfo>(finalList);
7525        }
7526
7527        return ParceledListSlice.emptyList();
7528    }
7529
7530    @Override
7531    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7532        // reader
7533        synchronized (mPackages) {
7534            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7535            return PackageParser.generateInstrumentationInfo(i, flags);
7536        }
7537    }
7538
7539    @Override
7540    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7541            String targetPackage, int flags) {
7542        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7543    }
7544
7545    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7546            int flags) {
7547        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7548
7549        // reader
7550        synchronized (mPackages) {
7551            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7552            while (i.hasNext()) {
7553                final PackageParser.Instrumentation p = i.next();
7554                if (targetPackage == null
7555                        || targetPackage.equals(p.info.targetPackage)) {
7556                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7557                            flags);
7558                    if (ii != null) {
7559                        finalList.add(ii);
7560                    }
7561                }
7562            }
7563        }
7564
7565        return finalList;
7566    }
7567
7568    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7569        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7570        try {
7571            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7572        } finally {
7573            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7574        }
7575    }
7576
7577    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7578        final File[] files = dir.listFiles();
7579        if (ArrayUtils.isEmpty(files)) {
7580            Log.d(TAG, "No files in app dir " + dir);
7581            return;
7582        }
7583
7584        if (DEBUG_PACKAGE_SCANNING) {
7585            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7586                    + " flags=0x" + Integer.toHexString(parseFlags));
7587        }
7588        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7589                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7590
7591        // Submit files for parsing in parallel
7592        int fileCount = 0;
7593        for (File file : files) {
7594            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7595                    && !PackageInstallerService.isStageName(file.getName());
7596            if (!isPackage) {
7597                // Ignore entries which are not packages
7598                continue;
7599            }
7600            parallelPackageParser.submit(file, parseFlags);
7601            fileCount++;
7602        }
7603
7604        // Process results one by one
7605        for (; fileCount > 0; fileCount--) {
7606            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7607            Throwable throwable = parseResult.throwable;
7608            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7609
7610            if (throwable == null) {
7611                // Static shared libraries have synthetic package names
7612                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7613                    renameStaticSharedLibraryPackage(parseResult.pkg);
7614                }
7615                try {
7616                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7617                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7618                                currentTime, null);
7619                    }
7620                } catch (PackageManagerException e) {
7621                    errorCode = e.error;
7622                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7623                }
7624            } else if (throwable instanceof PackageParser.PackageParserException) {
7625                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7626                        throwable;
7627                errorCode = e.error;
7628                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7629            } else {
7630                throw new IllegalStateException("Unexpected exception occurred while parsing "
7631                        + parseResult.scanFile, throwable);
7632            }
7633
7634            // Delete invalid userdata apps
7635            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7636                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7637                logCriticalInfo(Log.WARN,
7638                        "Deleting invalid package at " + parseResult.scanFile);
7639                removeCodePathLI(parseResult.scanFile);
7640            }
7641        }
7642        parallelPackageParser.close();
7643    }
7644
7645    private static File getSettingsProblemFile() {
7646        File dataDir = Environment.getDataDirectory();
7647        File systemDir = new File(dataDir, "system");
7648        File fname = new File(systemDir, "uiderrors.txt");
7649        return fname;
7650    }
7651
7652    static void reportSettingsProblem(int priority, String msg) {
7653        logCriticalInfo(priority, msg);
7654    }
7655
7656    public static void logCriticalInfo(int priority, String msg) {
7657        Slog.println(priority, TAG, msg);
7658        EventLogTags.writePmCriticalInfo(msg);
7659        try {
7660            File fname = getSettingsProblemFile();
7661            FileOutputStream out = new FileOutputStream(fname, true);
7662            PrintWriter pw = new FastPrintWriter(out);
7663            SimpleDateFormat formatter = new SimpleDateFormat();
7664            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7665            pw.println(dateString + ": " + msg);
7666            pw.close();
7667            FileUtils.setPermissions(
7668                    fname.toString(),
7669                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7670                    -1, -1);
7671        } catch (java.io.IOException e) {
7672        }
7673    }
7674
7675    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7676        if (srcFile.isDirectory()) {
7677            final File baseFile = new File(pkg.baseCodePath);
7678            long maxModifiedTime = baseFile.lastModified();
7679            if (pkg.splitCodePaths != null) {
7680                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7681                    final File splitFile = new File(pkg.splitCodePaths[i]);
7682                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7683                }
7684            }
7685            return maxModifiedTime;
7686        }
7687        return srcFile.lastModified();
7688    }
7689
7690    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7691            final int policyFlags) throws PackageManagerException {
7692        // When upgrading from pre-N MR1, verify the package time stamp using the package
7693        // directory and not the APK file.
7694        final long lastModifiedTime = mIsPreNMR1Upgrade
7695                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7696        if (ps != null
7697                && ps.codePath.equals(srcFile)
7698                && ps.timeStamp == lastModifiedTime
7699                && !isCompatSignatureUpdateNeeded(pkg)
7700                && !isRecoverSignatureUpdateNeeded(pkg)) {
7701            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7702            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7703            ArraySet<PublicKey> signingKs;
7704            synchronized (mPackages) {
7705                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7706            }
7707            if (ps.signatures.mSignatures != null
7708                    && ps.signatures.mSignatures.length != 0
7709                    && signingKs != null) {
7710                // Optimization: reuse the existing cached certificates
7711                // if the package appears to be unchanged.
7712                pkg.mSignatures = ps.signatures.mSignatures;
7713                pkg.mSigningKeys = signingKs;
7714                return;
7715            }
7716
7717            Slog.w(TAG, "PackageSetting for " + ps.name
7718                    + " is missing signatures.  Collecting certs again to recover them.");
7719        } else {
7720            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7721        }
7722
7723        try {
7724            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7725            PackageParser.collectCertificates(pkg, policyFlags);
7726        } catch (PackageParserException e) {
7727            throw PackageManagerException.from(e);
7728        } finally {
7729            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7730        }
7731    }
7732
7733    /**
7734     *  Traces a package scan.
7735     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7736     */
7737    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7738            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7739        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7740        try {
7741            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7742        } finally {
7743            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7744        }
7745    }
7746
7747    /**
7748     *  Scans a package and returns the newly parsed package.
7749     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7750     */
7751    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7752            long currentTime, UserHandle user) throws PackageManagerException {
7753        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7754        PackageParser pp = new PackageParser();
7755        pp.setSeparateProcesses(mSeparateProcesses);
7756        pp.setOnlyCoreApps(mOnlyCore);
7757        pp.setDisplayMetrics(mMetrics);
7758        pp.setCallback(mPackageParserCallback);
7759
7760        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7761            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7762        }
7763
7764        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7765        final PackageParser.Package pkg;
7766        try {
7767            pkg = pp.parsePackage(scanFile, parseFlags);
7768        } catch (PackageParserException e) {
7769            throw PackageManagerException.from(e);
7770        } finally {
7771            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7772        }
7773
7774        // Static shared libraries have synthetic package names
7775        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7776            renameStaticSharedLibraryPackage(pkg);
7777        }
7778
7779        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7780    }
7781
7782    /**
7783     *  Scans a package and returns the newly parsed package.
7784     *  @throws PackageManagerException on a parse error.
7785     */
7786    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7787            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7788            throws PackageManagerException {
7789        // If the package has children and this is the first dive in the function
7790        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7791        // packages (parent and children) would be successfully scanned before the
7792        // actual scan since scanning mutates internal state and we want to atomically
7793        // install the package and its children.
7794        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7795            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7796                scanFlags |= SCAN_CHECK_ONLY;
7797            }
7798        } else {
7799            scanFlags &= ~SCAN_CHECK_ONLY;
7800        }
7801
7802        // Scan the parent
7803        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7804                scanFlags, currentTime, user);
7805
7806        // Scan the children
7807        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7808        for (int i = 0; i < childCount; i++) {
7809            PackageParser.Package childPackage = pkg.childPackages.get(i);
7810            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7811                    currentTime, user);
7812        }
7813
7814
7815        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7816            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7817        }
7818
7819        return scannedPkg;
7820    }
7821
7822    /**
7823     *  Scans a package and returns the newly parsed package.
7824     *  @throws PackageManagerException on a parse error.
7825     */
7826    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7827            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7828            throws PackageManagerException {
7829        PackageSetting ps = null;
7830        PackageSetting updatedPkg;
7831        // reader
7832        synchronized (mPackages) {
7833            // Look to see if we already know about this package.
7834            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7835            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7836                // This package has been renamed to its original name.  Let's
7837                // use that.
7838                ps = mSettings.getPackageLPr(oldName);
7839            }
7840            // If there was no original package, see one for the real package name.
7841            if (ps == null) {
7842                ps = mSettings.getPackageLPr(pkg.packageName);
7843            }
7844            // Check to see if this package could be hiding/updating a system
7845            // package.  Must look for it either under the original or real
7846            // package name depending on our state.
7847            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7848            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7849
7850            // If this is a package we don't know about on the system partition, we
7851            // may need to remove disabled child packages on the system partition
7852            // or may need to not add child packages if the parent apk is updated
7853            // on the data partition and no longer defines this child package.
7854            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7855                // If this is a parent package for an updated system app and this system
7856                // app got an OTA update which no longer defines some of the child packages
7857                // we have to prune them from the disabled system packages.
7858                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7859                if (disabledPs != null) {
7860                    final int scannedChildCount = (pkg.childPackages != null)
7861                            ? pkg.childPackages.size() : 0;
7862                    final int disabledChildCount = disabledPs.childPackageNames != null
7863                            ? disabledPs.childPackageNames.size() : 0;
7864                    for (int i = 0; i < disabledChildCount; i++) {
7865                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7866                        boolean disabledPackageAvailable = false;
7867                        for (int j = 0; j < scannedChildCount; j++) {
7868                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7869                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7870                                disabledPackageAvailable = true;
7871                                break;
7872                            }
7873                         }
7874                         if (!disabledPackageAvailable) {
7875                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7876                         }
7877                    }
7878                }
7879            }
7880        }
7881
7882        boolean updatedPkgBetter = false;
7883        // First check if this is a system package that may involve an update
7884        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7885            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7886            // it needs to drop FLAG_PRIVILEGED.
7887            if (locationIsPrivileged(scanFile)) {
7888                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7889            } else {
7890                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7891            }
7892
7893            if (ps != null && !ps.codePath.equals(scanFile)) {
7894                // The path has changed from what was last scanned...  check the
7895                // version of the new path against what we have stored to determine
7896                // what to do.
7897                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7898                if (pkg.mVersionCode <= ps.versionCode) {
7899                    // The system package has been updated and the code path does not match
7900                    // Ignore entry. Skip it.
7901                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7902                            + " ignored: updated version " + ps.versionCode
7903                            + " better than this " + pkg.mVersionCode);
7904                    if (!updatedPkg.codePath.equals(scanFile)) {
7905                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7906                                + ps.name + " changing from " + updatedPkg.codePathString
7907                                + " to " + scanFile);
7908                        updatedPkg.codePath = scanFile;
7909                        updatedPkg.codePathString = scanFile.toString();
7910                        updatedPkg.resourcePath = scanFile;
7911                        updatedPkg.resourcePathString = scanFile.toString();
7912                    }
7913                    updatedPkg.pkg = pkg;
7914                    updatedPkg.versionCode = pkg.mVersionCode;
7915
7916                    // Update the disabled system child packages to point to the package too.
7917                    final int childCount = updatedPkg.childPackageNames != null
7918                            ? updatedPkg.childPackageNames.size() : 0;
7919                    for (int i = 0; i < childCount; i++) {
7920                        String childPackageName = updatedPkg.childPackageNames.get(i);
7921                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7922                                childPackageName);
7923                        if (updatedChildPkg != null) {
7924                            updatedChildPkg.pkg = pkg;
7925                            updatedChildPkg.versionCode = pkg.mVersionCode;
7926                        }
7927                    }
7928
7929                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7930                            + scanFile + " ignored: updated version " + ps.versionCode
7931                            + " better than this " + pkg.mVersionCode);
7932                } else {
7933                    // The current app on the system partition is better than
7934                    // what we have updated to on the data partition; switch
7935                    // back to the system partition version.
7936                    // At this point, its safely assumed that package installation for
7937                    // apps in system partition will go through. If not there won't be a working
7938                    // version of the app
7939                    // writer
7940                    synchronized (mPackages) {
7941                        // Just remove the loaded entries from package lists.
7942                        mPackages.remove(ps.name);
7943                    }
7944
7945                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7946                            + " reverting from " + ps.codePathString
7947                            + ": new version " + pkg.mVersionCode
7948                            + " better than installed " + ps.versionCode);
7949
7950                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7951                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7952                    synchronized (mInstallLock) {
7953                        args.cleanUpResourcesLI();
7954                    }
7955                    synchronized (mPackages) {
7956                        mSettings.enableSystemPackageLPw(ps.name);
7957                    }
7958                    updatedPkgBetter = true;
7959                }
7960            }
7961        }
7962
7963        if (updatedPkg != null) {
7964            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7965            // initially
7966            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7967
7968            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7969            // flag set initially
7970            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7971                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7972            }
7973        }
7974
7975        // Verify certificates against what was last scanned
7976        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7977
7978        /*
7979         * A new system app appeared, but we already had a non-system one of the
7980         * same name installed earlier.
7981         */
7982        boolean shouldHideSystemApp = false;
7983        if (updatedPkg == null && ps != null
7984                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7985            /*
7986             * Check to make sure the signatures match first. If they don't,
7987             * wipe the installed application and its data.
7988             */
7989            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7990                    != PackageManager.SIGNATURE_MATCH) {
7991                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7992                        + " signatures don't match existing userdata copy; removing");
7993                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7994                        "scanPackageInternalLI")) {
7995                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7996                }
7997                ps = null;
7998            } else {
7999                /*
8000                 * If the newly-added system app is an older version than the
8001                 * already installed version, hide it. It will be scanned later
8002                 * and re-added like an update.
8003                 */
8004                if (pkg.mVersionCode <= ps.versionCode) {
8005                    shouldHideSystemApp = true;
8006                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8007                            + " but new version " + pkg.mVersionCode + " better than installed "
8008                            + ps.versionCode + "; hiding system");
8009                } else {
8010                    /*
8011                     * The newly found system app is a newer version that the
8012                     * one previously installed. Simply remove the
8013                     * already-installed application and replace it with our own
8014                     * while keeping the application data.
8015                     */
8016                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8017                            + " reverting from " + ps.codePathString + ": new version "
8018                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8019                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8020                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8021                    synchronized (mInstallLock) {
8022                        args.cleanUpResourcesLI();
8023                    }
8024                }
8025            }
8026        }
8027
8028        // The apk is forward locked (not public) if its code and resources
8029        // are kept in different files. (except for app in either system or
8030        // vendor path).
8031        // TODO grab this value from PackageSettings
8032        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8033            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8034                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8035            }
8036        }
8037
8038        // TODO: extend to support forward-locked splits
8039        String resourcePath = null;
8040        String baseResourcePath = null;
8041        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8042            if (ps != null && ps.resourcePathString != null) {
8043                resourcePath = ps.resourcePathString;
8044                baseResourcePath = ps.resourcePathString;
8045            } else {
8046                // Should not happen at all. Just log an error.
8047                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8048            }
8049        } else {
8050            resourcePath = pkg.codePath;
8051            baseResourcePath = pkg.baseCodePath;
8052        }
8053
8054        // Set application objects path explicitly.
8055        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8056        pkg.setApplicationInfoCodePath(pkg.codePath);
8057        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8058        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8059        pkg.setApplicationInfoResourcePath(resourcePath);
8060        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8061        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8062
8063        final int userId = ((user == null) ? 0 : user.getIdentifier());
8064        if (ps != null && ps.getInstantApp(userId)) {
8065            scanFlags |= SCAN_AS_INSTANT_APP;
8066        }
8067
8068        // Note that we invoke the following method only if we are about to unpack an application
8069        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8070                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8071
8072        /*
8073         * If the system app should be overridden by a previously installed
8074         * data, hide the system app now and let the /data/app scan pick it up
8075         * again.
8076         */
8077        if (shouldHideSystemApp) {
8078            synchronized (mPackages) {
8079                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8080            }
8081        }
8082
8083        return scannedPkg;
8084    }
8085
8086    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8087        // Derive the new package synthetic package name
8088        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8089                + pkg.staticSharedLibVersion);
8090    }
8091
8092    private static String fixProcessName(String defProcessName,
8093            String processName) {
8094        if (processName == null) {
8095            return defProcessName;
8096        }
8097        return processName;
8098    }
8099
8100    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8101            throws PackageManagerException {
8102        if (pkgSetting.signatures.mSignatures != null) {
8103            // Already existing package. Make sure signatures match
8104            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8105                    == PackageManager.SIGNATURE_MATCH;
8106            if (!match) {
8107                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8108                        == PackageManager.SIGNATURE_MATCH;
8109            }
8110            if (!match) {
8111                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8112                        == PackageManager.SIGNATURE_MATCH;
8113            }
8114            if (!match) {
8115                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8116                        + pkg.packageName + " signatures do not match the "
8117                        + "previously installed version; ignoring!");
8118            }
8119        }
8120
8121        // Check for shared user signatures
8122        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8123            // Already existing package. Make sure signatures match
8124            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8125                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8126            if (!match) {
8127                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8128                        == PackageManager.SIGNATURE_MATCH;
8129            }
8130            if (!match) {
8131                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8132                        == PackageManager.SIGNATURE_MATCH;
8133            }
8134            if (!match) {
8135                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8136                        "Package " + pkg.packageName
8137                        + " has no signatures that match those in shared user "
8138                        + pkgSetting.sharedUser.name + "; ignoring!");
8139            }
8140        }
8141    }
8142
8143    /**
8144     * Enforces that only the system UID or root's UID can call a method exposed
8145     * via Binder.
8146     *
8147     * @param message used as message if SecurityException is thrown
8148     * @throws SecurityException if the caller is not system or root
8149     */
8150    private static final void enforceSystemOrRoot(String message) {
8151        final int uid = Binder.getCallingUid();
8152        if (uid != Process.SYSTEM_UID && uid != 0) {
8153            throw new SecurityException(message);
8154        }
8155    }
8156
8157    @Override
8158    public void performFstrimIfNeeded() {
8159        enforceSystemOrRoot("Only the system can request fstrim");
8160
8161        // Before everything else, see whether we need to fstrim.
8162        try {
8163            IStorageManager sm = PackageHelper.getStorageManager();
8164            if (sm != null) {
8165                boolean doTrim = false;
8166                final long interval = android.provider.Settings.Global.getLong(
8167                        mContext.getContentResolver(),
8168                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8169                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8170                if (interval > 0) {
8171                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8172                    if (timeSinceLast > interval) {
8173                        doTrim = true;
8174                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8175                                + "; running immediately");
8176                    }
8177                }
8178                if (doTrim) {
8179                    final boolean dexOptDialogShown;
8180                    synchronized (mPackages) {
8181                        dexOptDialogShown = mDexOptDialogShown;
8182                    }
8183                    if (!isFirstBoot() && dexOptDialogShown) {
8184                        try {
8185                            ActivityManager.getService().showBootMessage(
8186                                    mContext.getResources().getString(
8187                                            R.string.android_upgrading_fstrim), true);
8188                        } catch (RemoteException e) {
8189                        }
8190                    }
8191                    sm.runMaintenance();
8192                }
8193            } else {
8194                Slog.e(TAG, "storageManager service unavailable!");
8195            }
8196        } catch (RemoteException e) {
8197            // Can't happen; StorageManagerService is local
8198        }
8199    }
8200
8201    @Override
8202    public void updatePackagesIfNeeded() {
8203        enforceSystemOrRoot("Only the system can request package update");
8204
8205        // We need to re-extract after an OTA.
8206        boolean causeUpgrade = isUpgrade();
8207
8208        // First boot or factory reset.
8209        // Note: we also handle devices that are upgrading to N right now as if it is their
8210        //       first boot, as they do not have profile data.
8211        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8212
8213        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8214        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8215
8216        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8217            return;
8218        }
8219
8220        List<PackageParser.Package> pkgs;
8221        synchronized (mPackages) {
8222            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8223        }
8224
8225        final long startTime = System.nanoTime();
8226        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8227                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8228
8229        final int elapsedTimeSeconds =
8230                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8231
8232        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8233        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8234        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8235        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8236        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8237    }
8238
8239    /**
8240     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8241     * containing statistics about the invocation. The array consists of three elements,
8242     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8243     * and {@code numberOfPackagesFailed}.
8244     */
8245    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8246            String compilerFilter) {
8247
8248        int numberOfPackagesVisited = 0;
8249        int numberOfPackagesOptimized = 0;
8250        int numberOfPackagesSkipped = 0;
8251        int numberOfPackagesFailed = 0;
8252        final int numberOfPackagesToDexopt = pkgs.size();
8253
8254        for (PackageParser.Package pkg : pkgs) {
8255            numberOfPackagesVisited++;
8256
8257            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8258                if (DEBUG_DEXOPT) {
8259                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8260                }
8261                numberOfPackagesSkipped++;
8262                continue;
8263            }
8264
8265            if (DEBUG_DEXOPT) {
8266                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8267                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8268            }
8269
8270            if (showDialog) {
8271                try {
8272                    ActivityManager.getService().showBootMessage(
8273                            mContext.getResources().getString(R.string.android_upgrading_apk,
8274                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8275                } catch (RemoteException e) {
8276                }
8277                synchronized (mPackages) {
8278                    mDexOptDialogShown = true;
8279                }
8280            }
8281
8282            // If the OTA updates a system app which was previously preopted to a non-preopted state
8283            // the app might end up being verified at runtime. That's because by default the apps
8284            // are verify-profile but for preopted apps there's no profile.
8285            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8286            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8287            // filter (by default interpret-only).
8288            // Note that at this stage unused apps are already filtered.
8289            if (isSystemApp(pkg) &&
8290                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8291                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8292                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8293            }
8294
8295            // checkProfiles is false to avoid merging profiles during boot which
8296            // might interfere with background compilation (b/28612421).
8297            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8298            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8299            // trade-off worth doing to save boot time work.
8300            int dexOptStatus = performDexOptTraced(pkg.packageName,
8301                    false /* checkProfiles */,
8302                    compilerFilter,
8303                    false /* force */);
8304            switch (dexOptStatus) {
8305                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8306                    numberOfPackagesOptimized++;
8307                    break;
8308                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8309                    numberOfPackagesSkipped++;
8310                    break;
8311                case PackageDexOptimizer.DEX_OPT_FAILED:
8312                    numberOfPackagesFailed++;
8313                    break;
8314                default:
8315                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8316                    break;
8317            }
8318        }
8319
8320        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8321                numberOfPackagesFailed };
8322    }
8323
8324    @Override
8325    public void notifyPackageUse(String packageName, int reason) {
8326        synchronized (mPackages) {
8327            PackageParser.Package p = mPackages.get(packageName);
8328            if (p == null) {
8329                return;
8330            }
8331            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8332        }
8333    }
8334
8335    @Override
8336    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8337        int userId = UserHandle.getCallingUserId();
8338        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8339        if (ai == null) {
8340            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8341                + loadingPackageName + ", user=" + userId);
8342            return;
8343        }
8344        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8345    }
8346
8347    // TODO: this is not used nor needed. Delete it.
8348    @Override
8349    public boolean performDexOptIfNeeded(String packageName) {
8350        int dexOptStatus = performDexOptTraced(packageName,
8351                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8352        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8353    }
8354
8355    @Override
8356    public boolean performDexOpt(String packageName,
8357            boolean checkProfiles, int compileReason, boolean force) {
8358        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8359                getCompilerFilterForReason(compileReason), force);
8360        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8361    }
8362
8363    @Override
8364    public boolean performDexOptMode(String packageName,
8365            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8366        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8367                targetCompilerFilter, force);
8368        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8369    }
8370
8371    private int performDexOptTraced(String packageName,
8372                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8373        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8374        try {
8375            return performDexOptInternal(packageName, checkProfiles,
8376                    targetCompilerFilter, force);
8377        } finally {
8378            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8379        }
8380    }
8381
8382    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8383    // if the package can now be considered up to date for the given filter.
8384    private int performDexOptInternal(String packageName,
8385                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8386        PackageParser.Package p;
8387        synchronized (mPackages) {
8388            p = mPackages.get(packageName);
8389            if (p == null) {
8390                // Package could not be found. Report failure.
8391                return PackageDexOptimizer.DEX_OPT_FAILED;
8392            }
8393            mPackageUsage.maybeWriteAsync(mPackages);
8394            mCompilerStats.maybeWriteAsync();
8395        }
8396        long callingId = Binder.clearCallingIdentity();
8397        try {
8398            synchronized (mInstallLock) {
8399                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8400                        targetCompilerFilter, force);
8401            }
8402        } finally {
8403            Binder.restoreCallingIdentity(callingId);
8404        }
8405    }
8406
8407    public ArraySet<String> getOptimizablePackages() {
8408        ArraySet<String> pkgs = new ArraySet<String>();
8409        synchronized (mPackages) {
8410            for (PackageParser.Package p : mPackages.values()) {
8411                if (PackageDexOptimizer.canOptimizePackage(p)) {
8412                    pkgs.add(p.packageName);
8413                }
8414            }
8415        }
8416        return pkgs;
8417    }
8418
8419    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8420            boolean checkProfiles, String targetCompilerFilter,
8421            boolean force) {
8422        // Select the dex optimizer based on the force parameter.
8423        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8424        //       allocate an object here.
8425        PackageDexOptimizer pdo = force
8426                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8427                : mPackageDexOptimizer;
8428
8429        // Optimize all dependencies first. Note: we ignore the return value and march on
8430        // on errors.
8431        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8432        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8433        if (!deps.isEmpty()) {
8434            for (PackageParser.Package depPackage : deps) {
8435                // TODO: Analyze and investigate if we (should) profile libraries.
8436                // Currently this will do a full compilation of the library by default.
8437                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8438                        false /* checkProfiles */,
8439                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8440                        getOrCreateCompilerPackageStats(depPackage),
8441                        mDexManager.isUsedByOtherApps(p.packageName));
8442            }
8443        }
8444        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8445                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8446                mDexManager.isUsedByOtherApps(p.packageName));
8447    }
8448
8449    // Performs dexopt on the used secondary dex files belonging to the given package.
8450    // Returns true if all dex files were process successfully (which could mean either dexopt or
8451    // skip). Returns false if any of the files caused errors.
8452    @Override
8453    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8454            boolean force) {
8455        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8456    }
8457
8458    /**
8459     * Reconcile the information we have about the secondary dex files belonging to
8460     * {@code packagName} and the actual dex files. For all dex files that were
8461     * deleted, update the internal records and delete the generated oat files.
8462     */
8463    @Override
8464    public void reconcileSecondaryDexFiles(String packageName) {
8465        mDexManager.reconcileSecondaryDexFiles(packageName);
8466    }
8467
8468    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8469    // a reference there.
8470    /*package*/ DexManager getDexManager() {
8471        return mDexManager;
8472    }
8473
8474    /**
8475     * Execute the background dexopt job immediately.
8476     */
8477    @Override
8478    public boolean runBackgroundDexoptJob() {
8479        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8480    }
8481
8482    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8483        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8484                || p.usesStaticLibraries != null) {
8485            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8486            Set<String> collectedNames = new HashSet<>();
8487            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8488
8489            retValue.remove(p);
8490
8491            return retValue;
8492        } else {
8493            return Collections.emptyList();
8494        }
8495    }
8496
8497    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8498            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8499        if (!collectedNames.contains(p.packageName)) {
8500            collectedNames.add(p.packageName);
8501            collected.add(p);
8502
8503            if (p.usesLibraries != null) {
8504                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8505                        null, collected, collectedNames);
8506            }
8507            if (p.usesOptionalLibraries != null) {
8508                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8509                        null, collected, collectedNames);
8510            }
8511            if (p.usesStaticLibraries != null) {
8512                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8513                        p.usesStaticLibrariesVersions, collected, collectedNames);
8514            }
8515        }
8516    }
8517
8518    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8519            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8520        final int libNameCount = libs.size();
8521        for (int i = 0; i < libNameCount; i++) {
8522            String libName = libs.get(i);
8523            int version = (versions != null && versions.length == libNameCount)
8524                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8525            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8526            if (libPkg != null) {
8527                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8528            }
8529        }
8530    }
8531
8532    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8533        synchronized (mPackages) {
8534            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8535            if (libEntry != null) {
8536                return mPackages.get(libEntry.apk);
8537            }
8538            return null;
8539        }
8540    }
8541
8542    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8543        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8544        if (versionedLib == null) {
8545            return null;
8546        }
8547        return versionedLib.get(version);
8548    }
8549
8550    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8551        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8552                pkg.staticSharedLibName);
8553        if (versionedLib == null) {
8554            return null;
8555        }
8556        int previousLibVersion = -1;
8557        final int versionCount = versionedLib.size();
8558        for (int i = 0; i < versionCount; i++) {
8559            final int libVersion = versionedLib.keyAt(i);
8560            if (libVersion < pkg.staticSharedLibVersion) {
8561                previousLibVersion = Math.max(previousLibVersion, libVersion);
8562            }
8563        }
8564        if (previousLibVersion >= 0) {
8565            return versionedLib.get(previousLibVersion);
8566        }
8567        return null;
8568    }
8569
8570    public void shutdown() {
8571        mPackageUsage.writeNow(mPackages);
8572        mCompilerStats.writeNow();
8573    }
8574
8575    @Override
8576    public void dumpProfiles(String packageName) {
8577        PackageParser.Package pkg;
8578        synchronized (mPackages) {
8579            pkg = mPackages.get(packageName);
8580            if (pkg == null) {
8581                throw new IllegalArgumentException("Unknown package: " + packageName);
8582            }
8583        }
8584        /* Only the shell, root, or the app user should be able to dump profiles. */
8585        int callingUid = Binder.getCallingUid();
8586        if (callingUid != Process.SHELL_UID &&
8587            callingUid != Process.ROOT_UID &&
8588            callingUid != pkg.applicationInfo.uid) {
8589            throw new SecurityException("dumpProfiles");
8590        }
8591
8592        synchronized (mInstallLock) {
8593            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8594            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8595            try {
8596                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8597                String codePaths = TextUtils.join(";", allCodePaths);
8598                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8599            } catch (InstallerException e) {
8600                Slog.w(TAG, "Failed to dump profiles", e);
8601            }
8602            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8603        }
8604    }
8605
8606    @Override
8607    public void forceDexOpt(String packageName) {
8608        enforceSystemOrRoot("forceDexOpt");
8609
8610        PackageParser.Package pkg;
8611        synchronized (mPackages) {
8612            pkg = mPackages.get(packageName);
8613            if (pkg == null) {
8614                throw new IllegalArgumentException("Unknown package: " + packageName);
8615            }
8616        }
8617
8618        synchronized (mInstallLock) {
8619            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8620
8621            // Whoever is calling forceDexOpt wants a fully compiled package.
8622            // Don't use profiles since that may cause compilation to be skipped.
8623            final int res = performDexOptInternalWithDependenciesLI(pkg,
8624                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8625                    true /* force */);
8626
8627            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8628            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8629                throw new IllegalStateException("Failed to dexopt: " + res);
8630            }
8631        }
8632    }
8633
8634    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8635        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8636            Slog.w(TAG, "Unable to update from " + oldPkg.name
8637                    + " to " + newPkg.packageName
8638                    + ": old package not in system partition");
8639            return false;
8640        } else if (mPackages.get(oldPkg.name) != null) {
8641            Slog.w(TAG, "Unable to update from " + oldPkg.name
8642                    + " to " + newPkg.packageName
8643                    + ": old package still exists");
8644            return false;
8645        }
8646        return true;
8647    }
8648
8649    void removeCodePathLI(File codePath) {
8650        if (codePath.isDirectory()) {
8651            try {
8652                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8653            } catch (InstallerException e) {
8654                Slog.w(TAG, "Failed to remove code path", e);
8655            }
8656        } else {
8657            codePath.delete();
8658        }
8659    }
8660
8661    private int[] resolveUserIds(int userId) {
8662        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8663    }
8664
8665    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8666        if (pkg == null) {
8667            Slog.wtf(TAG, "Package was null!", new Throwable());
8668            return;
8669        }
8670        clearAppDataLeafLIF(pkg, userId, flags);
8671        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8672        for (int i = 0; i < childCount; i++) {
8673            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8674        }
8675    }
8676
8677    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8678        final PackageSetting ps;
8679        synchronized (mPackages) {
8680            ps = mSettings.mPackages.get(pkg.packageName);
8681        }
8682        for (int realUserId : resolveUserIds(userId)) {
8683            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8684            try {
8685                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8686                        ceDataInode);
8687            } catch (InstallerException e) {
8688                Slog.w(TAG, String.valueOf(e));
8689            }
8690        }
8691    }
8692
8693    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8694        if (pkg == null) {
8695            Slog.wtf(TAG, "Package was null!", new Throwable());
8696            return;
8697        }
8698        destroyAppDataLeafLIF(pkg, userId, flags);
8699        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8700        for (int i = 0; i < childCount; i++) {
8701            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8702        }
8703    }
8704
8705    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8706        final PackageSetting ps;
8707        synchronized (mPackages) {
8708            ps = mSettings.mPackages.get(pkg.packageName);
8709        }
8710        for (int realUserId : resolveUserIds(userId)) {
8711            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8712            try {
8713                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8714                        ceDataInode);
8715            } catch (InstallerException e) {
8716                Slog.w(TAG, String.valueOf(e));
8717            }
8718            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8719        }
8720    }
8721
8722    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8723        if (pkg == null) {
8724            Slog.wtf(TAG, "Package was null!", new Throwable());
8725            return;
8726        }
8727        destroyAppProfilesLeafLIF(pkg);
8728        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8729        for (int i = 0; i < childCount; i++) {
8730            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8731        }
8732    }
8733
8734    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8735        try {
8736            mInstaller.destroyAppProfiles(pkg.packageName);
8737        } catch (InstallerException e) {
8738            Slog.w(TAG, String.valueOf(e));
8739        }
8740    }
8741
8742    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8743        if (pkg == null) {
8744            Slog.wtf(TAG, "Package was null!", new Throwable());
8745            return;
8746        }
8747        clearAppProfilesLeafLIF(pkg);
8748        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8749        for (int i = 0; i < childCount; i++) {
8750            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8751        }
8752    }
8753
8754    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8755        try {
8756            mInstaller.clearAppProfiles(pkg.packageName);
8757        } catch (InstallerException e) {
8758            Slog.w(TAG, String.valueOf(e));
8759        }
8760    }
8761
8762    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8763            long lastUpdateTime) {
8764        // Set parent install/update time
8765        PackageSetting ps = (PackageSetting) pkg.mExtras;
8766        if (ps != null) {
8767            ps.firstInstallTime = firstInstallTime;
8768            ps.lastUpdateTime = lastUpdateTime;
8769        }
8770        // Set children install/update time
8771        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8772        for (int i = 0; i < childCount; i++) {
8773            PackageParser.Package childPkg = pkg.childPackages.get(i);
8774            ps = (PackageSetting) childPkg.mExtras;
8775            if (ps != null) {
8776                ps.firstInstallTime = firstInstallTime;
8777                ps.lastUpdateTime = lastUpdateTime;
8778            }
8779        }
8780    }
8781
8782    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8783            PackageParser.Package changingLib) {
8784        if (file.path != null) {
8785            usesLibraryFiles.add(file.path);
8786            return;
8787        }
8788        PackageParser.Package p = mPackages.get(file.apk);
8789        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8790            // If we are doing this while in the middle of updating a library apk,
8791            // then we need to make sure to use that new apk for determining the
8792            // dependencies here.  (We haven't yet finished committing the new apk
8793            // to the package manager state.)
8794            if (p == null || p.packageName.equals(changingLib.packageName)) {
8795                p = changingLib;
8796            }
8797        }
8798        if (p != null) {
8799            usesLibraryFiles.addAll(p.getAllCodePaths());
8800        }
8801    }
8802
8803    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8804            PackageParser.Package changingLib) throws PackageManagerException {
8805        if (pkg == null) {
8806            return;
8807        }
8808        ArraySet<String> usesLibraryFiles = null;
8809        if (pkg.usesLibraries != null) {
8810            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8811                    null, null, pkg.packageName, changingLib, true, null);
8812        }
8813        if (pkg.usesStaticLibraries != null) {
8814            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8815                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8816                    pkg.packageName, changingLib, true, usesLibraryFiles);
8817        }
8818        if (pkg.usesOptionalLibraries != null) {
8819            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8820                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8821        }
8822        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8823            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8824        } else {
8825            pkg.usesLibraryFiles = null;
8826        }
8827    }
8828
8829    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8830            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8831            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8832            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8833            throws PackageManagerException {
8834        final int libCount = requestedLibraries.size();
8835        for (int i = 0; i < libCount; i++) {
8836            final String libName = requestedLibraries.get(i);
8837            final int libVersion = requiredVersions != null ? requiredVersions[i]
8838                    : SharedLibraryInfo.VERSION_UNDEFINED;
8839            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8840            if (libEntry == null) {
8841                if (required) {
8842                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8843                            "Package " + packageName + " requires unavailable shared library "
8844                                    + libName + "; failing!");
8845                } else {
8846                    Slog.w(TAG, "Package " + packageName
8847                            + " desires unavailable shared library "
8848                            + libName + "; ignoring!");
8849                }
8850            } else {
8851                if (requiredVersions != null && requiredCertDigests != null) {
8852                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8853                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8854                            "Package " + packageName + " requires unavailable static shared"
8855                                    + " library " + libName + " version "
8856                                    + libEntry.info.getVersion() + "; failing!");
8857                    }
8858
8859                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8860                    if (libPkg == null) {
8861                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8862                                "Package " + packageName + " requires unavailable static shared"
8863                                        + " library; failing!");
8864                    }
8865
8866                    String expectedCertDigest = requiredCertDigests[i];
8867                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8868                                libPkg.mSignatures[0]);
8869                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8870                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8871                                "Package " + packageName + " requires differently signed" +
8872                                        " static shared library; failing!");
8873                    }
8874                }
8875
8876                if (outUsedLibraries == null) {
8877                    outUsedLibraries = new ArraySet<>();
8878                }
8879                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8880            }
8881        }
8882        return outUsedLibraries;
8883    }
8884
8885    private static boolean hasString(List<String> list, List<String> which) {
8886        if (list == null) {
8887            return false;
8888        }
8889        for (int i=list.size()-1; i>=0; i--) {
8890            for (int j=which.size()-1; j>=0; j--) {
8891                if (which.get(j).equals(list.get(i))) {
8892                    return true;
8893                }
8894            }
8895        }
8896        return false;
8897    }
8898
8899    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8900            PackageParser.Package changingPkg) {
8901        ArrayList<PackageParser.Package> res = null;
8902        for (PackageParser.Package pkg : mPackages.values()) {
8903            if (changingPkg != null
8904                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8905                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8906                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8907                            changingPkg.staticSharedLibName)) {
8908                return null;
8909            }
8910            if (res == null) {
8911                res = new ArrayList<>();
8912            }
8913            res.add(pkg);
8914            try {
8915                updateSharedLibrariesLPr(pkg, changingPkg);
8916            } catch (PackageManagerException e) {
8917                // If a system app update or an app and a required lib missing we
8918                // delete the package and for updated system apps keep the data as
8919                // it is better for the user to reinstall than to be in an limbo
8920                // state. Also libs disappearing under an app should never happen
8921                // - just in case.
8922                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8923                    final int flags = pkg.isUpdatedSystemApp()
8924                            ? PackageManager.DELETE_KEEP_DATA : 0;
8925                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8926                            flags , null, true, null);
8927                }
8928                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8929            }
8930        }
8931        return res;
8932    }
8933
8934    /**
8935     * Derive the value of the {@code cpuAbiOverride} based on the provided
8936     * value and an optional stored value from the package settings.
8937     */
8938    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8939        String cpuAbiOverride = null;
8940
8941        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8942            cpuAbiOverride = null;
8943        } else if (abiOverride != null) {
8944            cpuAbiOverride = abiOverride;
8945        } else if (settings != null) {
8946            cpuAbiOverride = settings.cpuAbiOverrideString;
8947        }
8948
8949        return cpuAbiOverride;
8950    }
8951
8952    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8953            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8954                    throws PackageManagerException {
8955        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8956        // If the package has children and this is the first dive in the function
8957        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8958        // whether all packages (parent and children) would be successfully scanned
8959        // before the actual scan since scanning mutates internal state and we want
8960        // to atomically install the package and its children.
8961        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8962            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8963                scanFlags |= SCAN_CHECK_ONLY;
8964            }
8965        } else {
8966            scanFlags &= ~SCAN_CHECK_ONLY;
8967        }
8968
8969        final PackageParser.Package scannedPkg;
8970        try {
8971            // Scan the parent
8972            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8973            // Scan the children
8974            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8975            for (int i = 0; i < childCount; i++) {
8976                PackageParser.Package childPkg = pkg.childPackages.get(i);
8977                scanPackageLI(childPkg, policyFlags,
8978                        scanFlags, currentTime, user);
8979            }
8980        } finally {
8981            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8982        }
8983
8984        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8985            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8986        }
8987
8988        return scannedPkg;
8989    }
8990
8991    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8992            int scanFlags, long currentTime, @Nullable UserHandle user)
8993                    throws PackageManagerException {
8994        boolean success = false;
8995        try {
8996            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8997                    currentTime, user);
8998            success = true;
8999            return res;
9000        } finally {
9001            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9002                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9003                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9004                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9005                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9006            }
9007        }
9008    }
9009
9010    /**
9011     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9012     */
9013    private static boolean apkHasCode(String fileName) {
9014        StrictJarFile jarFile = null;
9015        try {
9016            jarFile = new StrictJarFile(fileName,
9017                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9018            return jarFile.findEntry("classes.dex") != null;
9019        } catch (IOException ignore) {
9020        } finally {
9021            try {
9022                if (jarFile != null) {
9023                    jarFile.close();
9024                }
9025            } catch (IOException ignore) {}
9026        }
9027        return false;
9028    }
9029
9030    /**
9031     * Enforces code policy for the package. This ensures that if an APK has
9032     * declared hasCode="true" in its manifest that the APK actually contains
9033     * code.
9034     *
9035     * @throws PackageManagerException If bytecode could not be found when it should exist
9036     */
9037    private static void assertCodePolicy(PackageParser.Package pkg)
9038            throws PackageManagerException {
9039        final boolean shouldHaveCode =
9040                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9041        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9042            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9043                    "Package " + pkg.baseCodePath + " code is missing");
9044        }
9045
9046        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9047            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9048                final boolean splitShouldHaveCode =
9049                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9050                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9051                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9052                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9053                }
9054            }
9055        }
9056    }
9057
9058    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9059            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9060                    throws PackageManagerException {
9061        if (DEBUG_PACKAGE_SCANNING) {
9062            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9063                Log.d(TAG, "Scanning package " + pkg.packageName);
9064        }
9065
9066        applyPolicy(pkg, policyFlags);
9067
9068        assertPackageIsValid(pkg, policyFlags, scanFlags);
9069
9070        // Initialize package source and resource directories
9071        final File scanFile = new File(pkg.codePath);
9072        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9073        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9074
9075        SharedUserSetting suid = null;
9076        PackageSetting pkgSetting = null;
9077
9078        // Getting the package setting may have a side-effect, so if we
9079        // are only checking if scan would succeed, stash a copy of the
9080        // old setting to restore at the end.
9081        PackageSetting nonMutatedPs = null;
9082
9083        // We keep references to the derived CPU Abis from settings in oder to reuse
9084        // them in the case where we're not upgrading or booting for the first time.
9085        String primaryCpuAbiFromSettings = null;
9086        String secondaryCpuAbiFromSettings = null;
9087
9088        // writer
9089        synchronized (mPackages) {
9090            if (pkg.mSharedUserId != null) {
9091                // SIDE EFFECTS; may potentially allocate a new shared user
9092                suid = mSettings.getSharedUserLPw(
9093                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9094                if (DEBUG_PACKAGE_SCANNING) {
9095                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9096                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9097                                + "): packages=" + suid.packages);
9098                }
9099            }
9100
9101            // Check if we are renaming from an original package name.
9102            PackageSetting origPackage = null;
9103            String realName = null;
9104            if (pkg.mOriginalPackages != null) {
9105                // This package may need to be renamed to a previously
9106                // installed name.  Let's check on that...
9107                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9108                if (pkg.mOriginalPackages.contains(renamed)) {
9109                    // This package had originally been installed as the
9110                    // original name, and we have already taken care of
9111                    // transitioning to the new one.  Just update the new
9112                    // one to continue using the old name.
9113                    realName = pkg.mRealPackage;
9114                    if (!pkg.packageName.equals(renamed)) {
9115                        // Callers into this function may have already taken
9116                        // care of renaming the package; only do it here if
9117                        // it is not already done.
9118                        pkg.setPackageName(renamed);
9119                    }
9120                } else {
9121                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9122                        if ((origPackage = mSettings.getPackageLPr(
9123                                pkg.mOriginalPackages.get(i))) != null) {
9124                            // We do have the package already installed under its
9125                            // original name...  should we use it?
9126                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9127                                // New package is not compatible with original.
9128                                origPackage = null;
9129                                continue;
9130                            } else if (origPackage.sharedUser != null) {
9131                                // Make sure uid is compatible between packages.
9132                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9133                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9134                                            + " to " + pkg.packageName + ": old uid "
9135                                            + origPackage.sharedUser.name
9136                                            + " differs from " + pkg.mSharedUserId);
9137                                    origPackage = null;
9138                                    continue;
9139                                }
9140                                // TODO: Add case when shared user id is added [b/28144775]
9141                            } else {
9142                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9143                                        + pkg.packageName + " to old name " + origPackage.name);
9144                            }
9145                            break;
9146                        }
9147                    }
9148                }
9149            }
9150
9151            if (mTransferedPackages.contains(pkg.packageName)) {
9152                Slog.w(TAG, "Package " + pkg.packageName
9153                        + " was transferred to another, but its .apk remains");
9154            }
9155
9156            // See comments in nonMutatedPs declaration
9157            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9158                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9159                if (foundPs != null) {
9160                    nonMutatedPs = new PackageSetting(foundPs);
9161                }
9162            }
9163
9164            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9165                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9166                if (foundPs != null) {
9167                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9168                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9169                }
9170            }
9171
9172            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9173            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9174                PackageManagerService.reportSettingsProblem(Log.WARN,
9175                        "Package " + pkg.packageName + " shared user changed from "
9176                                + (pkgSetting.sharedUser != null
9177                                        ? pkgSetting.sharedUser.name : "<nothing>")
9178                                + " to "
9179                                + (suid != null ? suid.name : "<nothing>")
9180                                + "; replacing with new");
9181                pkgSetting = null;
9182            }
9183            final PackageSetting oldPkgSetting =
9184                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9185            final PackageSetting disabledPkgSetting =
9186                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9187
9188            String[] usesStaticLibraries = null;
9189            if (pkg.usesStaticLibraries != null) {
9190                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9191                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9192            }
9193
9194            if (pkgSetting == null) {
9195                final String parentPackageName = (pkg.parentPackage != null)
9196                        ? pkg.parentPackage.packageName : null;
9197                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9198                // REMOVE SharedUserSetting from method; update in a separate call
9199                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9200                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9201                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9202                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9203                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9204                        true /*allowInstall*/, instantApp, parentPackageName,
9205                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9206                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9207                // SIDE EFFECTS; updates system state; move elsewhere
9208                if (origPackage != null) {
9209                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9210                }
9211                mSettings.addUserToSettingLPw(pkgSetting);
9212            } else {
9213                // REMOVE SharedUserSetting from method; update in a separate call.
9214                //
9215                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9216                // secondaryCpuAbi are not known at this point so we always update them
9217                // to null here, only to reset them at a later point.
9218                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9219                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9220                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9221                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9222                        UserManagerService.getInstance(), usesStaticLibraries,
9223                        pkg.usesStaticLibrariesVersions);
9224            }
9225            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9226            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9227
9228            // SIDE EFFECTS; modifies system state; move elsewhere
9229            if (pkgSetting.origPackage != null) {
9230                // If we are first transitioning from an original package,
9231                // fix up the new package's name now.  We need to do this after
9232                // looking up the package under its new name, so getPackageLP
9233                // can take care of fiddling things correctly.
9234                pkg.setPackageName(origPackage.name);
9235
9236                // File a report about this.
9237                String msg = "New package " + pkgSetting.realName
9238                        + " renamed to replace old package " + pkgSetting.name;
9239                reportSettingsProblem(Log.WARN, msg);
9240
9241                // Make a note of it.
9242                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9243                    mTransferedPackages.add(origPackage.name);
9244                }
9245
9246                // No longer need to retain this.
9247                pkgSetting.origPackage = null;
9248            }
9249
9250            // SIDE EFFECTS; modifies system state; move elsewhere
9251            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9252                // Make a note of it.
9253                mTransferedPackages.add(pkg.packageName);
9254            }
9255
9256            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9257                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9258            }
9259
9260            if ((scanFlags & SCAN_BOOTING) == 0
9261                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9262                // Check all shared libraries and map to their actual file path.
9263                // We only do this here for apps not on a system dir, because those
9264                // are the only ones that can fail an install due to this.  We
9265                // will take care of the system apps by updating all of their
9266                // library paths after the scan is done. Also during the initial
9267                // scan don't update any libs as we do this wholesale after all
9268                // apps are scanned to avoid dependency based scanning.
9269                updateSharedLibrariesLPr(pkg, null);
9270            }
9271
9272            if (mFoundPolicyFile) {
9273                SELinuxMMAC.assignSeInfoValue(pkg);
9274            }
9275            pkg.applicationInfo.uid = pkgSetting.appId;
9276            pkg.mExtras = pkgSetting;
9277
9278
9279            // Static shared libs have same package with different versions where
9280            // we internally use a synthetic package name to allow multiple versions
9281            // of the same package, therefore we need to compare signatures against
9282            // the package setting for the latest library version.
9283            PackageSetting signatureCheckPs = pkgSetting;
9284            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9285                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9286                if (libraryEntry != null) {
9287                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9288                }
9289            }
9290
9291            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9292                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9293                    // We just determined the app is signed correctly, so bring
9294                    // over the latest parsed certs.
9295                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9296                } else {
9297                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9298                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9299                                "Package " + pkg.packageName + " upgrade keys do not match the "
9300                                + "previously installed version");
9301                    } else {
9302                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9303                        String msg = "System package " + pkg.packageName
9304                                + " signature changed; retaining data.";
9305                        reportSettingsProblem(Log.WARN, msg);
9306                    }
9307                }
9308            } else {
9309                try {
9310                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9311                    verifySignaturesLP(signatureCheckPs, pkg);
9312                    // We just determined the app is signed correctly, so bring
9313                    // over the latest parsed certs.
9314                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9315                } catch (PackageManagerException e) {
9316                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9317                        throw e;
9318                    }
9319                    // The signature has changed, but this package is in the system
9320                    // image...  let's recover!
9321                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9322                    // However...  if this package is part of a shared user, but it
9323                    // doesn't match the signature of the shared user, let's fail.
9324                    // What this means is that you can't change the signatures
9325                    // associated with an overall shared user, which doesn't seem all
9326                    // that unreasonable.
9327                    if (signatureCheckPs.sharedUser != null) {
9328                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9329                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9330                            throw new PackageManagerException(
9331                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9332                                    "Signature mismatch for shared user: "
9333                                            + pkgSetting.sharedUser);
9334                        }
9335                    }
9336                    // File a report about this.
9337                    String msg = "System package " + pkg.packageName
9338                            + " signature changed; retaining data.";
9339                    reportSettingsProblem(Log.WARN, msg);
9340                }
9341            }
9342
9343            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9344                // This package wants to adopt ownership of permissions from
9345                // another package.
9346                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9347                    final String origName = pkg.mAdoptPermissions.get(i);
9348                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9349                    if (orig != null) {
9350                        if (verifyPackageUpdateLPr(orig, pkg)) {
9351                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9352                                    + pkg.packageName);
9353                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9354                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9355                        }
9356                    }
9357                }
9358            }
9359        }
9360
9361        pkg.applicationInfo.processName = fixProcessName(
9362                pkg.applicationInfo.packageName,
9363                pkg.applicationInfo.processName);
9364
9365        if (pkg != mPlatformPackage) {
9366            // Get all of our default paths setup
9367            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9368        }
9369
9370        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9371
9372        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9373            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9374                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9375                derivePackageAbi(
9376                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9377                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9378
9379                // Some system apps still use directory structure for native libraries
9380                // in which case we might end up not detecting abi solely based on apk
9381                // structure. Try to detect abi based on directory structure.
9382                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9383                        pkg.applicationInfo.primaryCpuAbi == null) {
9384                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9385                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9386                }
9387            } else {
9388                // This is not a first boot or an upgrade, don't bother deriving the
9389                // ABI during the scan. Instead, trust the value that was stored in the
9390                // package setting.
9391                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9392                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9393
9394                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9395
9396                if (DEBUG_ABI_SELECTION) {
9397                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9398                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9399                        pkg.applicationInfo.secondaryCpuAbi);
9400                }
9401            }
9402        } else {
9403            if ((scanFlags & SCAN_MOVE) != 0) {
9404                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9405                // but we already have this packages package info in the PackageSetting. We just
9406                // use that and derive the native library path based on the new codepath.
9407                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9408                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9409            }
9410
9411            // Set native library paths again. For moves, the path will be updated based on the
9412            // ABIs we've determined above. For non-moves, the path will be updated based on the
9413            // ABIs we determined during compilation, but the path will depend on the final
9414            // package path (after the rename away from the stage path).
9415            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9416        }
9417
9418        // This is a special case for the "system" package, where the ABI is
9419        // dictated by the zygote configuration (and init.rc). We should keep track
9420        // of this ABI so that we can deal with "normal" applications that run under
9421        // the same UID correctly.
9422        if (mPlatformPackage == pkg) {
9423            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9424                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9425        }
9426
9427        // If there's a mismatch between the abi-override in the package setting
9428        // and the abiOverride specified for the install. Warn about this because we
9429        // would've already compiled the app without taking the package setting into
9430        // account.
9431        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9432            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9433                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9434                        " for package " + pkg.packageName);
9435            }
9436        }
9437
9438        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9439        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9440        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9441
9442        // Copy the derived override back to the parsed package, so that we can
9443        // update the package settings accordingly.
9444        pkg.cpuAbiOverride = cpuAbiOverride;
9445
9446        if (DEBUG_ABI_SELECTION) {
9447            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9448                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9449                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9450        }
9451
9452        // Push the derived path down into PackageSettings so we know what to
9453        // clean up at uninstall time.
9454        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9455
9456        if (DEBUG_ABI_SELECTION) {
9457            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9458                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9459                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9460        }
9461
9462        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9463        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9464            // We don't do this here during boot because we can do it all
9465            // at once after scanning all existing packages.
9466            //
9467            // We also do this *before* we perform dexopt on this package, so that
9468            // we can avoid redundant dexopts, and also to make sure we've got the
9469            // code and package path correct.
9470            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9471        }
9472
9473        if (mFactoryTest && pkg.requestedPermissions.contains(
9474                android.Manifest.permission.FACTORY_TEST)) {
9475            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9476        }
9477
9478        if (isSystemApp(pkg)) {
9479            pkgSetting.isOrphaned = true;
9480        }
9481
9482        // Take care of first install / last update times.
9483        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9484        if (currentTime != 0) {
9485            if (pkgSetting.firstInstallTime == 0) {
9486                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9487            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9488                pkgSetting.lastUpdateTime = currentTime;
9489            }
9490        } else if (pkgSetting.firstInstallTime == 0) {
9491            // We need *something*.  Take time time stamp of the file.
9492            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9493        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9494            if (scanFileTime != pkgSetting.timeStamp) {
9495                // A package on the system image has changed; consider this
9496                // to be an update.
9497                pkgSetting.lastUpdateTime = scanFileTime;
9498            }
9499        }
9500        pkgSetting.setTimeStamp(scanFileTime);
9501
9502        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9503            if (nonMutatedPs != null) {
9504                synchronized (mPackages) {
9505                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9506                }
9507            }
9508        } else {
9509            final int userId = user == null ? 0 : user.getIdentifier();
9510            // Modify state for the given package setting
9511            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9512                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9513            if (pkgSetting.getInstantApp(userId)) {
9514                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9515            }
9516        }
9517        return pkg;
9518    }
9519
9520    /**
9521     * Applies policy to the parsed package based upon the given policy flags.
9522     * Ensures the package is in a good state.
9523     * <p>
9524     * Implementation detail: This method must NOT have any side effect. It would
9525     * ideally be static, but, it requires locks to read system state.
9526     */
9527    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9528        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9529            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9530            if (pkg.applicationInfo.isDirectBootAware()) {
9531                // we're direct boot aware; set for all components
9532                for (PackageParser.Service s : pkg.services) {
9533                    s.info.encryptionAware = s.info.directBootAware = true;
9534                }
9535                for (PackageParser.Provider p : pkg.providers) {
9536                    p.info.encryptionAware = p.info.directBootAware = true;
9537                }
9538                for (PackageParser.Activity a : pkg.activities) {
9539                    a.info.encryptionAware = a.info.directBootAware = true;
9540                }
9541                for (PackageParser.Activity r : pkg.receivers) {
9542                    r.info.encryptionAware = r.info.directBootAware = true;
9543                }
9544            }
9545        } else {
9546            // Only allow system apps to be flagged as core apps.
9547            pkg.coreApp = false;
9548            // clear flags not applicable to regular apps
9549            pkg.applicationInfo.privateFlags &=
9550                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9551            pkg.applicationInfo.privateFlags &=
9552                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9553        }
9554        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9555
9556        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9557            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9558        }
9559
9560        if (!isSystemApp(pkg)) {
9561            // Only system apps can use these features.
9562            pkg.mOriginalPackages = null;
9563            pkg.mRealPackage = null;
9564            pkg.mAdoptPermissions = null;
9565        }
9566    }
9567
9568    /**
9569     * Asserts the parsed package is valid according to the given policy. If the
9570     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9571     * <p>
9572     * Implementation detail: This method must NOT have any side effects. It would
9573     * ideally be static, but, it requires locks to read system state.
9574     *
9575     * @throws PackageManagerException If the package fails any of the validation checks
9576     */
9577    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9578            throws PackageManagerException {
9579        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9580            assertCodePolicy(pkg);
9581        }
9582
9583        if (pkg.applicationInfo.getCodePath() == null ||
9584                pkg.applicationInfo.getResourcePath() == null) {
9585            // Bail out. The resource and code paths haven't been set.
9586            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9587                    "Code and resource paths haven't been set correctly");
9588        }
9589
9590        // Make sure we're not adding any bogus keyset info
9591        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9592        ksms.assertScannedPackageValid(pkg);
9593
9594        synchronized (mPackages) {
9595            // The special "android" package can only be defined once
9596            if (pkg.packageName.equals("android")) {
9597                if (mAndroidApplication != null) {
9598                    Slog.w(TAG, "*************************************************");
9599                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9600                    Slog.w(TAG, " codePath=" + pkg.codePath);
9601                    Slog.w(TAG, "*************************************************");
9602                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9603                            "Core android package being redefined.  Skipping.");
9604                }
9605            }
9606
9607            // A package name must be unique; don't allow duplicates
9608            if (mPackages.containsKey(pkg.packageName)) {
9609                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9610                        "Application package " + pkg.packageName
9611                        + " already installed.  Skipping duplicate.");
9612            }
9613
9614            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9615                // Static libs have a synthetic package name containing the version
9616                // but we still want the base name to be unique.
9617                if (mPackages.containsKey(pkg.manifestPackageName)) {
9618                    throw new PackageManagerException(
9619                            "Duplicate static shared lib provider package");
9620                }
9621
9622                // Static shared libraries should have at least O target SDK
9623                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9624                    throw new PackageManagerException(
9625                            "Packages declaring static-shared libs must target O SDK or higher");
9626                }
9627
9628                // Package declaring static a shared lib cannot be instant apps
9629                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9630                    throw new PackageManagerException(
9631                            "Packages declaring static-shared libs cannot be instant apps");
9632                }
9633
9634                // Package declaring static a shared lib cannot be renamed since the package
9635                // name is synthetic and apps can't code around package manager internals.
9636                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9637                    throw new PackageManagerException(
9638                            "Packages declaring static-shared libs cannot be renamed");
9639                }
9640
9641                // Package declaring static a shared lib cannot declare child packages
9642                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9643                    throw new PackageManagerException(
9644                            "Packages declaring static-shared libs cannot have child packages");
9645                }
9646
9647                // Package declaring static a shared lib cannot declare dynamic libs
9648                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9649                    throw new PackageManagerException(
9650                            "Packages declaring static-shared libs cannot declare dynamic libs");
9651                }
9652
9653                // Package declaring static a shared lib cannot declare shared users
9654                if (pkg.mSharedUserId != null) {
9655                    throw new PackageManagerException(
9656                            "Packages declaring static-shared libs cannot declare shared users");
9657                }
9658
9659                // Static shared libs cannot declare activities
9660                if (!pkg.activities.isEmpty()) {
9661                    throw new PackageManagerException(
9662                            "Static shared libs cannot declare activities");
9663                }
9664
9665                // Static shared libs cannot declare services
9666                if (!pkg.services.isEmpty()) {
9667                    throw new PackageManagerException(
9668                            "Static shared libs cannot declare services");
9669                }
9670
9671                // Static shared libs cannot declare providers
9672                if (!pkg.providers.isEmpty()) {
9673                    throw new PackageManagerException(
9674                            "Static shared libs cannot declare content providers");
9675                }
9676
9677                // Static shared libs cannot declare receivers
9678                if (!pkg.receivers.isEmpty()) {
9679                    throw new PackageManagerException(
9680                            "Static shared libs cannot declare broadcast receivers");
9681                }
9682
9683                // Static shared libs cannot declare permission groups
9684                if (!pkg.permissionGroups.isEmpty()) {
9685                    throw new PackageManagerException(
9686                            "Static shared libs cannot declare permission groups");
9687                }
9688
9689                // Static shared libs cannot declare permissions
9690                if (!pkg.permissions.isEmpty()) {
9691                    throw new PackageManagerException(
9692                            "Static shared libs cannot declare permissions");
9693                }
9694
9695                // Static shared libs cannot declare protected broadcasts
9696                if (pkg.protectedBroadcasts != null) {
9697                    throw new PackageManagerException(
9698                            "Static shared libs cannot declare protected broadcasts");
9699                }
9700
9701                // Static shared libs cannot be overlay targets
9702                if (pkg.mOverlayTarget != null) {
9703                    throw new PackageManagerException(
9704                            "Static shared libs cannot be overlay targets");
9705                }
9706
9707                // The version codes must be ordered as lib versions
9708                int minVersionCode = Integer.MIN_VALUE;
9709                int maxVersionCode = Integer.MAX_VALUE;
9710
9711                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9712                        pkg.staticSharedLibName);
9713                if (versionedLib != null) {
9714                    final int versionCount = versionedLib.size();
9715                    for (int i = 0; i < versionCount; i++) {
9716                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9717                        // TODO: We will change version code to long, so in the new API it is long
9718                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9719                                .getVersionCode();
9720                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9721                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9722                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9723                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9724                        } else {
9725                            minVersionCode = maxVersionCode = libVersionCode;
9726                            break;
9727                        }
9728                    }
9729                }
9730                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9731                    throw new PackageManagerException("Static shared"
9732                            + " lib version codes must be ordered as lib versions");
9733                }
9734            }
9735
9736            // Only privileged apps and updated privileged apps can add child packages.
9737            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9738                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9739                    throw new PackageManagerException("Only privileged apps can add child "
9740                            + "packages. Ignoring package " + pkg.packageName);
9741                }
9742                final int childCount = pkg.childPackages.size();
9743                for (int i = 0; i < childCount; i++) {
9744                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9745                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9746                            childPkg.packageName)) {
9747                        throw new PackageManagerException("Can't override child of "
9748                                + "another disabled app. Ignoring package " + pkg.packageName);
9749                    }
9750                }
9751            }
9752
9753            // If we're only installing presumed-existing packages, require that the
9754            // scanned APK is both already known and at the path previously established
9755            // for it.  Previously unknown packages we pick up normally, but if we have an
9756            // a priori expectation about this package's install presence, enforce it.
9757            // With a singular exception for new system packages. When an OTA contains
9758            // a new system package, we allow the codepath to change from a system location
9759            // to the user-installed location. If we don't allow this change, any newer,
9760            // user-installed version of the application will be ignored.
9761            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9762                if (mExpectingBetter.containsKey(pkg.packageName)) {
9763                    logCriticalInfo(Log.WARN,
9764                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9765                } else {
9766                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9767                    if (known != null) {
9768                        if (DEBUG_PACKAGE_SCANNING) {
9769                            Log.d(TAG, "Examining " + pkg.codePath
9770                                    + " and requiring known paths " + known.codePathString
9771                                    + " & " + known.resourcePathString);
9772                        }
9773                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9774                                || !pkg.applicationInfo.getResourcePath().equals(
9775                                        known.resourcePathString)) {
9776                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9777                                    "Application package " + pkg.packageName
9778                                    + " found at " + pkg.applicationInfo.getCodePath()
9779                                    + " but expected at " + known.codePathString
9780                                    + "; ignoring.");
9781                        }
9782                    }
9783                }
9784            }
9785
9786            // Verify that this new package doesn't have any content providers
9787            // that conflict with existing packages.  Only do this if the
9788            // package isn't already installed, since we don't want to break
9789            // things that are installed.
9790            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9791                final int N = pkg.providers.size();
9792                int i;
9793                for (i=0; i<N; i++) {
9794                    PackageParser.Provider p = pkg.providers.get(i);
9795                    if (p.info.authority != null) {
9796                        String names[] = p.info.authority.split(";");
9797                        for (int j = 0; j < names.length; j++) {
9798                            if (mProvidersByAuthority.containsKey(names[j])) {
9799                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9800                                final String otherPackageName =
9801                                        ((other != null && other.getComponentName() != null) ?
9802                                                other.getComponentName().getPackageName() : "?");
9803                                throw new PackageManagerException(
9804                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9805                                        "Can't install because provider name " + names[j]
9806                                                + " (in package " + pkg.applicationInfo.packageName
9807                                                + ") is already used by " + otherPackageName);
9808                            }
9809                        }
9810                    }
9811                }
9812            }
9813        }
9814    }
9815
9816    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9817            int type, String declaringPackageName, int declaringVersionCode) {
9818        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9819        if (versionedLib == null) {
9820            versionedLib = new SparseArray<>();
9821            mSharedLibraries.put(name, versionedLib);
9822            if (type == SharedLibraryInfo.TYPE_STATIC) {
9823                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9824            }
9825        } else if (versionedLib.indexOfKey(version) >= 0) {
9826            return false;
9827        }
9828        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9829                version, type, declaringPackageName, declaringVersionCode);
9830        versionedLib.put(version, libEntry);
9831        return true;
9832    }
9833
9834    private boolean removeSharedLibraryLPw(String name, int version) {
9835        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9836        if (versionedLib == null) {
9837            return false;
9838        }
9839        final int libIdx = versionedLib.indexOfKey(version);
9840        if (libIdx < 0) {
9841            return false;
9842        }
9843        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9844        versionedLib.remove(version);
9845        if (versionedLib.size() <= 0) {
9846            mSharedLibraries.remove(name);
9847            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9848                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9849                        .getPackageName());
9850            }
9851        }
9852        return true;
9853    }
9854
9855    /**
9856     * Adds a scanned package to the system. When this method is finished, the package will
9857     * be available for query, resolution, etc...
9858     */
9859    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9860            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9861        final String pkgName = pkg.packageName;
9862        if (mCustomResolverComponentName != null &&
9863                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9864            setUpCustomResolverActivity(pkg);
9865        }
9866
9867        if (pkg.packageName.equals("android")) {
9868            synchronized (mPackages) {
9869                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9870                    // Set up information for our fall-back user intent resolution activity.
9871                    mPlatformPackage = pkg;
9872                    pkg.mVersionCode = mSdkVersion;
9873                    mAndroidApplication = pkg.applicationInfo;
9874                    if (!mResolverReplaced) {
9875                        mResolveActivity.applicationInfo = mAndroidApplication;
9876                        mResolveActivity.name = ResolverActivity.class.getName();
9877                        mResolveActivity.packageName = mAndroidApplication.packageName;
9878                        mResolveActivity.processName = "system:ui";
9879                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9880                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9881                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9882                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9883                        mResolveActivity.exported = true;
9884                        mResolveActivity.enabled = true;
9885                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9886                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9887                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9888                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9889                                | ActivityInfo.CONFIG_ORIENTATION
9890                                | ActivityInfo.CONFIG_KEYBOARD
9891                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9892                        mResolveInfo.activityInfo = mResolveActivity;
9893                        mResolveInfo.priority = 0;
9894                        mResolveInfo.preferredOrder = 0;
9895                        mResolveInfo.match = 0;
9896                        mResolveComponentName = new ComponentName(
9897                                mAndroidApplication.packageName, mResolveActivity.name);
9898                    }
9899                }
9900            }
9901        }
9902
9903        ArrayList<PackageParser.Package> clientLibPkgs = null;
9904        // writer
9905        synchronized (mPackages) {
9906            boolean hasStaticSharedLibs = false;
9907
9908            // Any app can add new static shared libraries
9909            if (pkg.staticSharedLibName != null) {
9910                // Static shared libs don't allow renaming as they have synthetic package
9911                // names to allow install of multiple versions, so use name from manifest.
9912                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9913                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9914                        pkg.manifestPackageName, pkg.mVersionCode)) {
9915                    hasStaticSharedLibs = true;
9916                } else {
9917                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9918                                + pkg.staticSharedLibName + " already exists; skipping");
9919                }
9920                // Static shared libs cannot be updated once installed since they
9921                // use synthetic package name which includes the version code, so
9922                // not need to update other packages's shared lib dependencies.
9923            }
9924
9925            if (!hasStaticSharedLibs
9926                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9927                // Only system apps can add new dynamic shared libraries.
9928                if (pkg.libraryNames != null) {
9929                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9930                        String name = pkg.libraryNames.get(i);
9931                        boolean allowed = false;
9932                        if (pkg.isUpdatedSystemApp()) {
9933                            // New library entries can only be added through the
9934                            // system image.  This is important to get rid of a lot
9935                            // of nasty edge cases: for example if we allowed a non-
9936                            // system update of the app to add a library, then uninstalling
9937                            // the update would make the library go away, and assumptions
9938                            // we made such as through app install filtering would now
9939                            // have allowed apps on the device which aren't compatible
9940                            // with it.  Better to just have the restriction here, be
9941                            // conservative, and create many fewer cases that can negatively
9942                            // impact the user experience.
9943                            final PackageSetting sysPs = mSettings
9944                                    .getDisabledSystemPkgLPr(pkg.packageName);
9945                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9946                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9947                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9948                                        allowed = true;
9949                                        break;
9950                                    }
9951                                }
9952                            }
9953                        } else {
9954                            allowed = true;
9955                        }
9956                        if (allowed) {
9957                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9958                                    SharedLibraryInfo.VERSION_UNDEFINED,
9959                                    SharedLibraryInfo.TYPE_DYNAMIC,
9960                                    pkg.packageName, pkg.mVersionCode)) {
9961                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9962                                        + name + " already exists; skipping");
9963                            }
9964                        } else {
9965                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9966                                    + name + " that is not declared on system image; skipping");
9967                        }
9968                    }
9969
9970                    if ((scanFlags & SCAN_BOOTING) == 0) {
9971                        // If we are not booting, we need to update any applications
9972                        // that are clients of our shared library.  If we are booting,
9973                        // this will all be done once the scan is complete.
9974                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9975                    }
9976                }
9977            }
9978        }
9979
9980        if ((scanFlags & SCAN_BOOTING) != 0) {
9981            // No apps can run during boot scan, so they don't need to be frozen
9982        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9983            // Caller asked to not kill app, so it's probably not frozen
9984        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9985            // Caller asked us to ignore frozen check for some reason; they
9986            // probably didn't know the package name
9987        } else {
9988            // We're doing major surgery on this package, so it better be frozen
9989            // right now to keep it from launching
9990            checkPackageFrozen(pkgName);
9991        }
9992
9993        // Also need to kill any apps that are dependent on the library.
9994        if (clientLibPkgs != null) {
9995            for (int i=0; i<clientLibPkgs.size(); i++) {
9996                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9997                killApplication(clientPkg.applicationInfo.packageName,
9998                        clientPkg.applicationInfo.uid, "update lib");
9999            }
10000        }
10001
10002        // writer
10003        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10004
10005        synchronized (mPackages) {
10006            // We don't expect installation to fail beyond this point
10007
10008            // Add the new setting to mSettings
10009            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10010            // Add the new setting to mPackages
10011            mPackages.put(pkg.applicationInfo.packageName, pkg);
10012            // Make sure we don't accidentally delete its data.
10013            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10014            while (iter.hasNext()) {
10015                PackageCleanItem item = iter.next();
10016                if (pkgName.equals(item.packageName)) {
10017                    iter.remove();
10018                }
10019            }
10020
10021            // Add the package's KeySets to the global KeySetManagerService
10022            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10023            ksms.addScannedPackageLPw(pkg);
10024
10025            int N = pkg.providers.size();
10026            StringBuilder r = null;
10027            int i;
10028            for (i=0; i<N; i++) {
10029                PackageParser.Provider p = pkg.providers.get(i);
10030                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10031                        p.info.processName);
10032                mProviders.addProvider(p);
10033                p.syncable = p.info.isSyncable;
10034                if (p.info.authority != null) {
10035                    String names[] = p.info.authority.split(";");
10036                    p.info.authority = null;
10037                    for (int j = 0; j < names.length; j++) {
10038                        if (j == 1 && p.syncable) {
10039                            // We only want the first authority for a provider to possibly be
10040                            // syncable, so if we already added this provider using a different
10041                            // authority clear the syncable flag. We copy the provider before
10042                            // changing it because the mProviders object contains a reference
10043                            // to a provider that we don't want to change.
10044                            // Only do this for the second authority since the resulting provider
10045                            // object can be the same for all future authorities for this provider.
10046                            p = new PackageParser.Provider(p);
10047                            p.syncable = false;
10048                        }
10049                        if (!mProvidersByAuthority.containsKey(names[j])) {
10050                            mProvidersByAuthority.put(names[j], p);
10051                            if (p.info.authority == null) {
10052                                p.info.authority = names[j];
10053                            } else {
10054                                p.info.authority = p.info.authority + ";" + names[j];
10055                            }
10056                            if (DEBUG_PACKAGE_SCANNING) {
10057                                if (chatty)
10058                                    Log.d(TAG, "Registered content provider: " + names[j]
10059                                            + ", className = " + p.info.name + ", isSyncable = "
10060                                            + p.info.isSyncable);
10061                            }
10062                        } else {
10063                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10064                            Slog.w(TAG, "Skipping provider name " + names[j] +
10065                                    " (in package " + pkg.applicationInfo.packageName +
10066                                    "): name already used by "
10067                                    + ((other != null && other.getComponentName() != null)
10068                                            ? other.getComponentName().getPackageName() : "?"));
10069                        }
10070                    }
10071                }
10072                if (chatty) {
10073                    if (r == null) {
10074                        r = new StringBuilder(256);
10075                    } else {
10076                        r.append(' ');
10077                    }
10078                    r.append(p.info.name);
10079                }
10080            }
10081            if (r != null) {
10082                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10083            }
10084
10085            N = pkg.services.size();
10086            r = null;
10087            for (i=0; i<N; i++) {
10088                PackageParser.Service s = pkg.services.get(i);
10089                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10090                        s.info.processName);
10091                mServices.addService(s);
10092                if (chatty) {
10093                    if (r == null) {
10094                        r = new StringBuilder(256);
10095                    } else {
10096                        r.append(' ');
10097                    }
10098                    r.append(s.info.name);
10099                }
10100            }
10101            if (r != null) {
10102                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10103            }
10104
10105            N = pkg.receivers.size();
10106            r = null;
10107            for (i=0; i<N; i++) {
10108                PackageParser.Activity a = pkg.receivers.get(i);
10109                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10110                        a.info.processName);
10111                mReceivers.addActivity(a, "receiver");
10112                if (chatty) {
10113                    if (r == null) {
10114                        r = new StringBuilder(256);
10115                    } else {
10116                        r.append(' ');
10117                    }
10118                    r.append(a.info.name);
10119                }
10120            }
10121            if (r != null) {
10122                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10123            }
10124
10125            N = pkg.activities.size();
10126            r = null;
10127            for (i=0; i<N; i++) {
10128                PackageParser.Activity a = pkg.activities.get(i);
10129                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10130                        a.info.processName);
10131                mActivities.addActivity(a, "activity");
10132                if (chatty) {
10133                    if (r == null) {
10134                        r = new StringBuilder(256);
10135                    } else {
10136                        r.append(' ');
10137                    }
10138                    r.append(a.info.name);
10139                }
10140            }
10141            if (r != null) {
10142                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10143            }
10144
10145            N = pkg.permissionGroups.size();
10146            r = null;
10147            for (i=0; i<N; i++) {
10148                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10149                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10150                final String curPackageName = cur == null ? null : cur.info.packageName;
10151                // Dont allow ephemeral apps to define new permission groups.
10152                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10153                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10154                            + pg.info.packageName
10155                            + " ignored: instant apps cannot define new permission groups.");
10156                    continue;
10157                }
10158                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10159                if (cur == null || isPackageUpdate) {
10160                    mPermissionGroups.put(pg.info.name, pg);
10161                    if (chatty) {
10162                        if (r == null) {
10163                            r = new StringBuilder(256);
10164                        } else {
10165                            r.append(' ');
10166                        }
10167                        if (isPackageUpdate) {
10168                            r.append("UPD:");
10169                        }
10170                        r.append(pg.info.name);
10171                    }
10172                } else {
10173                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10174                            + pg.info.packageName + " ignored: original from "
10175                            + cur.info.packageName);
10176                    if (chatty) {
10177                        if (r == null) {
10178                            r = new StringBuilder(256);
10179                        } else {
10180                            r.append(' ');
10181                        }
10182                        r.append("DUP:");
10183                        r.append(pg.info.name);
10184                    }
10185                }
10186            }
10187            if (r != null) {
10188                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10189            }
10190
10191            N = pkg.permissions.size();
10192            r = null;
10193            for (i=0; i<N; i++) {
10194                PackageParser.Permission p = pkg.permissions.get(i);
10195
10196                // Dont allow ephemeral apps to define new permissions.
10197                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10198                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10199                            + p.info.packageName
10200                            + " ignored: instant apps cannot define new permissions.");
10201                    continue;
10202                }
10203
10204                // Assume by default that we did not install this permission into the system.
10205                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10206
10207                // Now that permission groups have a special meaning, we ignore permission
10208                // groups for legacy apps to prevent unexpected behavior. In particular,
10209                // permissions for one app being granted to someone just becase they happen
10210                // to be in a group defined by another app (before this had no implications).
10211                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10212                    p.group = mPermissionGroups.get(p.info.group);
10213                    // Warn for a permission in an unknown group.
10214                    if (p.info.group != null && p.group == null) {
10215                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10216                                + p.info.packageName + " in an unknown group " + p.info.group);
10217                    }
10218                }
10219
10220                ArrayMap<String, BasePermission> permissionMap =
10221                        p.tree ? mSettings.mPermissionTrees
10222                                : mSettings.mPermissions;
10223                BasePermission bp = permissionMap.get(p.info.name);
10224
10225                // Allow system apps to redefine non-system permissions
10226                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10227                    final boolean currentOwnerIsSystem = (bp.perm != null
10228                            && isSystemApp(bp.perm.owner));
10229                    if (isSystemApp(p.owner)) {
10230                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10231                            // It's a built-in permission and no owner, take ownership now
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                        } else if (!currentOwnerIsSystem) {
10238                            String msg = "New decl " + p.owner + " of permission  "
10239                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10240                            reportSettingsProblem(Log.WARN, msg);
10241                            bp = null;
10242                        }
10243                    }
10244                }
10245
10246                if (bp == null) {
10247                    bp = new BasePermission(p.info.name, p.info.packageName,
10248                            BasePermission.TYPE_NORMAL);
10249                    permissionMap.put(p.info.name, bp);
10250                }
10251
10252                if (bp.perm == null) {
10253                    if (bp.sourcePackage == null
10254                            || bp.sourcePackage.equals(p.info.packageName)) {
10255                        BasePermission tree = findPermissionTreeLP(p.info.name);
10256                        if (tree == null
10257                                || tree.sourcePackage.equals(p.info.packageName)) {
10258                            bp.packageSetting = pkgSetting;
10259                            bp.perm = p;
10260                            bp.uid = pkg.applicationInfo.uid;
10261                            bp.sourcePackage = p.info.packageName;
10262                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10263                            if (chatty) {
10264                                if (r == null) {
10265                                    r = new StringBuilder(256);
10266                                } else {
10267                                    r.append(' ');
10268                                }
10269                                r.append(p.info.name);
10270                            }
10271                        } else {
10272                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10273                                    + p.info.packageName + " ignored: base tree "
10274                                    + tree.name + " is from package "
10275                                    + tree.sourcePackage);
10276                        }
10277                    } else {
10278                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10279                                + p.info.packageName + " ignored: original from "
10280                                + bp.sourcePackage);
10281                    }
10282                } else if (chatty) {
10283                    if (r == null) {
10284                        r = new StringBuilder(256);
10285                    } else {
10286                        r.append(' ');
10287                    }
10288                    r.append("DUP:");
10289                    r.append(p.info.name);
10290                }
10291                if (bp.perm == p) {
10292                    bp.protectionLevel = p.info.protectionLevel;
10293                }
10294            }
10295
10296            if (r != null) {
10297                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10298            }
10299
10300            N = pkg.instrumentation.size();
10301            r = null;
10302            for (i=0; i<N; i++) {
10303                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10304                a.info.packageName = pkg.applicationInfo.packageName;
10305                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10306                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10307                a.info.splitNames = pkg.splitNames;
10308                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10309                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10310                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10311                a.info.dataDir = pkg.applicationInfo.dataDir;
10312                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10313                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10314                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10315                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10316                mInstrumentation.put(a.getComponentName(), a);
10317                if (chatty) {
10318                    if (r == null) {
10319                        r = new StringBuilder(256);
10320                    } else {
10321                        r.append(' ');
10322                    }
10323                    r.append(a.info.name);
10324                }
10325            }
10326            if (r != null) {
10327                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10328            }
10329
10330            if (pkg.protectedBroadcasts != null) {
10331                N = pkg.protectedBroadcasts.size();
10332                for (i=0; i<N; i++) {
10333                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10334                }
10335            }
10336        }
10337
10338        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10339    }
10340
10341    /**
10342     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10343     * is derived purely on the basis of the contents of {@code scanFile} and
10344     * {@code cpuAbiOverride}.
10345     *
10346     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10347     */
10348    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10349                                 String cpuAbiOverride, boolean extractLibs,
10350                                 File appLib32InstallDir)
10351            throws PackageManagerException {
10352        // Give ourselves some initial paths; we'll come back for another
10353        // pass once we've determined ABI below.
10354        setNativeLibraryPaths(pkg, appLib32InstallDir);
10355
10356        // We would never need to extract libs for forward-locked and external packages,
10357        // since the container service will do it for us. We shouldn't attempt to
10358        // extract libs from system app when it was not updated.
10359        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10360                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10361            extractLibs = false;
10362        }
10363
10364        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10365        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10366
10367        NativeLibraryHelper.Handle handle = null;
10368        try {
10369            handle = NativeLibraryHelper.Handle.create(pkg);
10370            // TODO(multiArch): This can be null for apps that didn't go through the
10371            // usual installation process. We can calculate it again, like we
10372            // do during install time.
10373            //
10374            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10375            // unnecessary.
10376            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10377
10378            // Null out the abis so that they can be recalculated.
10379            pkg.applicationInfo.primaryCpuAbi = null;
10380            pkg.applicationInfo.secondaryCpuAbi = null;
10381            if (isMultiArch(pkg.applicationInfo)) {
10382                // Warn if we've set an abiOverride for multi-lib packages..
10383                // By definition, we need to copy both 32 and 64 bit libraries for
10384                // such packages.
10385                if (pkg.cpuAbiOverride != null
10386                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10387                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10388                }
10389
10390                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10391                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10392                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10393                    if (extractLibs) {
10394                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10395                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10396                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10397                                useIsaSpecificSubdirs);
10398                    } else {
10399                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10400                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10401                    }
10402                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10403                }
10404
10405                maybeThrowExceptionForMultiArchCopy(
10406                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10407
10408                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10409                    if (extractLibs) {
10410                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10411                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10412                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10413                                useIsaSpecificSubdirs);
10414                    } else {
10415                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10416                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10417                    }
10418                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10419                }
10420
10421                maybeThrowExceptionForMultiArchCopy(
10422                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10423
10424                if (abi64 >= 0) {
10425                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10426                }
10427
10428                if (abi32 >= 0) {
10429                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10430                    if (abi64 >= 0) {
10431                        if (pkg.use32bitAbi) {
10432                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10433                            pkg.applicationInfo.primaryCpuAbi = abi;
10434                        } else {
10435                            pkg.applicationInfo.secondaryCpuAbi = abi;
10436                        }
10437                    } else {
10438                        pkg.applicationInfo.primaryCpuAbi = abi;
10439                    }
10440                }
10441
10442            } else {
10443                String[] abiList = (cpuAbiOverride != null) ?
10444                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10445
10446                // Enable gross and lame hacks for apps that are built with old
10447                // SDK tools. We must scan their APKs for renderscript bitcode and
10448                // not launch them if it's present. Don't bother checking on devices
10449                // that don't have 64 bit support.
10450                boolean needsRenderScriptOverride = false;
10451                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10452                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10453                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10454                    needsRenderScriptOverride = true;
10455                }
10456
10457                final int copyRet;
10458                if (extractLibs) {
10459                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10460                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10461                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10462                } else {
10463                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10464                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10465                }
10466                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10467
10468                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10469                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10470                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10471                }
10472
10473                if (copyRet >= 0) {
10474                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10475                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10476                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10477                } else if (needsRenderScriptOverride) {
10478                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10479                }
10480            }
10481        } catch (IOException ioe) {
10482            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10483        } finally {
10484            IoUtils.closeQuietly(handle);
10485        }
10486
10487        // Now that we've calculated the ABIs and determined if it's an internal app,
10488        // we will go ahead and populate the nativeLibraryPath.
10489        setNativeLibraryPaths(pkg, appLib32InstallDir);
10490    }
10491
10492    /**
10493     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10494     * i.e, so that all packages can be run inside a single process if required.
10495     *
10496     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10497     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10498     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10499     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10500     * updating a package that belongs to a shared user.
10501     *
10502     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10503     * adds unnecessary complexity.
10504     */
10505    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10506            PackageParser.Package scannedPackage) {
10507        String requiredInstructionSet = null;
10508        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10509            requiredInstructionSet = VMRuntime.getInstructionSet(
10510                     scannedPackage.applicationInfo.primaryCpuAbi);
10511        }
10512
10513        PackageSetting requirer = null;
10514        for (PackageSetting ps : packagesForUser) {
10515            // If packagesForUser contains scannedPackage, we skip it. This will happen
10516            // when scannedPackage is an update of an existing package. Without this check,
10517            // we will never be able to change the ABI of any package belonging to a shared
10518            // user, even if it's compatible with other packages.
10519            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10520                if (ps.primaryCpuAbiString == null) {
10521                    continue;
10522                }
10523
10524                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10525                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10526                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10527                    // this but there's not much we can do.
10528                    String errorMessage = "Instruction set mismatch, "
10529                            + ((requirer == null) ? "[caller]" : requirer)
10530                            + " requires " + requiredInstructionSet + " whereas " + ps
10531                            + " requires " + instructionSet;
10532                    Slog.w(TAG, errorMessage);
10533                }
10534
10535                if (requiredInstructionSet == null) {
10536                    requiredInstructionSet = instructionSet;
10537                    requirer = ps;
10538                }
10539            }
10540        }
10541
10542        if (requiredInstructionSet != null) {
10543            String adjustedAbi;
10544            if (requirer != null) {
10545                // requirer != null implies that either scannedPackage was null or that scannedPackage
10546                // did not require an ABI, in which case we have to adjust scannedPackage to match
10547                // the ABI of the set (which is the same as requirer's ABI)
10548                adjustedAbi = requirer.primaryCpuAbiString;
10549                if (scannedPackage != null) {
10550                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10551                }
10552            } else {
10553                // requirer == null implies that we're updating all ABIs in the set to
10554                // match scannedPackage.
10555                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10556            }
10557
10558            for (PackageSetting ps : packagesForUser) {
10559                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10560                    if (ps.primaryCpuAbiString != null) {
10561                        continue;
10562                    }
10563
10564                    ps.primaryCpuAbiString = adjustedAbi;
10565                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10566                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10567                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10568                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10569                                + " (requirer="
10570                                + (requirer != null ? requirer.pkg : "null")
10571                                + ", scannedPackage="
10572                                + (scannedPackage != null ? scannedPackage : "null")
10573                                + ")");
10574                        try {
10575                            mInstaller.rmdex(ps.codePathString,
10576                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10577                        } catch (InstallerException ignored) {
10578                        }
10579                    }
10580                }
10581            }
10582        }
10583    }
10584
10585    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10586        synchronized (mPackages) {
10587            mResolverReplaced = true;
10588            // Set up information for custom user intent resolution activity.
10589            mResolveActivity.applicationInfo = pkg.applicationInfo;
10590            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10591            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10592            mResolveActivity.processName = pkg.applicationInfo.packageName;
10593            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10594            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10595                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10596            mResolveActivity.theme = 0;
10597            mResolveActivity.exported = true;
10598            mResolveActivity.enabled = true;
10599            mResolveInfo.activityInfo = mResolveActivity;
10600            mResolveInfo.priority = 0;
10601            mResolveInfo.preferredOrder = 0;
10602            mResolveInfo.match = 0;
10603            mResolveComponentName = mCustomResolverComponentName;
10604            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10605                    mResolveComponentName);
10606        }
10607    }
10608
10609    private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) {
10610        if (installerComponent == null) {
10611            if (DEBUG_EPHEMERAL) {
10612                Slog.d(TAG, "Clear ephemeral installer activity");
10613            }
10614            mInstantAppInstallerActivity.applicationInfo = null;
10615            return;
10616        }
10617
10618        if (DEBUG_EPHEMERAL) {
10619            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10620        }
10621        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10622        // Set up information for ephemeral installer activity
10623        mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo;
10624        mInstantAppInstallerActivity.name = installerComponent.getClassName();
10625        mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName;
10626        mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName;
10627        mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10628        mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10629                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10630        mInstantAppInstallerActivity.theme = 0;
10631        mInstantAppInstallerActivity.exported = true;
10632        mInstantAppInstallerActivity.enabled = true;
10633        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10634        mInstantAppInstallerInfo.priority = 0;
10635        mInstantAppInstallerInfo.preferredOrder = 1;
10636        mInstantAppInstallerInfo.isDefault = true;
10637        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10638                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10639    }
10640
10641    private static String calculateBundledApkRoot(final String codePathString) {
10642        final File codePath = new File(codePathString);
10643        final File codeRoot;
10644        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10645            codeRoot = Environment.getRootDirectory();
10646        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10647            codeRoot = Environment.getOemDirectory();
10648        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10649            codeRoot = Environment.getVendorDirectory();
10650        } else {
10651            // Unrecognized code path; take its top real segment as the apk root:
10652            // e.g. /something/app/blah.apk => /something
10653            try {
10654                File f = codePath.getCanonicalFile();
10655                File parent = f.getParentFile();    // non-null because codePath is a file
10656                File tmp;
10657                while ((tmp = parent.getParentFile()) != null) {
10658                    f = parent;
10659                    parent = tmp;
10660                }
10661                codeRoot = f;
10662                Slog.w(TAG, "Unrecognized code path "
10663                        + codePath + " - using " + codeRoot);
10664            } catch (IOException e) {
10665                // Can't canonicalize the code path -- shenanigans?
10666                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10667                return Environment.getRootDirectory().getPath();
10668            }
10669        }
10670        return codeRoot.getPath();
10671    }
10672
10673    /**
10674     * Derive and set the location of native libraries for the given package,
10675     * which varies depending on where and how the package was installed.
10676     */
10677    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10678        final ApplicationInfo info = pkg.applicationInfo;
10679        final String codePath = pkg.codePath;
10680        final File codeFile = new File(codePath);
10681        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10682        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10683
10684        info.nativeLibraryRootDir = null;
10685        info.nativeLibraryRootRequiresIsa = false;
10686        info.nativeLibraryDir = null;
10687        info.secondaryNativeLibraryDir = null;
10688
10689        if (isApkFile(codeFile)) {
10690            // Monolithic install
10691            if (bundledApp) {
10692                // If "/system/lib64/apkname" exists, assume that is the per-package
10693                // native library directory to use; otherwise use "/system/lib/apkname".
10694                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10695                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10696                        getPrimaryInstructionSet(info));
10697
10698                // This is a bundled system app so choose the path based on the ABI.
10699                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10700                // is just the default path.
10701                final String apkName = deriveCodePathName(codePath);
10702                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10703                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10704                        apkName).getAbsolutePath();
10705
10706                if (info.secondaryCpuAbi != null) {
10707                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10708                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10709                            secondaryLibDir, apkName).getAbsolutePath();
10710                }
10711            } else if (asecApp) {
10712                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10713                        .getAbsolutePath();
10714            } else {
10715                final String apkName = deriveCodePathName(codePath);
10716                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10717                        .getAbsolutePath();
10718            }
10719
10720            info.nativeLibraryRootRequiresIsa = false;
10721            info.nativeLibraryDir = info.nativeLibraryRootDir;
10722        } else {
10723            // Cluster install
10724            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10725            info.nativeLibraryRootRequiresIsa = true;
10726
10727            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10728                    getPrimaryInstructionSet(info)).getAbsolutePath();
10729
10730            if (info.secondaryCpuAbi != null) {
10731                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10732                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10733            }
10734        }
10735    }
10736
10737    /**
10738     * Calculate the abis and roots for a bundled app. These can uniquely
10739     * be determined from the contents of the system partition, i.e whether
10740     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10741     * of this information, and instead assume that the system was built
10742     * sensibly.
10743     */
10744    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10745                                           PackageSetting pkgSetting) {
10746        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10747
10748        // If "/system/lib64/apkname" exists, assume that is the per-package
10749        // native library directory to use; otherwise use "/system/lib/apkname".
10750        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10751        setBundledAppAbi(pkg, apkRoot, apkName);
10752        // pkgSetting might be null during rescan following uninstall of updates
10753        // to a bundled app, so accommodate that possibility.  The settings in
10754        // that case will be established later from the parsed package.
10755        //
10756        // If the settings aren't null, sync them up with what we've just derived.
10757        // note that apkRoot isn't stored in the package settings.
10758        if (pkgSetting != null) {
10759            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10760            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10761        }
10762    }
10763
10764    /**
10765     * Deduces the ABI of a bundled app and sets the relevant fields on the
10766     * parsed pkg object.
10767     *
10768     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10769     *        under which system libraries are installed.
10770     * @param apkName the name of the installed package.
10771     */
10772    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10773        final File codeFile = new File(pkg.codePath);
10774
10775        final boolean has64BitLibs;
10776        final boolean has32BitLibs;
10777        if (isApkFile(codeFile)) {
10778            // Monolithic install
10779            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10780            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10781        } else {
10782            // Cluster install
10783            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10784            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10785                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10786                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10787                has64BitLibs = (new File(rootDir, isa)).exists();
10788            } else {
10789                has64BitLibs = false;
10790            }
10791            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10792                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10793                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10794                has32BitLibs = (new File(rootDir, isa)).exists();
10795            } else {
10796                has32BitLibs = false;
10797            }
10798        }
10799
10800        if (has64BitLibs && !has32BitLibs) {
10801            // The package has 64 bit libs, but not 32 bit libs. Its primary
10802            // ABI should be 64 bit. We can safely assume here that the bundled
10803            // native libraries correspond to the most preferred ABI in the list.
10804
10805            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10806            pkg.applicationInfo.secondaryCpuAbi = null;
10807        } else if (has32BitLibs && !has64BitLibs) {
10808            // The package has 32 bit libs but not 64 bit libs. Its primary
10809            // ABI should be 32 bit.
10810
10811            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10812            pkg.applicationInfo.secondaryCpuAbi = null;
10813        } else if (has32BitLibs && has64BitLibs) {
10814            // The application has both 64 and 32 bit bundled libraries. We check
10815            // here that the app declares multiArch support, and warn if it doesn't.
10816            //
10817            // We will be lenient here and record both ABIs. The primary will be the
10818            // ABI that's higher on the list, i.e, a device that's configured to prefer
10819            // 64 bit apps will see a 64 bit primary ABI,
10820
10821            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10822                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10823            }
10824
10825            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10826                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10827                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10828            } else {
10829                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10830                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10831            }
10832        } else {
10833            pkg.applicationInfo.primaryCpuAbi = null;
10834            pkg.applicationInfo.secondaryCpuAbi = null;
10835        }
10836    }
10837
10838    private void killApplication(String pkgName, int appId, String reason) {
10839        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10840    }
10841
10842    private void killApplication(String pkgName, int appId, int userId, String reason) {
10843        // Request the ActivityManager to kill the process(only for existing packages)
10844        // so that we do not end up in a confused state while the user is still using the older
10845        // version of the application while the new one gets installed.
10846        final long token = Binder.clearCallingIdentity();
10847        try {
10848            IActivityManager am = ActivityManager.getService();
10849            if (am != null) {
10850                try {
10851                    am.killApplication(pkgName, appId, userId, reason);
10852                } catch (RemoteException e) {
10853                }
10854            }
10855        } finally {
10856            Binder.restoreCallingIdentity(token);
10857        }
10858    }
10859
10860    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10861        // Remove the parent package setting
10862        PackageSetting ps = (PackageSetting) pkg.mExtras;
10863        if (ps != null) {
10864            removePackageLI(ps, chatty);
10865        }
10866        // Remove the child package setting
10867        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10868        for (int i = 0; i < childCount; i++) {
10869            PackageParser.Package childPkg = pkg.childPackages.get(i);
10870            ps = (PackageSetting) childPkg.mExtras;
10871            if (ps != null) {
10872                removePackageLI(ps, chatty);
10873            }
10874        }
10875    }
10876
10877    void removePackageLI(PackageSetting ps, boolean chatty) {
10878        if (DEBUG_INSTALL) {
10879            if (chatty)
10880                Log.d(TAG, "Removing package " + ps.name);
10881        }
10882
10883        // writer
10884        synchronized (mPackages) {
10885            mPackages.remove(ps.name);
10886            final PackageParser.Package pkg = ps.pkg;
10887            if (pkg != null) {
10888                cleanPackageDataStructuresLILPw(pkg, chatty);
10889            }
10890        }
10891    }
10892
10893    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10894        if (DEBUG_INSTALL) {
10895            if (chatty)
10896                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10897        }
10898
10899        // writer
10900        synchronized (mPackages) {
10901            // Remove the parent package
10902            mPackages.remove(pkg.applicationInfo.packageName);
10903            cleanPackageDataStructuresLILPw(pkg, chatty);
10904
10905            // Remove the child packages
10906            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10907            for (int i = 0; i < childCount; i++) {
10908                PackageParser.Package childPkg = pkg.childPackages.get(i);
10909                mPackages.remove(childPkg.applicationInfo.packageName);
10910                cleanPackageDataStructuresLILPw(childPkg, chatty);
10911            }
10912        }
10913    }
10914
10915    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10916        int N = pkg.providers.size();
10917        StringBuilder r = null;
10918        int i;
10919        for (i=0; i<N; i++) {
10920            PackageParser.Provider p = pkg.providers.get(i);
10921            mProviders.removeProvider(p);
10922            if (p.info.authority == null) {
10923
10924                /* There was another ContentProvider with this authority when
10925                 * this app was installed so this authority is null,
10926                 * Ignore it as we don't have to unregister the provider.
10927                 */
10928                continue;
10929            }
10930            String names[] = p.info.authority.split(";");
10931            for (int j = 0; j < names.length; j++) {
10932                if (mProvidersByAuthority.get(names[j]) == p) {
10933                    mProvidersByAuthority.remove(names[j]);
10934                    if (DEBUG_REMOVE) {
10935                        if (chatty)
10936                            Log.d(TAG, "Unregistered content provider: " + names[j]
10937                                    + ", className = " + p.info.name + ", isSyncable = "
10938                                    + p.info.isSyncable);
10939                    }
10940                }
10941            }
10942            if (DEBUG_REMOVE && chatty) {
10943                if (r == null) {
10944                    r = new StringBuilder(256);
10945                } else {
10946                    r.append(' ');
10947                }
10948                r.append(p.info.name);
10949            }
10950        }
10951        if (r != null) {
10952            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10953        }
10954
10955        N = pkg.services.size();
10956        r = null;
10957        for (i=0; i<N; i++) {
10958            PackageParser.Service s = pkg.services.get(i);
10959            mServices.removeService(s);
10960            if (chatty) {
10961                if (r == null) {
10962                    r = new StringBuilder(256);
10963                } else {
10964                    r.append(' ');
10965                }
10966                r.append(s.info.name);
10967            }
10968        }
10969        if (r != null) {
10970            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10971        }
10972
10973        N = pkg.receivers.size();
10974        r = null;
10975        for (i=0; i<N; i++) {
10976            PackageParser.Activity a = pkg.receivers.get(i);
10977            mReceivers.removeActivity(a, "receiver");
10978            if (DEBUG_REMOVE && chatty) {
10979                if (r == null) {
10980                    r = new StringBuilder(256);
10981                } else {
10982                    r.append(' ');
10983                }
10984                r.append(a.info.name);
10985            }
10986        }
10987        if (r != null) {
10988            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10989        }
10990
10991        N = pkg.activities.size();
10992        r = null;
10993        for (i=0; i<N; i++) {
10994            PackageParser.Activity a = pkg.activities.get(i);
10995            mActivities.removeActivity(a, "activity");
10996            if (DEBUG_REMOVE && chatty) {
10997                if (r == null) {
10998                    r = new StringBuilder(256);
10999                } else {
11000                    r.append(' ');
11001                }
11002                r.append(a.info.name);
11003            }
11004        }
11005        if (r != null) {
11006            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11007        }
11008
11009        N = pkg.permissions.size();
11010        r = null;
11011        for (i=0; i<N; i++) {
11012            PackageParser.Permission p = pkg.permissions.get(i);
11013            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11014            if (bp == null) {
11015                bp = mSettings.mPermissionTrees.get(p.info.name);
11016            }
11017            if (bp != null && bp.perm == p) {
11018                bp.perm = null;
11019                if (DEBUG_REMOVE && chatty) {
11020                    if (r == null) {
11021                        r = new StringBuilder(256);
11022                    } else {
11023                        r.append(' ');
11024                    }
11025                    r.append(p.info.name);
11026                }
11027            }
11028            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11029                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11030                if (appOpPkgs != null) {
11031                    appOpPkgs.remove(pkg.packageName);
11032                }
11033            }
11034        }
11035        if (r != null) {
11036            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11037        }
11038
11039        N = pkg.requestedPermissions.size();
11040        r = null;
11041        for (i=0; i<N; i++) {
11042            String perm = pkg.requestedPermissions.get(i);
11043            BasePermission bp = mSettings.mPermissions.get(perm);
11044            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11045                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11046                if (appOpPkgs != null) {
11047                    appOpPkgs.remove(pkg.packageName);
11048                    if (appOpPkgs.isEmpty()) {
11049                        mAppOpPermissionPackages.remove(perm);
11050                    }
11051                }
11052            }
11053        }
11054        if (r != null) {
11055            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11056        }
11057
11058        N = pkg.instrumentation.size();
11059        r = null;
11060        for (i=0; i<N; i++) {
11061            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11062            mInstrumentation.remove(a.getComponentName());
11063            if (DEBUG_REMOVE && chatty) {
11064                if (r == null) {
11065                    r = new StringBuilder(256);
11066                } else {
11067                    r.append(' ');
11068                }
11069                r.append(a.info.name);
11070            }
11071        }
11072        if (r != null) {
11073            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11074        }
11075
11076        r = null;
11077        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11078            // Only system apps can hold shared libraries.
11079            if (pkg.libraryNames != null) {
11080                for (i = 0; i < pkg.libraryNames.size(); i++) {
11081                    String name = pkg.libraryNames.get(i);
11082                    if (removeSharedLibraryLPw(name, 0)) {
11083                        if (DEBUG_REMOVE && chatty) {
11084                            if (r == null) {
11085                                r = new StringBuilder(256);
11086                            } else {
11087                                r.append(' ');
11088                            }
11089                            r.append(name);
11090                        }
11091                    }
11092                }
11093            }
11094        }
11095
11096        r = null;
11097
11098        // Any package can hold static shared libraries.
11099        if (pkg.staticSharedLibName != null) {
11100            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11101                if (DEBUG_REMOVE && chatty) {
11102                    if (r == null) {
11103                        r = new StringBuilder(256);
11104                    } else {
11105                        r.append(' ');
11106                    }
11107                    r.append(pkg.staticSharedLibName);
11108                }
11109            }
11110        }
11111
11112        if (r != null) {
11113            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11114        }
11115    }
11116
11117    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11118        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11119            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11120                return true;
11121            }
11122        }
11123        return false;
11124    }
11125
11126    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11127    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11128    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11129
11130    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11131        // Update the parent permissions
11132        updatePermissionsLPw(pkg.packageName, pkg, flags);
11133        // Update the child permissions
11134        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11135        for (int i = 0; i < childCount; i++) {
11136            PackageParser.Package childPkg = pkg.childPackages.get(i);
11137            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11138        }
11139    }
11140
11141    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11142            int flags) {
11143        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11144        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11145    }
11146
11147    private void updatePermissionsLPw(String changingPkg,
11148            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11149        // Make sure there are no dangling permission trees.
11150        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11151        while (it.hasNext()) {
11152            final BasePermission bp = it.next();
11153            if (bp.packageSetting == null) {
11154                // We may not yet have parsed the package, so just see if
11155                // we still know about its settings.
11156                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11157            }
11158            if (bp.packageSetting == null) {
11159                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11160                        + " from package " + bp.sourcePackage);
11161                it.remove();
11162            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11163                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11164                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11165                            + " from package " + bp.sourcePackage);
11166                    flags |= UPDATE_PERMISSIONS_ALL;
11167                    it.remove();
11168                }
11169            }
11170        }
11171
11172        // Make sure all dynamic permissions have been assigned to a package,
11173        // and make sure there are no dangling permissions.
11174        it = mSettings.mPermissions.values().iterator();
11175        while (it.hasNext()) {
11176            final BasePermission bp = it.next();
11177            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11178                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11179                        + bp.name + " pkg=" + bp.sourcePackage
11180                        + " info=" + bp.pendingInfo);
11181                if (bp.packageSetting == null && bp.pendingInfo != null) {
11182                    final BasePermission tree = findPermissionTreeLP(bp.name);
11183                    if (tree != null && tree.perm != null) {
11184                        bp.packageSetting = tree.packageSetting;
11185                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11186                                new PermissionInfo(bp.pendingInfo));
11187                        bp.perm.info.packageName = tree.perm.info.packageName;
11188                        bp.perm.info.name = bp.name;
11189                        bp.uid = tree.uid;
11190                    }
11191                }
11192            }
11193            if (bp.packageSetting == null) {
11194                // We may not yet have parsed the package, so just see if
11195                // we still know about its settings.
11196                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11197            }
11198            if (bp.packageSetting == null) {
11199                Slog.w(TAG, "Removing dangling permission: " + bp.name
11200                        + " from package " + bp.sourcePackage);
11201                it.remove();
11202            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11203                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11204                    Slog.i(TAG, "Removing old permission: " + bp.name
11205                            + " from package " + bp.sourcePackage);
11206                    flags |= UPDATE_PERMISSIONS_ALL;
11207                    it.remove();
11208                }
11209            }
11210        }
11211
11212        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11213        // Now update the permissions for all packages, in particular
11214        // replace the granted permissions of the system packages.
11215        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11216            for (PackageParser.Package pkg : mPackages.values()) {
11217                if (pkg != pkgInfo) {
11218                    // Only replace for packages on requested volume
11219                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11220                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11221                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11222                    grantPermissionsLPw(pkg, replace, changingPkg);
11223                }
11224            }
11225        }
11226
11227        if (pkgInfo != null) {
11228            // Only replace for packages on requested volume
11229            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11230            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11231                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11232            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11233        }
11234        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11235    }
11236
11237    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11238            String packageOfInterest) {
11239        // IMPORTANT: There are two types of permissions: install and runtime.
11240        // Install time permissions are granted when the app is installed to
11241        // all device users and users added in the future. Runtime permissions
11242        // are granted at runtime explicitly to specific users. Normal and signature
11243        // protected permissions are install time permissions. Dangerous permissions
11244        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11245        // otherwise they are runtime permissions. This function does not manage
11246        // runtime permissions except for the case an app targeting Lollipop MR1
11247        // being upgraded to target a newer SDK, in which case dangerous permissions
11248        // are transformed from install time to runtime ones.
11249
11250        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11251        if (ps == null) {
11252            return;
11253        }
11254
11255        PermissionsState permissionsState = ps.getPermissionsState();
11256        PermissionsState origPermissions = permissionsState;
11257
11258        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11259
11260        boolean runtimePermissionsRevoked = false;
11261        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11262
11263        boolean changedInstallPermission = false;
11264
11265        if (replace) {
11266            ps.installPermissionsFixed = false;
11267            if (!ps.isSharedUser()) {
11268                origPermissions = new PermissionsState(permissionsState);
11269                permissionsState.reset();
11270            } else {
11271                // We need to know only about runtime permission changes since the
11272                // calling code always writes the install permissions state but
11273                // the runtime ones are written only if changed. The only cases of
11274                // changed runtime permissions here are promotion of an install to
11275                // runtime and revocation of a runtime from a shared user.
11276                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11277                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11278                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11279                    runtimePermissionsRevoked = true;
11280                }
11281            }
11282        }
11283
11284        permissionsState.setGlobalGids(mGlobalGids);
11285
11286        final int N = pkg.requestedPermissions.size();
11287        for (int i=0; i<N; i++) {
11288            final String name = pkg.requestedPermissions.get(i);
11289            final BasePermission bp = mSettings.mPermissions.get(name);
11290
11291            if (DEBUG_INSTALL) {
11292                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11293            }
11294
11295            if (bp == null || bp.packageSetting == null) {
11296                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11297                    Slog.w(TAG, "Unknown permission " + name
11298                            + " in package " + pkg.packageName);
11299                }
11300                continue;
11301            }
11302
11303
11304            // Limit ephemeral apps to ephemeral allowed permissions.
11305            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11306                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11307                        + pkg.packageName);
11308                continue;
11309            }
11310
11311            final String perm = bp.name;
11312            boolean allowedSig = false;
11313            int grant = GRANT_DENIED;
11314
11315            // Keep track of app op permissions.
11316            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11317                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11318                if (pkgs == null) {
11319                    pkgs = new ArraySet<>();
11320                    mAppOpPermissionPackages.put(bp.name, pkgs);
11321                }
11322                pkgs.add(pkg.packageName);
11323            }
11324
11325            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11326            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11327                    >= Build.VERSION_CODES.M;
11328            switch (level) {
11329                case PermissionInfo.PROTECTION_NORMAL: {
11330                    // For all apps normal permissions are install time ones.
11331                    grant = GRANT_INSTALL;
11332                } break;
11333
11334                case PermissionInfo.PROTECTION_DANGEROUS: {
11335                    // If a permission review is required for legacy apps we represent
11336                    // their permissions as always granted runtime ones since we need
11337                    // to keep the review required permission flag per user while an
11338                    // install permission's state is shared across all users.
11339                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11340                        // For legacy apps dangerous permissions are install time ones.
11341                        grant = GRANT_INSTALL;
11342                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11343                        // For legacy apps that became modern, install becomes runtime.
11344                        grant = GRANT_UPGRADE;
11345                    } else if (mPromoteSystemApps
11346                            && isSystemApp(ps)
11347                            && mExistingSystemPackages.contains(ps.name)) {
11348                        // For legacy system apps, install becomes runtime.
11349                        // We cannot check hasInstallPermission() for system apps since those
11350                        // permissions were granted implicitly and not persisted pre-M.
11351                        grant = GRANT_UPGRADE;
11352                    } else {
11353                        // For modern apps keep runtime permissions unchanged.
11354                        grant = GRANT_RUNTIME;
11355                    }
11356                } break;
11357
11358                case PermissionInfo.PROTECTION_SIGNATURE: {
11359                    // For all apps signature permissions are install time ones.
11360                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11361                    if (allowedSig) {
11362                        grant = GRANT_INSTALL;
11363                    }
11364                } break;
11365            }
11366
11367            if (DEBUG_INSTALL) {
11368                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11369            }
11370
11371            if (grant != GRANT_DENIED) {
11372                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11373                    // If this is an existing, non-system package, then
11374                    // we can't add any new permissions to it.
11375                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11376                        // Except...  if this is a permission that was added
11377                        // to the platform (note: need to only do this when
11378                        // updating the platform).
11379                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11380                            grant = GRANT_DENIED;
11381                        }
11382                    }
11383                }
11384
11385                switch (grant) {
11386                    case GRANT_INSTALL: {
11387                        // Revoke this as runtime permission to handle the case of
11388                        // a runtime permission being downgraded to an install one.
11389                        // Also in permission review mode we keep dangerous permissions
11390                        // for legacy apps
11391                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11392                            if (origPermissions.getRuntimePermissionState(
11393                                    bp.name, userId) != null) {
11394                                // Revoke the runtime permission and clear the flags.
11395                                origPermissions.revokeRuntimePermission(bp, userId);
11396                                origPermissions.updatePermissionFlags(bp, userId,
11397                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11398                                // If we revoked a permission permission, we have to write.
11399                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11400                                        changedRuntimePermissionUserIds, userId);
11401                            }
11402                        }
11403                        // Grant an install permission.
11404                        if (permissionsState.grantInstallPermission(bp) !=
11405                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11406                            changedInstallPermission = true;
11407                        }
11408                    } break;
11409
11410                    case GRANT_RUNTIME: {
11411                        // Grant previously granted runtime permissions.
11412                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11413                            PermissionState permissionState = origPermissions
11414                                    .getRuntimePermissionState(bp.name, userId);
11415                            int flags = permissionState != null
11416                                    ? permissionState.getFlags() : 0;
11417                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11418                                // Don't propagate the permission in a permission review mode if
11419                                // the former was revoked, i.e. marked to not propagate on upgrade.
11420                                // Note that in a permission review mode install permissions are
11421                                // represented as constantly granted runtime ones since we need to
11422                                // keep a per user state associated with the permission. Also the
11423                                // revoke on upgrade flag is no longer applicable and is reset.
11424                                final boolean revokeOnUpgrade = (flags & PackageManager
11425                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11426                                if (revokeOnUpgrade) {
11427                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11428                                    // Since we changed the flags, we have to write.
11429                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11430                                            changedRuntimePermissionUserIds, userId);
11431                                }
11432                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11433                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11434                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11435                                        // If we cannot put the permission as it was,
11436                                        // we have to write.
11437                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11438                                                changedRuntimePermissionUserIds, userId);
11439                                    }
11440                                }
11441
11442                                // If the app supports runtime permissions no need for a review.
11443                                if (mPermissionReviewRequired
11444                                        && appSupportsRuntimePermissions
11445                                        && (flags & PackageManager
11446                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11447                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11448                                    // Since we changed the flags, we have to write.
11449                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11450                                            changedRuntimePermissionUserIds, userId);
11451                                }
11452                            } else if (mPermissionReviewRequired
11453                                    && !appSupportsRuntimePermissions) {
11454                                // For legacy apps that need a permission review, every new
11455                                // runtime permission is granted but it is pending a review.
11456                                // We also need to review only platform defined runtime
11457                                // permissions as these are the only ones the platform knows
11458                                // how to disable the API to simulate revocation as legacy
11459                                // apps don't expect to run with revoked permissions.
11460                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11461                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11462                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11463                                        // We changed the flags, hence have to write.
11464                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11465                                                changedRuntimePermissionUserIds, userId);
11466                                    }
11467                                }
11468                                if (permissionsState.grantRuntimePermission(bp, userId)
11469                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11470                                    // We changed the permission, hence have to write.
11471                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11472                                            changedRuntimePermissionUserIds, userId);
11473                                }
11474                            }
11475                            // Propagate the permission flags.
11476                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11477                        }
11478                    } break;
11479
11480                    case GRANT_UPGRADE: {
11481                        // Grant runtime permissions for a previously held install permission.
11482                        PermissionState permissionState = origPermissions
11483                                .getInstallPermissionState(bp.name);
11484                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11485
11486                        if (origPermissions.revokeInstallPermission(bp)
11487                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11488                            // We will be transferring the permission flags, so clear them.
11489                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11490                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11491                            changedInstallPermission = true;
11492                        }
11493
11494                        // If the permission is not to be promoted to runtime we ignore it and
11495                        // also its other flags as they are not applicable to install permissions.
11496                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11497                            for (int userId : currentUserIds) {
11498                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11499                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11500                                    // Transfer the permission flags.
11501                                    permissionsState.updatePermissionFlags(bp, userId,
11502                                            flags, flags);
11503                                    // If we granted the permission, we have to write.
11504                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11505                                            changedRuntimePermissionUserIds, userId);
11506                                }
11507                            }
11508                        }
11509                    } break;
11510
11511                    default: {
11512                        if (packageOfInterest == null
11513                                || packageOfInterest.equals(pkg.packageName)) {
11514                            Slog.w(TAG, "Not granting permission " + perm
11515                                    + " to package " + pkg.packageName
11516                                    + " because it was previously installed without");
11517                        }
11518                    } break;
11519                }
11520            } else {
11521                if (permissionsState.revokeInstallPermission(bp) !=
11522                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11523                    // Also drop the permission flags.
11524                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11525                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11526                    changedInstallPermission = true;
11527                    Slog.i(TAG, "Un-granting permission " + perm
11528                            + " from package " + pkg.packageName
11529                            + " (protectionLevel=" + bp.protectionLevel
11530                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11531                            + ")");
11532                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11533                    // Don't print warning for app op permissions, since it is fine for them
11534                    // not to be granted, there is a UI for the user to decide.
11535                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11536                        Slog.w(TAG, "Not granting permission " + perm
11537                                + " to package " + pkg.packageName
11538                                + " (protectionLevel=" + bp.protectionLevel
11539                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11540                                + ")");
11541                    }
11542                }
11543            }
11544        }
11545
11546        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11547                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11548            // This is the first that we have heard about this package, so the
11549            // permissions we have now selected are fixed until explicitly
11550            // changed.
11551            ps.installPermissionsFixed = true;
11552        }
11553
11554        // Persist the runtime permissions state for users with changes. If permissions
11555        // were revoked because no app in the shared user declares them we have to
11556        // write synchronously to avoid losing runtime permissions state.
11557        for (int userId : changedRuntimePermissionUserIds) {
11558            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11559        }
11560    }
11561
11562    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11563        boolean allowed = false;
11564        final int NP = PackageParser.NEW_PERMISSIONS.length;
11565        for (int ip=0; ip<NP; ip++) {
11566            final PackageParser.NewPermissionInfo npi
11567                    = PackageParser.NEW_PERMISSIONS[ip];
11568            if (npi.name.equals(perm)
11569                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11570                allowed = true;
11571                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11572                        + pkg.packageName);
11573                break;
11574            }
11575        }
11576        return allowed;
11577    }
11578
11579    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11580            BasePermission bp, PermissionsState origPermissions) {
11581        boolean privilegedPermission = (bp.protectionLevel
11582                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11583        boolean privappPermissionsDisable =
11584                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11585        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11586        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11587        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11588                && !platformPackage && platformPermission) {
11589            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11590                    .getPrivAppPermissions(pkg.packageName);
11591            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11592            if (!whitelisted) {
11593                Slog.w(TAG, "Privileged permission " + perm + " for package "
11594                        + pkg.packageName + " - not in privapp-permissions whitelist");
11595                // Only report violations for apps on system image
11596                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11597                    if (mPrivappPermissionsViolations == null) {
11598                        mPrivappPermissionsViolations = new ArraySet<>();
11599                    }
11600                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11601                }
11602                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11603                    return false;
11604                }
11605            }
11606        }
11607        boolean allowed = (compareSignatures(
11608                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11609                        == PackageManager.SIGNATURE_MATCH)
11610                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11611                        == PackageManager.SIGNATURE_MATCH);
11612        if (!allowed && privilegedPermission) {
11613            if (isSystemApp(pkg)) {
11614                // For updated system applications, a system permission
11615                // is granted only if it had been defined by the original application.
11616                if (pkg.isUpdatedSystemApp()) {
11617                    final PackageSetting sysPs = mSettings
11618                            .getDisabledSystemPkgLPr(pkg.packageName);
11619                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11620                        // If the original was granted this permission, we take
11621                        // that grant decision as read and propagate it to the
11622                        // update.
11623                        if (sysPs.isPrivileged()) {
11624                            allowed = true;
11625                        }
11626                    } else {
11627                        // The system apk may have been updated with an older
11628                        // version of the one on the data partition, but which
11629                        // granted a new system permission that it didn't have
11630                        // before.  In this case we do want to allow the app to
11631                        // now get the new permission if the ancestral apk is
11632                        // privileged to get it.
11633                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11634                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11635                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11636                                    allowed = true;
11637                                    break;
11638                                }
11639                            }
11640                        }
11641                        // Also if a privileged parent package on the system image or any of
11642                        // its children requested a privileged permission, the updated child
11643                        // packages can also get the permission.
11644                        if (pkg.parentPackage != null) {
11645                            final PackageSetting disabledSysParentPs = mSettings
11646                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11647                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11648                                    && disabledSysParentPs.isPrivileged()) {
11649                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11650                                    allowed = true;
11651                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11652                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11653                                    for (int i = 0; i < count; i++) {
11654                                        PackageParser.Package disabledSysChildPkg =
11655                                                disabledSysParentPs.pkg.childPackages.get(i);
11656                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11657                                                perm)) {
11658                                            allowed = true;
11659                                            break;
11660                                        }
11661                                    }
11662                                }
11663                            }
11664                        }
11665                    }
11666                } else {
11667                    allowed = isPrivilegedApp(pkg);
11668                }
11669            }
11670        }
11671        if (!allowed) {
11672            if (!allowed && (bp.protectionLevel
11673                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11674                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11675                // If this was a previously normal/dangerous permission that got moved
11676                // to a system permission as part of the runtime permission redesign, then
11677                // we still want to blindly grant it to old apps.
11678                allowed = true;
11679            }
11680            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11681                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11682                // If this permission is to be granted to the system installer and
11683                // this app is an installer, then it gets the permission.
11684                allowed = true;
11685            }
11686            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11687                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11688                // If this permission is to be granted to the system verifier and
11689                // this app is a verifier, then it gets the permission.
11690                allowed = true;
11691            }
11692            if (!allowed && (bp.protectionLevel
11693                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11694                    && isSystemApp(pkg)) {
11695                // Any pre-installed system app is allowed to get this permission.
11696                allowed = true;
11697            }
11698            if (!allowed && (bp.protectionLevel
11699                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11700                // For development permissions, a development permission
11701                // is granted only if it was already granted.
11702                allowed = origPermissions.hasInstallPermission(perm);
11703            }
11704            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11705                    && pkg.packageName.equals(mSetupWizardPackage)) {
11706                // If this permission is to be granted to the system setup wizard and
11707                // this app is a setup wizard, then it gets the permission.
11708                allowed = true;
11709            }
11710        }
11711        return allowed;
11712    }
11713
11714    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11715        final int permCount = pkg.requestedPermissions.size();
11716        for (int j = 0; j < permCount; j++) {
11717            String requestedPermission = pkg.requestedPermissions.get(j);
11718            if (permission.equals(requestedPermission)) {
11719                return true;
11720            }
11721        }
11722        return false;
11723    }
11724
11725    final class ActivityIntentResolver
11726            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11727        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11728                boolean defaultOnly, int userId) {
11729            if (!sUserManager.exists(userId)) return null;
11730            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11731            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11732        }
11733
11734        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11735                int userId) {
11736            if (!sUserManager.exists(userId)) return null;
11737            mFlags = flags;
11738            return super.queryIntent(intent, resolvedType,
11739                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11740                    userId);
11741        }
11742
11743        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11744                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11745            if (!sUserManager.exists(userId)) return null;
11746            if (packageActivities == null) {
11747                return null;
11748            }
11749            mFlags = flags;
11750            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11751            final int N = packageActivities.size();
11752            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11753                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11754
11755            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11756            for (int i = 0; i < N; ++i) {
11757                intentFilters = packageActivities.get(i).intents;
11758                if (intentFilters != null && intentFilters.size() > 0) {
11759                    PackageParser.ActivityIntentInfo[] array =
11760                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11761                    intentFilters.toArray(array);
11762                    listCut.add(array);
11763                }
11764            }
11765            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11766        }
11767
11768        /**
11769         * Finds a privileged activity that matches the specified activity names.
11770         */
11771        private PackageParser.Activity findMatchingActivity(
11772                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11773            for (PackageParser.Activity sysActivity : activityList) {
11774                if (sysActivity.info.name.equals(activityInfo.name)) {
11775                    return sysActivity;
11776                }
11777                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11778                    return sysActivity;
11779                }
11780                if (sysActivity.info.targetActivity != null) {
11781                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11782                        return sysActivity;
11783                    }
11784                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11785                        return sysActivity;
11786                    }
11787                }
11788            }
11789            return null;
11790        }
11791
11792        public class IterGenerator<E> {
11793            public Iterator<E> generate(ActivityIntentInfo info) {
11794                return null;
11795            }
11796        }
11797
11798        public class ActionIterGenerator extends IterGenerator<String> {
11799            @Override
11800            public Iterator<String> generate(ActivityIntentInfo info) {
11801                return info.actionsIterator();
11802            }
11803        }
11804
11805        public class CategoriesIterGenerator extends IterGenerator<String> {
11806            @Override
11807            public Iterator<String> generate(ActivityIntentInfo info) {
11808                return info.categoriesIterator();
11809            }
11810        }
11811
11812        public class SchemesIterGenerator extends IterGenerator<String> {
11813            @Override
11814            public Iterator<String> generate(ActivityIntentInfo info) {
11815                return info.schemesIterator();
11816            }
11817        }
11818
11819        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11820            @Override
11821            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11822                return info.authoritiesIterator();
11823            }
11824        }
11825
11826        /**
11827         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11828         * MODIFIED. Do not pass in a list that should not be changed.
11829         */
11830        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11831                IterGenerator<T> generator, Iterator<T> searchIterator) {
11832            // loop through the set of actions; every one must be found in the intent filter
11833            while (searchIterator.hasNext()) {
11834                // we must have at least one filter in the list to consider a match
11835                if (intentList.size() == 0) {
11836                    break;
11837                }
11838
11839                final T searchAction = searchIterator.next();
11840
11841                // loop through the set of intent filters
11842                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11843                while (intentIter.hasNext()) {
11844                    final ActivityIntentInfo intentInfo = intentIter.next();
11845                    boolean selectionFound = false;
11846
11847                    // loop through the intent filter's selection criteria; at least one
11848                    // of them must match the searched criteria
11849                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11850                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11851                        final T intentSelection = intentSelectionIter.next();
11852                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11853                            selectionFound = true;
11854                            break;
11855                        }
11856                    }
11857
11858                    // the selection criteria wasn't found in this filter's set; this filter
11859                    // is not a potential match
11860                    if (!selectionFound) {
11861                        intentIter.remove();
11862                    }
11863                }
11864            }
11865        }
11866
11867        private boolean isProtectedAction(ActivityIntentInfo filter) {
11868            final Iterator<String> actionsIter = filter.actionsIterator();
11869            while (actionsIter != null && actionsIter.hasNext()) {
11870                final String filterAction = actionsIter.next();
11871                if (PROTECTED_ACTIONS.contains(filterAction)) {
11872                    return true;
11873                }
11874            }
11875            return false;
11876        }
11877
11878        /**
11879         * Adjusts the priority of the given intent filter according to policy.
11880         * <p>
11881         * <ul>
11882         * <li>The priority for non privileged applications is capped to '0'</li>
11883         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11884         * <li>The priority for unbundled updates to privileged applications is capped to the
11885         *      priority defined on the system partition</li>
11886         * </ul>
11887         * <p>
11888         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11889         * allowed to obtain any priority on any action.
11890         */
11891        private void adjustPriority(
11892                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11893            // nothing to do; priority is fine as-is
11894            if (intent.getPriority() <= 0) {
11895                return;
11896            }
11897
11898            final ActivityInfo activityInfo = intent.activity.info;
11899            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11900
11901            final boolean privilegedApp =
11902                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11903            if (!privilegedApp) {
11904                // non-privileged applications can never define a priority >0
11905                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11906                        + " package: " + applicationInfo.packageName
11907                        + " activity: " + intent.activity.className
11908                        + " origPrio: " + intent.getPriority());
11909                intent.setPriority(0);
11910                return;
11911            }
11912
11913            if (systemActivities == null) {
11914                // the system package is not disabled; we're parsing the system partition
11915                if (isProtectedAction(intent)) {
11916                    if (mDeferProtectedFilters) {
11917                        // We can't deal with these just yet. No component should ever obtain a
11918                        // >0 priority for a protected actions, with ONE exception -- the setup
11919                        // wizard. The setup wizard, however, cannot be known until we're able to
11920                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11921                        // until all intent filters have been processed. Chicken, meet egg.
11922                        // Let the filter temporarily have a high priority and rectify the
11923                        // priorities after all system packages have been scanned.
11924                        mProtectedFilters.add(intent);
11925                        if (DEBUG_FILTERS) {
11926                            Slog.i(TAG, "Protected action; save for later;"
11927                                    + " package: " + applicationInfo.packageName
11928                                    + " activity: " + intent.activity.className
11929                                    + " origPrio: " + intent.getPriority());
11930                        }
11931                        return;
11932                    } else {
11933                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11934                            Slog.i(TAG, "No setup wizard;"
11935                                + " All protected intents capped to priority 0");
11936                        }
11937                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11938                            if (DEBUG_FILTERS) {
11939                                Slog.i(TAG, "Found setup wizard;"
11940                                    + " allow priority " + intent.getPriority() + ";"
11941                                    + " package: " + intent.activity.info.packageName
11942                                    + " activity: " + intent.activity.className
11943                                    + " priority: " + intent.getPriority());
11944                            }
11945                            // setup wizard gets whatever it wants
11946                            return;
11947                        }
11948                        Slog.w(TAG, "Protected action; cap priority to 0;"
11949                                + " package: " + intent.activity.info.packageName
11950                                + " activity: " + intent.activity.className
11951                                + " origPrio: " + intent.getPriority());
11952                        intent.setPriority(0);
11953                        return;
11954                    }
11955                }
11956                // privileged apps on the system image get whatever priority they request
11957                return;
11958            }
11959
11960            // privileged app unbundled update ... try to find the same activity
11961            final PackageParser.Activity foundActivity =
11962                    findMatchingActivity(systemActivities, activityInfo);
11963            if (foundActivity == null) {
11964                // this is a new activity; it cannot obtain >0 priority
11965                if (DEBUG_FILTERS) {
11966                    Slog.i(TAG, "New activity; cap priority to 0;"
11967                            + " package: " + applicationInfo.packageName
11968                            + " activity: " + intent.activity.className
11969                            + " origPrio: " + intent.getPriority());
11970                }
11971                intent.setPriority(0);
11972                return;
11973            }
11974
11975            // found activity, now check for filter equivalence
11976
11977            // a shallow copy is enough; we modify the list, not its contents
11978            final List<ActivityIntentInfo> intentListCopy =
11979                    new ArrayList<>(foundActivity.intents);
11980            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11981
11982            // find matching action subsets
11983            final Iterator<String> actionsIterator = intent.actionsIterator();
11984            if (actionsIterator != null) {
11985                getIntentListSubset(
11986                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11987                if (intentListCopy.size() == 0) {
11988                    // no more intents to match; we're not equivalent
11989                    if (DEBUG_FILTERS) {
11990                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11991                                + " package: " + applicationInfo.packageName
11992                                + " activity: " + intent.activity.className
11993                                + " origPrio: " + intent.getPriority());
11994                    }
11995                    intent.setPriority(0);
11996                    return;
11997                }
11998            }
11999
12000            // find matching category subsets
12001            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12002            if (categoriesIterator != null) {
12003                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12004                        categoriesIterator);
12005                if (intentListCopy.size() == 0) {
12006                    // no more intents to match; we're not equivalent
12007                    if (DEBUG_FILTERS) {
12008                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12009                                + " package: " + applicationInfo.packageName
12010                                + " activity: " + intent.activity.className
12011                                + " origPrio: " + intent.getPriority());
12012                    }
12013                    intent.setPriority(0);
12014                    return;
12015                }
12016            }
12017
12018            // find matching schemes subsets
12019            final Iterator<String> schemesIterator = intent.schemesIterator();
12020            if (schemesIterator != null) {
12021                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12022                        schemesIterator);
12023                if (intentListCopy.size() == 0) {
12024                    // no more intents to match; we're not equivalent
12025                    if (DEBUG_FILTERS) {
12026                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12027                                + " package: " + applicationInfo.packageName
12028                                + " activity: " + intent.activity.className
12029                                + " origPrio: " + intent.getPriority());
12030                    }
12031                    intent.setPriority(0);
12032                    return;
12033                }
12034            }
12035
12036            // find matching authorities subsets
12037            final Iterator<IntentFilter.AuthorityEntry>
12038                    authoritiesIterator = intent.authoritiesIterator();
12039            if (authoritiesIterator != null) {
12040                getIntentListSubset(intentListCopy,
12041                        new AuthoritiesIterGenerator(),
12042                        authoritiesIterator);
12043                if (intentListCopy.size() == 0) {
12044                    // no more intents to match; we're not equivalent
12045                    if (DEBUG_FILTERS) {
12046                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12047                                + " package: " + applicationInfo.packageName
12048                                + " activity: " + intent.activity.className
12049                                + " origPrio: " + intent.getPriority());
12050                    }
12051                    intent.setPriority(0);
12052                    return;
12053                }
12054            }
12055
12056            // we found matching filter(s); app gets the max priority of all intents
12057            int cappedPriority = 0;
12058            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12059                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12060            }
12061            if (intent.getPriority() > cappedPriority) {
12062                if (DEBUG_FILTERS) {
12063                    Slog.i(TAG, "Found matching filter(s);"
12064                            + " cap priority to " + cappedPriority + ";"
12065                            + " package: " + applicationInfo.packageName
12066                            + " activity: " + intent.activity.className
12067                            + " origPrio: " + intent.getPriority());
12068                }
12069                intent.setPriority(cappedPriority);
12070                return;
12071            }
12072            // all this for nothing; the requested priority was <= what was on the system
12073        }
12074
12075        public final void addActivity(PackageParser.Activity a, String type) {
12076            mActivities.put(a.getComponentName(), a);
12077            if (DEBUG_SHOW_INFO)
12078                Log.v(
12079                TAG, "  " + type + " " +
12080                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12081            if (DEBUG_SHOW_INFO)
12082                Log.v(TAG, "    Class=" + a.info.name);
12083            final int NI = a.intents.size();
12084            for (int j=0; j<NI; j++) {
12085                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12086                if ("activity".equals(type)) {
12087                    final PackageSetting ps =
12088                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12089                    final List<PackageParser.Activity> systemActivities =
12090                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12091                    adjustPriority(systemActivities, intent);
12092                }
12093                if (DEBUG_SHOW_INFO) {
12094                    Log.v(TAG, "    IntentFilter:");
12095                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12096                }
12097                if (!intent.debugCheck()) {
12098                    Log.w(TAG, "==> For Activity " + a.info.name);
12099                }
12100                addFilter(intent);
12101            }
12102        }
12103
12104        public final void removeActivity(PackageParser.Activity a, String type) {
12105            mActivities.remove(a.getComponentName());
12106            if (DEBUG_SHOW_INFO) {
12107                Log.v(TAG, "  " + type + " "
12108                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12109                                : a.info.name) + ":");
12110                Log.v(TAG, "    Class=" + a.info.name);
12111            }
12112            final int NI = a.intents.size();
12113            for (int j=0; j<NI; j++) {
12114                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12115                if (DEBUG_SHOW_INFO) {
12116                    Log.v(TAG, "    IntentFilter:");
12117                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12118                }
12119                removeFilter(intent);
12120            }
12121        }
12122
12123        @Override
12124        protected boolean allowFilterResult(
12125                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12126            ActivityInfo filterAi = filter.activity.info;
12127            for (int i=dest.size()-1; i>=0; i--) {
12128                ActivityInfo destAi = dest.get(i).activityInfo;
12129                if (destAi.name == filterAi.name
12130                        && destAi.packageName == filterAi.packageName) {
12131                    return false;
12132                }
12133            }
12134            return true;
12135        }
12136
12137        @Override
12138        protected ActivityIntentInfo[] newArray(int size) {
12139            return new ActivityIntentInfo[size];
12140        }
12141
12142        @Override
12143        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12144            if (!sUserManager.exists(userId)) return true;
12145            PackageParser.Package p = filter.activity.owner;
12146            if (p != null) {
12147                PackageSetting ps = (PackageSetting)p.mExtras;
12148                if (ps != null) {
12149                    // System apps are never considered stopped for purposes of
12150                    // filtering, because there may be no way for the user to
12151                    // actually re-launch them.
12152                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12153                            && ps.getStopped(userId);
12154                }
12155            }
12156            return false;
12157        }
12158
12159        @Override
12160        protected boolean isPackageForFilter(String packageName,
12161                PackageParser.ActivityIntentInfo info) {
12162            return packageName.equals(info.activity.owner.packageName);
12163        }
12164
12165        @Override
12166        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12167                int match, int userId) {
12168            if (!sUserManager.exists(userId)) return null;
12169            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12170                return null;
12171            }
12172            final PackageParser.Activity activity = info.activity;
12173            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12174            if (ps == null) {
12175                return null;
12176            }
12177            final PackageUserState userState = ps.readUserState(userId);
12178            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12179                    userState, userId);
12180            if (ai == null) {
12181                return null;
12182            }
12183            final boolean matchVisibleToInstantApp =
12184                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12185            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12186            // throw out filters that aren't visible to ephemeral apps
12187            if (matchVisibleToInstantApp
12188                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12189                return null;
12190            }
12191            // throw out ephemeral filters if we're not explicitly requesting them
12192            if (!isInstantApp && userState.instantApp) {
12193                return null;
12194            }
12195            // throw out instant app filters if updates are available; will trigger
12196            // instant app resolution
12197            if (userState.instantApp && ps.isUpdateAvailable()) {
12198                return null;
12199            }
12200            final ResolveInfo res = new ResolveInfo();
12201            res.activityInfo = ai;
12202            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12203                res.filter = info;
12204            }
12205            if (info != null) {
12206                res.handleAllWebDataURI = info.handleAllWebDataURI();
12207            }
12208            res.priority = info.getPriority();
12209            res.preferredOrder = activity.owner.mPreferredOrder;
12210            //System.out.println("Result: " + res.activityInfo.className +
12211            //                   " = " + res.priority);
12212            res.match = match;
12213            res.isDefault = info.hasDefault;
12214            res.labelRes = info.labelRes;
12215            res.nonLocalizedLabel = info.nonLocalizedLabel;
12216            if (userNeedsBadging(userId)) {
12217                res.noResourceId = true;
12218            } else {
12219                res.icon = info.icon;
12220            }
12221            res.iconResourceId = info.icon;
12222            res.system = res.activityInfo.applicationInfo.isSystemApp();
12223            res.instantAppAvailable = userState.instantApp;
12224            return res;
12225        }
12226
12227        @Override
12228        protected void sortResults(List<ResolveInfo> results) {
12229            Collections.sort(results, mResolvePrioritySorter);
12230        }
12231
12232        @Override
12233        protected void dumpFilter(PrintWriter out, String prefix,
12234                PackageParser.ActivityIntentInfo filter) {
12235            out.print(prefix); out.print(
12236                    Integer.toHexString(System.identityHashCode(filter.activity)));
12237                    out.print(' ');
12238                    filter.activity.printComponentShortName(out);
12239                    out.print(" filter ");
12240                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12241        }
12242
12243        @Override
12244        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12245            return filter.activity;
12246        }
12247
12248        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12249            PackageParser.Activity activity = (PackageParser.Activity)label;
12250            out.print(prefix); out.print(
12251                    Integer.toHexString(System.identityHashCode(activity)));
12252                    out.print(' ');
12253                    activity.printComponentShortName(out);
12254            if (count > 1) {
12255                out.print(" ("); out.print(count); out.print(" filters)");
12256            }
12257            out.println();
12258        }
12259
12260        // Keys are String (activity class name), values are Activity.
12261        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12262                = new ArrayMap<ComponentName, PackageParser.Activity>();
12263        private int mFlags;
12264    }
12265
12266    private final class ServiceIntentResolver
12267            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12268        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12269                boolean defaultOnly, int userId) {
12270            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12271            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12272        }
12273
12274        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12275                int userId) {
12276            if (!sUserManager.exists(userId)) return null;
12277            mFlags = flags;
12278            return super.queryIntent(intent, resolvedType,
12279                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12280                    userId);
12281        }
12282
12283        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12284                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12285            if (!sUserManager.exists(userId)) return null;
12286            if (packageServices == null) {
12287                return null;
12288            }
12289            mFlags = flags;
12290            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12291            final int N = packageServices.size();
12292            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12293                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12294
12295            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12296            for (int i = 0; i < N; ++i) {
12297                intentFilters = packageServices.get(i).intents;
12298                if (intentFilters != null && intentFilters.size() > 0) {
12299                    PackageParser.ServiceIntentInfo[] array =
12300                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12301                    intentFilters.toArray(array);
12302                    listCut.add(array);
12303                }
12304            }
12305            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12306        }
12307
12308        public final void addService(PackageParser.Service s) {
12309            mServices.put(s.getComponentName(), s);
12310            if (DEBUG_SHOW_INFO) {
12311                Log.v(TAG, "  "
12312                        + (s.info.nonLocalizedLabel != null
12313                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12314                Log.v(TAG, "    Class=" + s.info.name);
12315            }
12316            final int NI = s.intents.size();
12317            int j;
12318            for (j=0; j<NI; j++) {
12319                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12320                if (DEBUG_SHOW_INFO) {
12321                    Log.v(TAG, "    IntentFilter:");
12322                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12323                }
12324                if (!intent.debugCheck()) {
12325                    Log.w(TAG, "==> For Service " + s.info.name);
12326                }
12327                addFilter(intent);
12328            }
12329        }
12330
12331        public final void removeService(PackageParser.Service s) {
12332            mServices.remove(s.getComponentName());
12333            if (DEBUG_SHOW_INFO) {
12334                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12335                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12336                Log.v(TAG, "    Class=" + s.info.name);
12337            }
12338            final int NI = s.intents.size();
12339            int j;
12340            for (j=0; j<NI; j++) {
12341                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12342                if (DEBUG_SHOW_INFO) {
12343                    Log.v(TAG, "    IntentFilter:");
12344                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12345                }
12346                removeFilter(intent);
12347            }
12348        }
12349
12350        @Override
12351        protected boolean allowFilterResult(
12352                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12353            ServiceInfo filterSi = filter.service.info;
12354            for (int i=dest.size()-1; i>=0; i--) {
12355                ServiceInfo destAi = dest.get(i).serviceInfo;
12356                if (destAi.name == filterSi.name
12357                        && destAi.packageName == filterSi.packageName) {
12358                    return false;
12359                }
12360            }
12361            return true;
12362        }
12363
12364        @Override
12365        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12366            return new PackageParser.ServiceIntentInfo[size];
12367        }
12368
12369        @Override
12370        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12371            if (!sUserManager.exists(userId)) return true;
12372            PackageParser.Package p = filter.service.owner;
12373            if (p != null) {
12374                PackageSetting ps = (PackageSetting)p.mExtras;
12375                if (ps != null) {
12376                    // System apps are never considered stopped for purposes of
12377                    // filtering, because there may be no way for the user to
12378                    // actually re-launch them.
12379                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12380                            && ps.getStopped(userId);
12381                }
12382            }
12383            return false;
12384        }
12385
12386        @Override
12387        protected boolean isPackageForFilter(String packageName,
12388                PackageParser.ServiceIntentInfo info) {
12389            return packageName.equals(info.service.owner.packageName);
12390        }
12391
12392        @Override
12393        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12394                int match, int userId) {
12395            if (!sUserManager.exists(userId)) return null;
12396            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12397            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12398                return null;
12399            }
12400            final PackageParser.Service service = info.service;
12401            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12402            if (ps == null) {
12403                return null;
12404            }
12405            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12406                    ps.readUserState(userId), userId);
12407            if (si == null) {
12408                return null;
12409            }
12410            final ResolveInfo res = new ResolveInfo();
12411            res.serviceInfo = si;
12412            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12413                res.filter = filter;
12414            }
12415            res.priority = info.getPriority();
12416            res.preferredOrder = service.owner.mPreferredOrder;
12417            res.match = match;
12418            res.isDefault = info.hasDefault;
12419            res.labelRes = info.labelRes;
12420            res.nonLocalizedLabel = info.nonLocalizedLabel;
12421            res.icon = info.icon;
12422            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12423            return res;
12424        }
12425
12426        @Override
12427        protected void sortResults(List<ResolveInfo> results) {
12428            Collections.sort(results, mResolvePrioritySorter);
12429        }
12430
12431        @Override
12432        protected void dumpFilter(PrintWriter out, String prefix,
12433                PackageParser.ServiceIntentInfo filter) {
12434            out.print(prefix); out.print(
12435                    Integer.toHexString(System.identityHashCode(filter.service)));
12436                    out.print(' ');
12437                    filter.service.printComponentShortName(out);
12438                    out.print(" filter ");
12439                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12440        }
12441
12442        @Override
12443        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12444            return filter.service;
12445        }
12446
12447        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12448            PackageParser.Service service = (PackageParser.Service)label;
12449            out.print(prefix); out.print(
12450                    Integer.toHexString(System.identityHashCode(service)));
12451                    out.print(' ');
12452                    service.printComponentShortName(out);
12453            if (count > 1) {
12454                out.print(" ("); out.print(count); out.print(" filters)");
12455            }
12456            out.println();
12457        }
12458
12459//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12460//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12461//            final List<ResolveInfo> retList = Lists.newArrayList();
12462//            while (i.hasNext()) {
12463//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12464//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12465//                    retList.add(resolveInfo);
12466//                }
12467//            }
12468//            return retList;
12469//        }
12470
12471        // Keys are String (activity class name), values are Activity.
12472        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12473                = new ArrayMap<ComponentName, PackageParser.Service>();
12474        private int mFlags;
12475    }
12476
12477    private final class ProviderIntentResolver
12478            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12479        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12480                boolean defaultOnly, int userId) {
12481            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12482            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12483        }
12484
12485        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12486                int userId) {
12487            if (!sUserManager.exists(userId))
12488                return null;
12489            mFlags = flags;
12490            return super.queryIntent(intent, resolvedType,
12491                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12492                    userId);
12493        }
12494
12495        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12496                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12497            if (!sUserManager.exists(userId))
12498                return null;
12499            if (packageProviders == null) {
12500                return null;
12501            }
12502            mFlags = flags;
12503            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12504            final int N = packageProviders.size();
12505            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12506                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12507
12508            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12509            for (int i = 0; i < N; ++i) {
12510                intentFilters = packageProviders.get(i).intents;
12511                if (intentFilters != null && intentFilters.size() > 0) {
12512                    PackageParser.ProviderIntentInfo[] array =
12513                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12514                    intentFilters.toArray(array);
12515                    listCut.add(array);
12516                }
12517            }
12518            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12519        }
12520
12521        public final void addProvider(PackageParser.Provider p) {
12522            if (mProviders.containsKey(p.getComponentName())) {
12523                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12524                return;
12525            }
12526
12527            mProviders.put(p.getComponentName(), p);
12528            if (DEBUG_SHOW_INFO) {
12529                Log.v(TAG, "  "
12530                        + (p.info.nonLocalizedLabel != null
12531                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12532                Log.v(TAG, "    Class=" + p.info.name);
12533            }
12534            final int NI = p.intents.size();
12535            int j;
12536            for (j = 0; j < NI; j++) {
12537                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12538                if (DEBUG_SHOW_INFO) {
12539                    Log.v(TAG, "    IntentFilter:");
12540                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12541                }
12542                if (!intent.debugCheck()) {
12543                    Log.w(TAG, "==> For Provider " + p.info.name);
12544                }
12545                addFilter(intent);
12546            }
12547        }
12548
12549        public final void removeProvider(PackageParser.Provider p) {
12550            mProviders.remove(p.getComponentName());
12551            if (DEBUG_SHOW_INFO) {
12552                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12553                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12554                Log.v(TAG, "    Class=" + p.info.name);
12555            }
12556            final int NI = p.intents.size();
12557            int j;
12558            for (j = 0; j < NI; j++) {
12559                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12560                if (DEBUG_SHOW_INFO) {
12561                    Log.v(TAG, "    IntentFilter:");
12562                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12563                }
12564                removeFilter(intent);
12565            }
12566        }
12567
12568        @Override
12569        protected boolean allowFilterResult(
12570                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12571            ProviderInfo filterPi = filter.provider.info;
12572            for (int i = dest.size() - 1; i >= 0; i--) {
12573                ProviderInfo destPi = dest.get(i).providerInfo;
12574                if (destPi.name == filterPi.name
12575                        && destPi.packageName == filterPi.packageName) {
12576                    return false;
12577                }
12578            }
12579            return true;
12580        }
12581
12582        @Override
12583        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12584            return new PackageParser.ProviderIntentInfo[size];
12585        }
12586
12587        @Override
12588        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12589            if (!sUserManager.exists(userId))
12590                return true;
12591            PackageParser.Package p = filter.provider.owner;
12592            if (p != null) {
12593                PackageSetting ps = (PackageSetting) p.mExtras;
12594                if (ps != null) {
12595                    // System apps are never considered stopped for purposes of
12596                    // filtering, because there may be no way for the user to
12597                    // actually re-launch them.
12598                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12599                            && ps.getStopped(userId);
12600                }
12601            }
12602            return false;
12603        }
12604
12605        @Override
12606        protected boolean isPackageForFilter(String packageName,
12607                PackageParser.ProviderIntentInfo info) {
12608            return packageName.equals(info.provider.owner.packageName);
12609        }
12610
12611        @Override
12612        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12613                int match, int userId) {
12614            if (!sUserManager.exists(userId))
12615                return null;
12616            final PackageParser.ProviderIntentInfo info = filter;
12617            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12618                return null;
12619            }
12620            final PackageParser.Provider provider = info.provider;
12621            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12622            if (ps == null) {
12623                return null;
12624            }
12625            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12626                    ps.readUserState(userId), userId);
12627            if (pi == null) {
12628                return null;
12629            }
12630            final ResolveInfo res = new ResolveInfo();
12631            res.providerInfo = pi;
12632            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12633                res.filter = filter;
12634            }
12635            res.priority = info.getPriority();
12636            res.preferredOrder = provider.owner.mPreferredOrder;
12637            res.match = match;
12638            res.isDefault = info.hasDefault;
12639            res.labelRes = info.labelRes;
12640            res.nonLocalizedLabel = info.nonLocalizedLabel;
12641            res.icon = info.icon;
12642            res.system = res.providerInfo.applicationInfo.isSystemApp();
12643            return res;
12644        }
12645
12646        @Override
12647        protected void sortResults(List<ResolveInfo> results) {
12648            Collections.sort(results, mResolvePrioritySorter);
12649        }
12650
12651        @Override
12652        protected void dumpFilter(PrintWriter out, String prefix,
12653                PackageParser.ProviderIntentInfo filter) {
12654            out.print(prefix);
12655            out.print(
12656                    Integer.toHexString(System.identityHashCode(filter.provider)));
12657            out.print(' ');
12658            filter.provider.printComponentShortName(out);
12659            out.print(" filter ");
12660            out.println(Integer.toHexString(System.identityHashCode(filter)));
12661        }
12662
12663        @Override
12664        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12665            return filter.provider;
12666        }
12667
12668        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12669            PackageParser.Provider provider = (PackageParser.Provider)label;
12670            out.print(prefix); out.print(
12671                    Integer.toHexString(System.identityHashCode(provider)));
12672                    out.print(' ');
12673                    provider.printComponentShortName(out);
12674            if (count > 1) {
12675                out.print(" ("); out.print(count); out.print(" filters)");
12676            }
12677            out.println();
12678        }
12679
12680        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12681                = new ArrayMap<ComponentName, PackageParser.Provider>();
12682        private int mFlags;
12683    }
12684
12685    static final class EphemeralIntentResolver
12686            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12687        /**
12688         * The result that has the highest defined order. Ordering applies on a
12689         * per-package basis. Mapping is from package name to Pair of order and
12690         * EphemeralResolveInfo.
12691         * <p>
12692         * NOTE: This is implemented as a field variable for convenience and efficiency.
12693         * By having a field variable, we're able to track filter ordering as soon as
12694         * a non-zero order is defined. Otherwise, multiple loops across the result set
12695         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12696         * this needs to be contained entirely within {@link #filterResults}.
12697         */
12698        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12699
12700        @Override
12701        protected AuxiliaryResolveInfo[] newArray(int size) {
12702            return new AuxiliaryResolveInfo[size];
12703        }
12704
12705        @Override
12706        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12707            return true;
12708        }
12709
12710        @Override
12711        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12712                int userId) {
12713            if (!sUserManager.exists(userId)) {
12714                return null;
12715            }
12716            final String packageName = responseObj.resolveInfo.getPackageName();
12717            final Integer order = responseObj.getOrder();
12718            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12719                    mOrderResult.get(packageName);
12720            // ordering is enabled and this item's order isn't high enough
12721            if (lastOrderResult != null && lastOrderResult.first >= order) {
12722                return null;
12723            }
12724            final InstantAppResolveInfo res = responseObj.resolveInfo;
12725            if (order > 0) {
12726                // non-zero order, enable ordering
12727                mOrderResult.put(packageName, new Pair<>(order, res));
12728            }
12729            return responseObj;
12730        }
12731
12732        @Override
12733        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12734            // only do work if ordering is enabled [most of the time it won't be]
12735            if (mOrderResult.size() == 0) {
12736                return;
12737            }
12738            int resultSize = results.size();
12739            for (int i = 0; i < resultSize; i++) {
12740                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12741                final String packageName = info.getPackageName();
12742                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12743                if (savedInfo == null) {
12744                    // package doesn't having ordering
12745                    continue;
12746                }
12747                if (savedInfo.second == info) {
12748                    // circled back to the highest ordered item; remove from order list
12749                    mOrderResult.remove(savedInfo);
12750                    if (mOrderResult.size() == 0) {
12751                        // no more ordered items
12752                        break;
12753                    }
12754                    continue;
12755                }
12756                // item has a worse order, remove it from the result list
12757                results.remove(i);
12758                resultSize--;
12759                i--;
12760            }
12761        }
12762    }
12763
12764    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12765            new Comparator<ResolveInfo>() {
12766        public int compare(ResolveInfo r1, ResolveInfo r2) {
12767            int v1 = r1.priority;
12768            int v2 = r2.priority;
12769            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12770            if (v1 != v2) {
12771                return (v1 > v2) ? -1 : 1;
12772            }
12773            v1 = r1.preferredOrder;
12774            v2 = r2.preferredOrder;
12775            if (v1 != v2) {
12776                return (v1 > v2) ? -1 : 1;
12777            }
12778            if (r1.isDefault != r2.isDefault) {
12779                return r1.isDefault ? -1 : 1;
12780            }
12781            v1 = r1.match;
12782            v2 = r2.match;
12783            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12784            if (v1 != v2) {
12785                return (v1 > v2) ? -1 : 1;
12786            }
12787            if (r1.system != r2.system) {
12788                return r1.system ? -1 : 1;
12789            }
12790            if (r1.activityInfo != null) {
12791                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12792            }
12793            if (r1.serviceInfo != null) {
12794                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12795            }
12796            if (r1.providerInfo != null) {
12797                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12798            }
12799            return 0;
12800        }
12801    };
12802
12803    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12804            new Comparator<ProviderInfo>() {
12805        public int compare(ProviderInfo p1, ProviderInfo p2) {
12806            final int v1 = p1.initOrder;
12807            final int v2 = p2.initOrder;
12808            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12809        }
12810    };
12811
12812    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12813            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12814            final int[] userIds) {
12815        mHandler.post(new Runnable() {
12816            @Override
12817            public void run() {
12818                try {
12819                    final IActivityManager am = ActivityManager.getService();
12820                    if (am == null) return;
12821                    final int[] resolvedUserIds;
12822                    if (userIds == null) {
12823                        resolvedUserIds = am.getRunningUserIds();
12824                    } else {
12825                        resolvedUserIds = userIds;
12826                    }
12827                    for (int id : resolvedUserIds) {
12828                        final Intent intent = new Intent(action,
12829                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12830                        if (extras != null) {
12831                            intent.putExtras(extras);
12832                        }
12833                        if (targetPkg != null) {
12834                            intent.setPackage(targetPkg);
12835                        }
12836                        // Modify the UID when posting to other users
12837                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12838                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12839                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12840                            intent.putExtra(Intent.EXTRA_UID, uid);
12841                        }
12842                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12843                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12844                        if (DEBUG_BROADCASTS) {
12845                            RuntimeException here = new RuntimeException("here");
12846                            here.fillInStackTrace();
12847                            Slog.d(TAG, "Sending to user " + id + ": "
12848                                    + intent.toShortString(false, true, false, false)
12849                                    + " " + intent.getExtras(), here);
12850                        }
12851                        am.broadcastIntent(null, intent, null, finishedReceiver,
12852                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12853                                null, finishedReceiver != null, false, id);
12854                    }
12855                } catch (RemoteException ex) {
12856                }
12857            }
12858        });
12859    }
12860
12861    /**
12862     * Check if the external storage media is available. This is true if there
12863     * is a mounted external storage medium or if the external storage is
12864     * emulated.
12865     */
12866    private boolean isExternalMediaAvailable() {
12867        return mMediaMounted || Environment.isExternalStorageEmulated();
12868    }
12869
12870    @Override
12871    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12872        // writer
12873        synchronized (mPackages) {
12874            if (!isExternalMediaAvailable()) {
12875                // If the external storage is no longer mounted at this point,
12876                // the caller may not have been able to delete all of this
12877                // packages files and can not delete any more.  Bail.
12878                return null;
12879            }
12880            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12881            if (lastPackage != null) {
12882                pkgs.remove(lastPackage);
12883            }
12884            if (pkgs.size() > 0) {
12885                return pkgs.get(0);
12886            }
12887        }
12888        return null;
12889    }
12890
12891    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12892        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12893                userId, andCode ? 1 : 0, packageName);
12894        if (mSystemReady) {
12895            msg.sendToTarget();
12896        } else {
12897            if (mPostSystemReadyMessages == null) {
12898                mPostSystemReadyMessages = new ArrayList<>();
12899            }
12900            mPostSystemReadyMessages.add(msg);
12901        }
12902    }
12903
12904    void startCleaningPackages() {
12905        // reader
12906        if (!isExternalMediaAvailable()) {
12907            return;
12908        }
12909        synchronized (mPackages) {
12910            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12911                return;
12912            }
12913        }
12914        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12915        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12916        IActivityManager am = ActivityManager.getService();
12917        if (am != null) {
12918            try {
12919                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12920                        UserHandle.USER_SYSTEM);
12921            } catch (RemoteException e) {
12922            }
12923        }
12924    }
12925
12926    @Override
12927    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12928            int installFlags, String installerPackageName, int userId) {
12929        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12930
12931        final int callingUid = Binder.getCallingUid();
12932        enforceCrossUserPermission(callingUid, userId,
12933                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12934
12935        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12936            try {
12937                if (observer != null) {
12938                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12939                }
12940            } catch (RemoteException re) {
12941            }
12942            return;
12943        }
12944
12945        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12946            installFlags |= PackageManager.INSTALL_FROM_ADB;
12947
12948        } else {
12949            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12950            // about installerPackageName.
12951
12952            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12953            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12954        }
12955
12956        UserHandle user;
12957        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12958            user = UserHandle.ALL;
12959        } else {
12960            user = new UserHandle(userId);
12961        }
12962
12963        // Only system components can circumvent runtime permissions when installing.
12964        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12965                && mContext.checkCallingOrSelfPermission(Manifest.permission
12966                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12967            throw new SecurityException("You need the "
12968                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12969                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12970        }
12971
12972        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12973                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12974            throw new IllegalArgumentException(
12975                    "New installs into ASEC containers no longer supported");
12976        }
12977
12978        final File originFile = new File(originPath);
12979        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12980
12981        final Message msg = mHandler.obtainMessage(INIT_COPY);
12982        final VerificationInfo verificationInfo = new VerificationInfo(
12983                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12984        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12985                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12986                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12987                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12988        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12989        msg.obj = params;
12990
12991        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12992                System.identityHashCode(msg.obj));
12993        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12994                System.identityHashCode(msg.obj));
12995
12996        mHandler.sendMessage(msg);
12997    }
12998
12999
13000    /**
13001     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13002     * it is acting on behalf on an enterprise or the user).
13003     *
13004     * Note that the ordering of the conditionals in this method is important. The checks we perform
13005     * are as follows, in this order:
13006     *
13007     * 1) If the install is being performed by a system app, we can trust the app to have set the
13008     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13009     *    what it is.
13010     * 2) If the install is being performed by a device or profile owner app, the install reason
13011     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13012     *    set the install reason correctly. If the app targets an older SDK version where install
13013     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13014     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13015     * 3) In all other cases, the install is being performed by a regular app that is neither part
13016     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13017     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13018     *    set to enterprise policy and if so, change it to unknown instead.
13019     */
13020    private int fixUpInstallReason(String installerPackageName, int installerUid,
13021            int installReason) {
13022        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13023                == PERMISSION_GRANTED) {
13024            // If the install is being performed by a system app, we trust that app to have set the
13025            // install reason correctly.
13026            return installReason;
13027        }
13028
13029        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13030            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13031        if (dpm != null) {
13032            ComponentName owner = null;
13033            try {
13034                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13035                if (owner == null) {
13036                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13037                }
13038            } catch (RemoteException e) {
13039            }
13040            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13041                // If the install is being performed by a device or profile owner, the install
13042                // reason should be enterprise policy.
13043                return PackageManager.INSTALL_REASON_POLICY;
13044            }
13045        }
13046
13047        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13048            // If the install is being performed by a regular app (i.e. neither system app nor
13049            // device or profile owner), we have no reason to believe that the app is acting on
13050            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13051            // change it to unknown instead.
13052            return PackageManager.INSTALL_REASON_UNKNOWN;
13053        }
13054
13055        // If the install is being performed by a regular app and the install reason was set to any
13056        // value but enterprise policy, leave the install reason unchanged.
13057        return installReason;
13058    }
13059
13060    void installStage(String packageName, File stagedDir, String stagedCid,
13061            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13062            String installerPackageName, int installerUid, UserHandle user,
13063            Certificate[][] certificates) {
13064        if (DEBUG_EPHEMERAL) {
13065            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13066                Slog.d(TAG, "Ephemeral install of " + packageName);
13067            }
13068        }
13069        final VerificationInfo verificationInfo = new VerificationInfo(
13070                sessionParams.originatingUri, sessionParams.referrerUri,
13071                sessionParams.originatingUid, installerUid);
13072
13073        final OriginInfo origin;
13074        if (stagedDir != null) {
13075            origin = OriginInfo.fromStagedFile(stagedDir);
13076        } else {
13077            origin = OriginInfo.fromStagedContainer(stagedCid);
13078        }
13079
13080        final Message msg = mHandler.obtainMessage(INIT_COPY);
13081        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13082                sessionParams.installReason);
13083        final InstallParams params = new InstallParams(origin, null, observer,
13084                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13085                verificationInfo, user, sessionParams.abiOverride,
13086                sessionParams.grantedRuntimePermissions, certificates, installReason);
13087        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13088        msg.obj = params;
13089
13090        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13091                System.identityHashCode(msg.obj));
13092        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13093                System.identityHashCode(msg.obj));
13094
13095        mHandler.sendMessage(msg);
13096    }
13097
13098    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13099            int userId) {
13100        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13101        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13102    }
13103
13104    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13105            int appId, int... userIds) {
13106        if (ArrayUtils.isEmpty(userIds)) {
13107            return;
13108        }
13109        Bundle extras = new Bundle(1);
13110        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13111        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13112
13113        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13114                packageName, extras, 0, null, null, userIds);
13115        if (isSystem) {
13116            mHandler.post(() -> {
13117                        for (int userId : userIds) {
13118                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13119                        }
13120                    }
13121            );
13122        }
13123    }
13124
13125    /**
13126     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13127     * automatically without needing an explicit launch.
13128     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13129     */
13130    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13131        // If user is not running, the app didn't miss any broadcast
13132        if (!mUserManagerInternal.isUserRunning(userId)) {
13133            return;
13134        }
13135        final IActivityManager am = ActivityManager.getService();
13136        try {
13137            // Deliver LOCKED_BOOT_COMPLETED first
13138            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13139                    .setPackage(packageName);
13140            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13141            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13142                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13143
13144            // Deliver BOOT_COMPLETED only if user is unlocked
13145            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13146                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13147                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13148                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13149            }
13150        } catch (RemoteException e) {
13151            throw e.rethrowFromSystemServer();
13152        }
13153    }
13154
13155    @Override
13156    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13157            int userId) {
13158        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13159        PackageSetting pkgSetting;
13160        final int uid = Binder.getCallingUid();
13161        enforceCrossUserPermission(uid, userId,
13162                true /* requireFullPermission */, true /* checkShell */,
13163                "setApplicationHiddenSetting for user " + userId);
13164
13165        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13166            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13167            return false;
13168        }
13169
13170        long callingId = Binder.clearCallingIdentity();
13171        try {
13172            boolean sendAdded = false;
13173            boolean sendRemoved = false;
13174            // writer
13175            synchronized (mPackages) {
13176                pkgSetting = mSettings.mPackages.get(packageName);
13177                if (pkgSetting == null) {
13178                    return false;
13179                }
13180                // Do not allow "android" is being disabled
13181                if ("android".equals(packageName)) {
13182                    Slog.w(TAG, "Cannot hide package: android");
13183                    return false;
13184                }
13185                // Cannot hide static shared libs as they are considered
13186                // a part of the using app (emulating static linking). Also
13187                // static libs are installed always on internal storage.
13188                PackageParser.Package pkg = mPackages.get(packageName);
13189                if (pkg != null && pkg.staticSharedLibName != null) {
13190                    Slog.w(TAG, "Cannot hide package: " + packageName
13191                            + " providing static shared library: "
13192                            + pkg.staticSharedLibName);
13193                    return false;
13194                }
13195                // Only allow protected packages to hide themselves.
13196                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13197                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13198                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13199                    return false;
13200                }
13201
13202                if (pkgSetting.getHidden(userId) != hidden) {
13203                    pkgSetting.setHidden(hidden, userId);
13204                    mSettings.writePackageRestrictionsLPr(userId);
13205                    if (hidden) {
13206                        sendRemoved = true;
13207                    } else {
13208                        sendAdded = true;
13209                    }
13210                }
13211            }
13212            if (sendAdded) {
13213                sendPackageAddedForUser(packageName, pkgSetting, userId);
13214                return true;
13215            }
13216            if (sendRemoved) {
13217                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13218                        "hiding pkg");
13219                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13220                return true;
13221            }
13222        } finally {
13223            Binder.restoreCallingIdentity(callingId);
13224        }
13225        return false;
13226    }
13227
13228    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13229            int userId) {
13230        final PackageRemovedInfo info = new PackageRemovedInfo();
13231        info.removedPackage = packageName;
13232        info.removedUsers = new int[] {userId};
13233        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13234        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13235    }
13236
13237    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13238        if (pkgList.length > 0) {
13239            Bundle extras = new Bundle(1);
13240            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13241
13242            sendPackageBroadcast(
13243                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13244                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13245                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13246                    new int[] {userId});
13247        }
13248    }
13249
13250    /**
13251     * Returns true if application is not found or there was an error. Otherwise it returns
13252     * the hidden state of the package for the given user.
13253     */
13254    @Override
13255    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13256        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13257        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13258                true /* requireFullPermission */, false /* checkShell */,
13259                "getApplicationHidden for user " + userId);
13260        PackageSetting pkgSetting;
13261        long callingId = Binder.clearCallingIdentity();
13262        try {
13263            // writer
13264            synchronized (mPackages) {
13265                pkgSetting = mSettings.mPackages.get(packageName);
13266                if (pkgSetting == null) {
13267                    return true;
13268                }
13269                return pkgSetting.getHidden(userId);
13270            }
13271        } finally {
13272            Binder.restoreCallingIdentity(callingId);
13273        }
13274    }
13275
13276    /**
13277     * @hide
13278     */
13279    @Override
13280    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13281            int installReason) {
13282        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13283                null);
13284        PackageSetting pkgSetting;
13285        final int uid = Binder.getCallingUid();
13286        enforceCrossUserPermission(uid, userId,
13287                true /* requireFullPermission */, true /* checkShell */,
13288                "installExistingPackage for user " + userId);
13289        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13290            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13291        }
13292
13293        long callingId = Binder.clearCallingIdentity();
13294        try {
13295            boolean installed = false;
13296            final boolean instantApp =
13297                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13298            final boolean fullApp =
13299                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13300
13301            // writer
13302            synchronized (mPackages) {
13303                pkgSetting = mSettings.mPackages.get(packageName);
13304                if (pkgSetting == null) {
13305                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13306                }
13307                if (!pkgSetting.getInstalled(userId)) {
13308                    pkgSetting.setInstalled(true, userId);
13309                    pkgSetting.setHidden(false, userId);
13310                    pkgSetting.setInstallReason(installReason, userId);
13311                    mSettings.writePackageRestrictionsLPr(userId);
13312                    mSettings.writeKernelMappingLPr(pkgSetting);
13313                    installed = true;
13314                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13315                    // upgrade app from instant to full; we don't allow app downgrade
13316                    installed = true;
13317                }
13318                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13319            }
13320
13321            if (installed) {
13322                if (pkgSetting.pkg != null) {
13323                    synchronized (mInstallLock) {
13324                        // We don't need to freeze for a brand new install
13325                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13326                    }
13327                }
13328                sendPackageAddedForUser(packageName, pkgSetting, userId);
13329                synchronized (mPackages) {
13330                    updateSequenceNumberLP(packageName, new int[]{ userId });
13331                }
13332            }
13333        } finally {
13334            Binder.restoreCallingIdentity(callingId);
13335        }
13336
13337        return PackageManager.INSTALL_SUCCEEDED;
13338    }
13339
13340    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13341            boolean instantApp, boolean fullApp) {
13342        // no state specified; do nothing
13343        if (!instantApp && !fullApp) {
13344            return;
13345        }
13346        if (userId != UserHandle.USER_ALL) {
13347            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13348                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13349            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13350                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13351            }
13352        } else {
13353            for (int currentUserId : sUserManager.getUserIds()) {
13354                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13355                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13356                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13357                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13358                }
13359            }
13360        }
13361    }
13362
13363    boolean isUserRestricted(int userId, String restrictionKey) {
13364        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13365        if (restrictions.getBoolean(restrictionKey, false)) {
13366            Log.w(TAG, "User is restricted: " + restrictionKey);
13367            return true;
13368        }
13369        return false;
13370    }
13371
13372    @Override
13373    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13374            int userId) {
13375        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13376        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13377                true /* requireFullPermission */, true /* checkShell */,
13378                "setPackagesSuspended for user " + userId);
13379
13380        if (ArrayUtils.isEmpty(packageNames)) {
13381            return packageNames;
13382        }
13383
13384        // List of package names for whom the suspended state has changed.
13385        List<String> changedPackages = new ArrayList<>(packageNames.length);
13386        // List of package names for whom the suspended state is not set as requested in this
13387        // method.
13388        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13389        long callingId = Binder.clearCallingIdentity();
13390        try {
13391            for (int i = 0; i < packageNames.length; i++) {
13392                String packageName = packageNames[i];
13393                boolean changed = false;
13394                final int appId;
13395                synchronized (mPackages) {
13396                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13397                    if (pkgSetting == null) {
13398                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13399                                + "\". Skipping suspending/un-suspending.");
13400                        unactionedPackages.add(packageName);
13401                        continue;
13402                    }
13403                    appId = pkgSetting.appId;
13404                    if (pkgSetting.getSuspended(userId) != suspended) {
13405                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13406                            unactionedPackages.add(packageName);
13407                            continue;
13408                        }
13409                        pkgSetting.setSuspended(suspended, userId);
13410                        mSettings.writePackageRestrictionsLPr(userId);
13411                        changed = true;
13412                        changedPackages.add(packageName);
13413                    }
13414                }
13415
13416                if (changed && suspended) {
13417                    killApplication(packageName, UserHandle.getUid(userId, appId),
13418                            "suspending package");
13419                }
13420            }
13421        } finally {
13422            Binder.restoreCallingIdentity(callingId);
13423        }
13424
13425        if (!changedPackages.isEmpty()) {
13426            sendPackagesSuspendedForUser(changedPackages.toArray(
13427                    new String[changedPackages.size()]), userId, suspended);
13428        }
13429
13430        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13431    }
13432
13433    @Override
13434    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13435        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13436                true /* requireFullPermission */, false /* checkShell */,
13437                "isPackageSuspendedForUser for user " + userId);
13438        synchronized (mPackages) {
13439            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13440            if (pkgSetting == null) {
13441                throw new IllegalArgumentException("Unknown target package: " + packageName);
13442            }
13443            return pkgSetting.getSuspended(userId);
13444        }
13445    }
13446
13447    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13448        if (isPackageDeviceAdmin(packageName, userId)) {
13449            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13450                    + "\": has an active device admin");
13451            return false;
13452        }
13453
13454        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13455        if (packageName.equals(activeLauncherPackageName)) {
13456            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13457                    + "\": contains the active launcher");
13458            return false;
13459        }
13460
13461        if (packageName.equals(mRequiredInstallerPackage)) {
13462            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13463                    + "\": required for package installation");
13464            return false;
13465        }
13466
13467        if (packageName.equals(mRequiredUninstallerPackage)) {
13468            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13469                    + "\": required for package uninstallation");
13470            return false;
13471        }
13472
13473        if (packageName.equals(mRequiredVerifierPackage)) {
13474            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13475                    + "\": required for package verification");
13476            return false;
13477        }
13478
13479        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13480            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13481                    + "\": is the default dialer");
13482            return false;
13483        }
13484
13485        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13486            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13487                    + "\": protected package");
13488            return false;
13489        }
13490
13491        // Cannot suspend static shared libs as they are considered
13492        // a part of the using app (emulating static linking). Also
13493        // static libs are installed always on internal storage.
13494        PackageParser.Package pkg = mPackages.get(packageName);
13495        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13496            Slog.w(TAG, "Cannot suspend package: " + packageName
13497                    + " providing static shared library: "
13498                    + pkg.staticSharedLibName);
13499            return false;
13500        }
13501
13502        return true;
13503    }
13504
13505    private String getActiveLauncherPackageName(int userId) {
13506        Intent intent = new Intent(Intent.ACTION_MAIN);
13507        intent.addCategory(Intent.CATEGORY_HOME);
13508        ResolveInfo resolveInfo = resolveIntent(
13509                intent,
13510                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13511                PackageManager.MATCH_DEFAULT_ONLY,
13512                userId);
13513
13514        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13515    }
13516
13517    private String getDefaultDialerPackageName(int userId) {
13518        synchronized (mPackages) {
13519            return mSettings.getDefaultDialerPackageNameLPw(userId);
13520        }
13521    }
13522
13523    @Override
13524    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13525        mContext.enforceCallingOrSelfPermission(
13526                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13527                "Only package verification agents can verify applications");
13528
13529        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13530        final PackageVerificationResponse response = new PackageVerificationResponse(
13531                verificationCode, Binder.getCallingUid());
13532        msg.arg1 = id;
13533        msg.obj = response;
13534        mHandler.sendMessage(msg);
13535    }
13536
13537    @Override
13538    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13539            long millisecondsToDelay) {
13540        mContext.enforceCallingOrSelfPermission(
13541                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13542                "Only package verification agents can extend verification timeouts");
13543
13544        final PackageVerificationState state = mPendingVerification.get(id);
13545        final PackageVerificationResponse response = new PackageVerificationResponse(
13546                verificationCodeAtTimeout, Binder.getCallingUid());
13547
13548        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13549            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13550        }
13551        if (millisecondsToDelay < 0) {
13552            millisecondsToDelay = 0;
13553        }
13554        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13555                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13556            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13557        }
13558
13559        if ((state != null) && !state.timeoutExtended()) {
13560            state.extendTimeout();
13561
13562            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13563            msg.arg1 = id;
13564            msg.obj = response;
13565            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13566        }
13567    }
13568
13569    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13570            int verificationCode, UserHandle user) {
13571        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13572        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13573        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13574        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13575        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13576
13577        mContext.sendBroadcastAsUser(intent, user,
13578                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13579    }
13580
13581    private ComponentName matchComponentForVerifier(String packageName,
13582            List<ResolveInfo> receivers) {
13583        ActivityInfo targetReceiver = null;
13584
13585        final int NR = receivers.size();
13586        for (int i = 0; i < NR; i++) {
13587            final ResolveInfo info = receivers.get(i);
13588            if (info.activityInfo == null) {
13589                continue;
13590            }
13591
13592            if (packageName.equals(info.activityInfo.packageName)) {
13593                targetReceiver = info.activityInfo;
13594                break;
13595            }
13596        }
13597
13598        if (targetReceiver == null) {
13599            return null;
13600        }
13601
13602        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13603    }
13604
13605    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13606            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13607        if (pkgInfo.verifiers.length == 0) {
13608            return null;
13609        }
13610
13611        final int N = pkgInfo.verifiers.length;
13612        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13613        for (int i = 0; i < N; i++) {
13614            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13615
13616            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13617                    receivers);
13618            if (comp == null) {
13619                continue;
13620            }
13621
13622            final int verifierUid = getUidForVerifier(verifierInfo);
13623            if (verifierUid == -1) {
13624                continue;
13625            }
13626
13627            if (DEBUG_VERIFY) {
13628                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13629                        + " with the correct signature");
13630            }
13631            sufficientVerifiers.add(comp);
13632            verificationState.addSufficientVerifier(verifierUid);
13633        }
13634
13635        return sufficientVerifiers;
13636    }
13637
13638    private int getUidForVerifier(VerifierInfo verifierInfo) {
13639        synchronized (mPackages) {
13640            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13641            if (pkg == null) {
13642                return -1;
13643            } else if (pkg.mSignatures.length != 1) {
13644                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13645                        + " has more than one signature; ignoring");
13646                return -1;
13647            }
13648
13649            /*
13650             * If the public key of the package's signature does not match
13651             * our expected public key, then this is a different package and
13652             * we should skip.
13653             */
13654
13655            final byte[] expectedPublicKey;
13656            try {
13657                final Signature verifierSig = pkg.mSignatures[0];
13658                final PublicKey publicKey = verifierSig.getPublicKey();
13659                expectedPublicKey = publicKey.getEncoded();
13660            } catch (CertificateException e) {
13661                return -1;
13662            }
13663
13664            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13665
13666            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13667                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13668                        + " does not have the expected public key; ignoring");
13669                return -1;
13670            }
13671
13672            return pkg.applicationInfo.uid;
13673        }
13674    }
13675
13676    @Override
13677    public void finishPackageInstall(int token, boolean didLaunch) {
13678        enforceSystemOrRoot("Only the system is allowed to finish installs");
13679
13680        if (DEBUG_INSTALL) {
13681            Slog.v(TAG, "BM finishing package install for " + token);
13682        }
13683        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13684
13685        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13686        mHandler.sendMessage(msg);
13687    }
13688
13689    /**
13690     * Get the verification agent timeout.
13691     *
13692     * @return verification timeout in milliseconds
13693     */
13694    private long getVerificationTimeout() {
13695        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13696                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13697                DEFAULT_VERIFICATION_TIMEOUT);
13698    }
13699
13700    /**
13701     * Get the default verification agent response code.
13702     *
13703     * @return default verification response code
13704     */
13705    private int getDefaultVerificationResponse() {
13706        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13707                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13708                DEFAULT_VERIFICATION_RESPONSE);
13709    }
13710
13711    /**
13712     * Check whether or not package verification has been enabled.
13713     *
13714     * @return true if verification should be performed
13715     */
13716    private boolean isVerificationEnabled(int userId, int installFlags) {
13717        if (!DEFAULT_VERIFY_ENABLE) {
13718            return false;
13719        }
13720
13721        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13722
13723        // Check if installing from ADB
13724        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13725            // Do not run verification in a test harness environment
13726            if (ActivityManager.isRunningInTestHarness()) {
13727                return false;
13728            }
13729            if (ensureVerifyAppsEnabled) {
13730                return true;
13731            }
13732            // Check if the developer does not want package verification for ADB installs
13733            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13734                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13735                return false;
13736            }
13737        }
13738
13739        if (ensureVerifyAppsEnabled) {
13740            return true;
13741        }
13742
13743        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13744                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13745    }
13746
13747    @Override
13748    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13749            throws RemoteException {
13750        mContext.enforceCallingOrSelfPermission(
13751                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13752                "Only intentfilter verification agents can verify applications");
13753
13754        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13755        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13756                Binder.getCallingUid(), verificationCode, failedDomains);
13757        msg.arg1 = id;
13758        msg.obj = response;
13759        mHandler.sendMessage(msg);
13760    }
13761
13762    @Override
13763    public int getIntentVerificationStatus(String packageName, int userId) {
13764        synchronized (mPackages) {
13765            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13766        }
13767    }
13768
13769    @Override
13770    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13771        mContext.enforceCallingOrSelfPermission(
13772                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13773
13774        boolean result = false;
13775        synchronized (mPackages) {
13776            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13777        }
13778        if (result) {
13779            scheduleWritePackageRestrictionsLocked(userId);
13780        }
13781        return result;
13782    }
13783
13784    @Override
13785    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13786            String packageName) {
13787        synchronized (mPackages) {
13788            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13789        }
13790    }
13791
13792    @Override
13793    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13794        if (TextUtils.isEmpty(packageName)) {
13795            return ParceledListSlice.emptyList();
13796        }
13797        synchronized (mPackages) {
13798            PackageParser.Package pkg = mPackages.get(packageName);
13799            if (pkg == null || pkg.activities == null) {
13800                return ParceledListSlice.emptyList();
13801            }
13802            final int count = pkg.activities.size();
13803            ArrayList<IntentFilter> result = new ArrayList<>();
13804            for (int n=0; n<count; n++) {
13805                PackageParser.Activity activity = pkg.activities.get(n);
13806                if (activity.intents != null && activity.intents.size() > 0) {
13807                    result.addAll(activity.intents);
13808                }
13809            }
13810            return new ParceledListSlice<>(result);
13811        }
13812    }
13813
13814    @Override
13815    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13816        mContext.enforceCallingOrSelfPermission(
13817                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13818
13819        synchronized (mPackages) {
13820            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13821            if (packageName != null) {
13822                result |= updateIntentVerificationStatus(packageName,
13823                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13824                        userId);
13825                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13826                        packageName, userId);
13827            }
13828            return result;
13829        }
13830    }
13831
13832    @Override
13833    public String getDefaultBrowserPackageName(int userId) {
13834        synchronized (mPackages) {
13835            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13836        }
13837    }
13838
13839    /**
13840     * Get the "allow unknown sources" setting.
13841     *
13842     * @return the current "allow unknown sources" setting
13843     */
13844    private int getUnknownSourcesSettings() {
13845        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13846                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13847                -1);
13848    }
13849
13850    @Override
13851    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13852        final int uid = Binder.getCallingUid();
13853        // writer
13854        synchronized (mPackages) {
13855            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13856            if (targetPackageSetting == null) {
13857                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13858            }
13859
13860            PackageSetting installerPackageSetting;
13861            if (installerPackageName != null) {
13862                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13863                if (installerPackageSetting == null) {
13864                    throw new IllegalArgumentException("Unknown installer package: "
13865                            + installerPackageName);
13866                }
13867            } else {
13868                installerPackageSetting = null;
13869            }
13870
13871            Signature[] callerSignature;
13872            Object obj = mSettings.getUserIdLPr(uid);
13873            if (obj != null) {
13874                if (obj instanceof SharedUserSetting) {
13875                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13876                } else if (obj instanceof PackageSetting) {
13877                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13878                } else {
13879                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13880                }
13881            } else {
13882                throw new SecurityException("Unknown calling UID: " + uid);
13883            }
13884
13885            // Verify: can't set installerPackageName to a package that is
13886            // not signed with the same cert as the caller.
13887            if (installerPackageSetting != null) {
13888                if (compareSignatures(callerSignature,
13889                        installerPackageSetting.signatures.mSignatures)
13890                        != PackageManager.SIGNATURE_MATCH) {
13891                    throw new SecurityException(
13892                            "Caller does not have same cert as new installer package "
13893                            + installerPackageName);
13894                }
13895            }
13896
13897            // Verify: if target already has an installer package, it must
13898            // be signed with the same cert as the caller.
13899            if (targetPackageSetting.installerPackageName != null) {
13900                PackageSetting setting = mSettings.mPackages.get(
13901                        targetPackageSetting.installerPackageName);
13902                // If the currently set package isn't valid, then it's always
13903                // okay to change it.
13904                if (setting != null) {
13905                    if (compareSignatures(callerSignature,
13906                            setting.signatures.mSignatures)
13907                            != PackageManager.SIGNATURE_MATCH) {
13908                        throw new SecurityException(
13909                                "Caller does not have same cert as old installer package "
13910                                + targetPackageSetting.installerPackageName);
13911                    }
13912                }
13913            }
13914
13915            // Okay!
13916            targetPackageSetting.installerPackageName = installerPackageName;
13917            if (installerPackageName != null) {
13918                mSettings.mInstallerPackages.add(installerPackageName);
13919            }
13920            scheduleWriteSettingsLocked();
13921        }
13922    }
13923
13924    @Override
13925    public void setApplicationCategoryHint(String packageName, int categoryHint,
13926            String callerPackageName) {
13927        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13928                callerPackageName);
13929        synchronized (mPackages) {
13930            PackageSetting ps = mSettings.mPackages.get(packageName);
13931            if (ps == null) {
13932                throw new IllegalArgumentException("Unknown target package " + packageName);
13933            }
13934
13935            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13936                throw new IllegalArgumentException("Calling package " + callerPackageName
13937                        + " is not installer for " + packageName);
13938            }
13939
13940            if (ps.categoryHint != categoryHint) {
13941                ps.categoryHint = categoryHint;
13942                scheduleWriteSettingsLocked();
13943            }
13944        }
13945    }
13946
13947    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13948        // Queue up an async operation since the package installation may take a little while.
13949        mHandler.post(new Runnable() {
13950            public void run() {
13951                mHandler.removeCallbacks(this);
13952                 // Result object to be returned
13953                PackageInstalledInfo res = new PackageInstalledInfo();
13954                res.setReturnCode(currentStatus);
13955                res.uid = -1;
13956                res.pkg = null;
13957                res.removedInfo = null;
13958                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13959                    args.doPreInstall(res.returnCode);
13960                    synchronized (mInstallLock) {
13961                        installPackageTracedLI(args, res);
13962                    }
13963                    args.doPostInstall(res.returnCode, res.uid);
13964                }
13965
13966                // A restore should be performed at this point if (a) the install
13967                // succeeded, (b) the operation is not an update, and (c) the new
13968                // package has not opted out of backup participation.
13969                final boolean update = res.removedInfo != null
13970                        && res.removedInfo.removedPackage != null;
13971                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13972                boolean doRestore = !update
13973                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13974
13975                // Set up the post-install work request bookkeeping.  This will be used
13976                // and cleaned up by the post-install event handling regardless of whether
13977                // there's a restore pass performed.  Token values are >= 1.
13978                int token;
13979                if (mNextInstallToken < 0) mNextInstallToken = 1;
13980                token = mNextInstallToken++;
13981
13982                PostInstallData data = new PostInstallData(args, res);
13983                mRunningInstalls.put(token, data);
13984                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13985
13986                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13987                    // Pass responsibility to the Backup Manager.  It will perform a
13988                    // restore if appropriate, then pass responsibility back to the
13989                    // Package Manager to run the post-install observer callbacks
13990                    // and broadcasts.
13991                    IBackupManager bm = IBackupManager.Stub.asInterface(
13992                            ServiceManager.getService(Context.BACKUP_SERVICE));
13993                    if (bm != null) {
13994                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13995                                + " to BM for possible restore");
13996                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13997                        try {
13998                            // TODO: http://b/22388012
13999                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14000                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14001                            } else {
14002                                doRestore = false;
14003                            }
14004                        } catch (RemoteException e) {
14005                            // can't happen; the backup manager is local
14006                        } catch (Exception e) {
14007                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14008                            doRestore = false;
14009                        }
14010                    } else {
14011                        Slog.e(TAG, "Backup Manager not found!");
14012                        doRestore = false;
14013                    }
14014                }
14015
14016                if (!doRestore) {
14017                    // No restore possible, or the Backup Manager was mysteriously not
14018                    // available -- just fire the post-install work request directly.
14019                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14020
14021                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14022
14023                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14024                    mHandler.sendMessage(msg);
14025                }
14026            }
14027        });
14028    }
14029
14030    /**
14031     * Callback from PackageSettings whenever an app is first transitioned out of the
14032     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14033     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14034     * here whether the app is the target of an ongoing install, and only send the
14035     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14036     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14037     * handling.
14038     */
14039    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14040        // Serialize this with the rest of the install-process message chain.  In the
14041        // restore-at-install case, this Runnable will necessarily run before the
14042        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14043        // are coherent.  In the non-restore case, the app has already completed install
14044        // and been launched through some other means, so it is not in a problematic
14045        // state for observers to see the FIRST_LAUNCH signal.
14046        mHandler.post(new Runnable() {
14047            @Override
14048            public void run() {
14049                for (int i = 0; i < mRunningInstalls.size(); i++) {
14050                    final PostInstallData data = mRunningInstalls.valueAt(i);
14051                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14052                        continue;
14053                    }
14054                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14055                        // right package; but is it for the right user?
14056                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14057                            if (userId == data.res.newUsers[uIndex]) {
14058                                if (DEBUG_BACKUP) {
14059                                    Slog.i(TAG, "Package " + pkgName
14060                                            + " being restored so deferring FIRST_LAUNCH");
14061                                }
14062                                return;
14063                            }
14064                        }
14065                    }
14066                }
14067                // didn't find it, so not being restored
14068                if (DEBUG_BACKUP) {
14069                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14070                }
14071                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14072            }
14073        });
14074    }
14075
14076    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14077        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14078                installerPkg, null, userIds);
14079    }
14080
14081    private abstract class HandlerParams {
14082        private static final int MAX_RETRIES = 4;
14083
14084        /**
14085         * Number of times startCopy() has been attempted and had a non-fatal
14086         * error.
14087         */
14088        private int mRetries = 0;
14089
14090        /** User handle for the user requesting the information or installation. */
14091        private final UserHandle mUser;
14092        String traceMethod;
14093        int traceCookie;
14094
14095        HandlerParams(UserHandle user) {
14096            mUser = user;
14097        }
14098
14099        UserHandle getUser() {
14100            return mUser;
14101        }
14102
14103        HandlerParams setTraceMethod(String traceMethod) {
14104            this.traceMethod = traceMethod;
14105            return this;
14106        }
14107
14108        HandlerParams setTraceCookie(int traceCookie) {
14109            this.traceCookie = traceCookie;
14110            return this;
14111        }
14112
14113        final boolean startCopy() {
14114            boolean res;
14115            try {
14116                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14117
14118                if (++mRetries > MAX_RETRIES) {
14119                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14120                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14121                    handleServiceError();
14122                    return false;
14123                } else {
14124                    handleStartCopy();
14125                    res = true;
14126                }
14127            } catch (RemoteException e) {
14128                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14129                mHandler.sendEmptyMessage(MCS_RECONNECT);
14130                res = false;
14131            }
14132            handleReturnCode();
14133            return res;
14134        }
14135
14136        final void serviceError() {
14137            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14138            handleServiceError();
14139            handleReturnCode();
14140        }
14141
14142        abstract void handleStartCopy() throws RemoteException;
14143        abstract void handleServiceError();
14144        abstract void handleReturnCode();
14145    }
14146
14147    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14148        for (File path : paths) {
14149            try {
14150                mcs.clearDirectory(path.getAbsolutePath());
14151            } catch (RemoteException e) {
14152            }
14153        }
14154    }
14155
14156    static class OriginInfo {
14157        /**
14158         * Location where install is coming from, before it has been
14159         * copied/renamed into place. This could be a single monolithic APK
14160         * file, or a cluster directory. This location may be untrusted.
14161         */
14162        final File file;
14163        final String cid;
14164
14165        /**
14166         * Flag indicating that {@link #file} or {@link #cid} has already been
14167         * staged, meaning downstream users don't need to defensively copy the
14168         * contents.
14169         */
14170        final boolean staged;
14171
14172        /**
14173         * Flag indicating that {@link #file} or {@link #cid} is an already
14174         * installed app that is being moved.
14175         */
14176        final boolean existing;
14177
14178        final String resolvedPath;
14179        final File resolvedFile;
14180
14181        static OriginInfo fromNothing() {
14182            return new OriginInfo(null, null, false, false);
14183        }
14184
14185        static OriginInfo fromUntrustedFile(File file) {
14186            return new OriginInfo(file, null, false, false);
14187        }
14188
14189        static OriginInfo fromExistingFile(File file) {
14190            return new OriginInfo(file, null, false, true);
14191        }
14192
14193        static OriginInfo fromStagedFile(File file) {
14194            return new OriginInfo(file, null, true, false);
14195        }
14196
14197        static OriginInfo fromStagedContainer(String cid) {
14198            return new OriginInfo(null, cid, true, false);
14199        }
14200
14201        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14202            this.file = file;
14203            this.cid = cid;
14204            this.staged = staged;
14205            this.existing = existing;
14206
14207            if (cid != null) {
14208                resolvedPath = PackageHelper.getSdDir(cid);
14209                resolvedFile = new File(resolvedPath);
14210            } else if (file != null) {
14211                resolvedPath = file.getAbsolutePath();
14212                resolvedFile = file;
14213            } else {
14214                resolvedPath = null;
14215                resolvedFile = null;
14216            }
14217        }
14218    }
14219
14220    static class MoveInfo {
14221        final int moveId;
14222        final String fromUuid;
14223        final String toUuid;
14224        final String packageName;
14225        final String dataAppName;
14226        final int appId;
14227        final String seinfo;
14228        final int targetSdkVersion;
14229
14230        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14231                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14232            this.moveId = moveId;
14233            this.fromUuid = fromUuid;
14234            this.toUuid = toUuid;
14235            this.packageName = packageName;
14236            this.dataAppName = dataAppName;
14237            this.appId = appId;
14238            this.seinfo = seinfo;
14239            this.targetSdkVersion = targetSdkVersion;
14240        }
14241    }
14242
14243    static class VerificationInfo {
14244        /** A constant used to indicate that a uid value is not present. */
14245        public static final int NO_UID = -1;
14246
14247        /** URI referencing where the package was downloaded from. */
14248        final Uri originatingUri;
14249
14250        /** HTTP referrer URI associated with the originatingURI. */
14251        final Uri referrer;
14252
14253        /** UID of the application that the install request originated from. */
14254        final int originatingUid;
14255
14256        /** UID of application requesting the install */
14257        final int installerUid;
14258
14259        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14260            this.originatingUri = originatingUri;
14261            this.referrer = referrer;
14262            this.originatingUid = originatingUid;
14263            this.installerUid = installerUid;
14264        }
14265    }
14266
14267    class InstallParams extends HandlerParams {
14268        final OriginInfo origin;
14269        final MoveInfo move;
14270        final IPackageInstallObserver2 observer;
14271        int installFlags;
14272        final String installerPackageName;
14273        final String volumeUuid;
14274        private InstallArgs mArgs;
14275        private int mRet;
14276        final String packageAbiOverride;
14277        final String[] grantedRuntimePermissions;
14278        final VerificationInfo verificationInfo;
14279        final Certificate[][] certificates;
14280        final int installReason;
14281
14282        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14283                int installFlags, String installerPackageName, String volumeUuid,
14284                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14285                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14286            super(user);
14287            this.origin = origin;
14288            this.move = move;
14289            this.observer = observer;
14290            this.installFlags = installFlags;
14291            this.installerPackageName = installerPackageName;
14292            this.volumeUuid = volumeUuid;
14293            this.verificationInfo = verificationInfo;
14294            this.packageAbiOverride = packageAbiOverride;
14295            this.grantedRuntimePermissions = grantedPermissions;
14296            this.certificates = certificates;
14297            this.installReason = installReason;
14298        }
14299
14300        @Override
14301        public String toString() {
14302            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14303                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14304        }
14305
14306        private int installLocationPolicy(PackageInfoLite pkgLite) {
14307            String packageName = pkgLite.packageName;
14308            int installLocation = pkgLite.installLocation;
14309            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14310            // reader
14311            synchronized (mPackages) {
14312                // Currently installed package which the new package is attempting to replace or
14313                // null if no such package is installed.
14314                PackageParser.Package installedPkg = mPackages.get(packageName);
14315                // Package which currently owns the data which the new package will own if installed.
14316                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14317                // will be null whereas dataOwnerPkg will contain information about the package
14318                // which was uninstalled while keeping its data.
14319                PackageParser.Package dataOwnerPkg = installedPkg;
14320                if (dataOwnerPkg  == null) {
14321                    PackageSetting ps = mSettings.mPackages.get(packageName);
14322                    if (ps != null) {
14323                        dataOwnerPkg = ps.pkg;
14324                    }
14325                }
14326
14327                if (dataOwnerPkg != null) {
14328                    // If installed, the package will get access to data left on the device by its
14329                    // predecessor. As a security measure, this is permited only if this is not a
14330                    // version downgrade or if the predecessor package is marked as debuggable and
14331                    // a downgrade is explicitly requested.
14332                    //
14333                    // On debuggable platform builds, downgrades are permitted even for
14334                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14335                    // not offer security guarantees and thus it's OK to disable some security
14336                    // mechanisms to make debugging/testing easier on those builds. However, even on
14337                    // debuggable builds downgrades of packages are permitted only if requested via
14338                    // installFlags. This is because we aim to keep the behavior of debuggable
14339                    // platform builds as close as possible to the behavior of non-debuggable
14340                    // platform builds.
14341                    final boolean downgradeRequested =
14342                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14343                    final boolean packageDebuggable =
14344                                (dataOwnerPkg.applicationInfo.flags
14345                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14346                    final boolean downgradePermitted =
14347                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14348                    if (!downgradePermitted) {
14349                        try {
14350                            checkDowngrade(dataOwnerPkg, pkgLite);
14351                        } catch (PackageManagerException e) {
14352                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14353                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14354                        }
14355                    }
14356                }
14357
14358                if (installedPkg != null) {
14359                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14360                        // Check for updated system application.
14361                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14362                            if (onSd) {
14363                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14364                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14365                            }
14366                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14367                        } else {
14368                            if (onSd) {
14369                                // Install flag overrides everything.
14370                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14371                            }
14372                            // If current upgrade specifies particular preference
14373                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14374                                // Application explicitly specified internal.
14375                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14376                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14377                                // App explictly prefers external. Let policy decide
14378                            } else {
14379                                // Prefer previous location
14380                                if (isExternal(installedPkg)) {
14381                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14382                                }
14383                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14384                            }
14385                        }
14386                    } else {
14387                        // Invalid install. Return error code
14388                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14389                    }
14390                }
14391            }
14392            // All the special cases have been taken care of.
14393            // Return result based on recommended install location.
14394            if (onSd) {
14395                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14396            }
14397            return pkgLite.recommendedInstallLocation;
14398        }
14399
14400        /*
14401         * Invoke remote method to get package information and install
14402         * location values. Override install location based on default
14403         * policy if needed and then create install arguments based
14404         * on the install location.
14405         */
14406        public void handleStartCopy() throws RemoteException {
14407            int ret = PackageManager.INSTALL_SUCCEEDED;
14408
14409            // If we're already staged, we've firmly committed to an install location
14410            if (origin.staged) {
14411                if (origin.file != null) {
14412                    installFlags |= PackageManager.INSTALL_INTERNAL;
14413                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14414                } else if (origin.cid != null) {
14415                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14416                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14417                } else {
14418                    throw new IllegalStateException("Invalid stage location");
14419                }
14420            }
14421
14422            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14423            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14424            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14425            PackageInfoLite pkgLite = null;
14426
14427            if (onInt && onSd) {
14428                // Check if both bits are set.
14429                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14430                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14431            } else if (onSd && ephemeral) {
14432                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14433                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14434            } else {
14435                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14436                        packageAbiOverride);
14437
14438                if (DEBUG_EPHEMERAL && ephemeral) {
14439                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14440                }
14441
14442                /*
14443                 * If we have too little free space, try to free cache
14444                 * before giving up.
14445                 */
14446                if (!origin.staged && pkgLite.recommendedInstallLocation
14447                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14448                    // TODO: focus freeing disk space on the target device
14449                    final StorageManager storage = StorageManager.from(mContext);
14450                    final long lowThreshold = storage.getStorageLowBytes(
14451                            Environment.getDataDirectory());
14452
14453                    final long sizeBytes = mContainerService.calculateInstalledSize(
14454                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14455
14456                    try {
14457                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14458                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14459                                installFlags, packageAbiOverride);
14460                    } catch (InstallerException e) {
14461                        Slog.w(TAG, "Failed to free cache", e);
14462                    }
14463
14464                    /*
14465                     * The cache free must have deleted the file we
14466                     * downloaded to install.
14467                     *
14468                     * TODO: fix the "freeCache" call to not delete
14469                     *       the file we care about.
14470                     */
14471                    if (pkgLite.recommendedInstallLocation
14472                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14473                        pkgLite.recommendedInstallLocation
14474                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14475                    }
14476                }
14477            }
14478
14479            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14480                int loc = pkgLite.recommendedInstallLocation;
14481                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14482                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14483                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14484                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14485                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14486                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14487                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14488                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14489                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14490                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14491                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14492                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14493                } else {
14494                    // Override with defaults if needed.
14495                    loc = installLocationPolicy(pkgLite);
14496                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14497                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14498                    } else if (!onSd && !onInt) {
14499                        // Override install location with flags
14500                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14501                            // Set the flag to install on external media.
14502                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14503                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14504                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14505                            if (DEBUG_EPHEMERAL) {
14506                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14507                            }
14508                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14509                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14510                                    |PackageManager.INSTALL_INTERNAL);
14511                        } else {
14512                            // Make sure the flag for installing on external
14513                            // media is unset
14514                            installFlags |= PackageManager.INSTALL_INTERNAL;
14515                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14516                        }
14517                    }
14518                }
14519            }
14520
14521            final InstallArgs args = createInstallArgs(this);
14522            mArgs = args;
14523
14524            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14525                // TODO: http://b/22976637
14526                // Apps installed for "all" users use the device owner to verify the app
14527                UserHandle verifierUser = getUser();
14528                if (verifierUser == UserHandle.ALL) {
14529                    verifierUser = UserHandle.SYSTEM;
14530                }
14531
14532                /*
14533                 * Determine if we have any installed package verifiers. If we
14534                 * do, then we'll defer to them to verify the packages.
14535                 */
14536                final int requiredUid = mRequiredVerifierPackage == null ? -1
14537                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14538                                verifierUser.getIdentifier());
14539                if (!origin.existing && requiredUid != -1
14540                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14541                    final Intent verification = new Intent(
14542                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14543                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14544                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14545                            PACKAGE_MIME_TYPE);
14546                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14547
14548                    // Query all live verifiers based on current user state
14549                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14550                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14551
14552                    if (DEBUG_VERIFY) {
14553                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14554                                + verification.toString() + " with " + pkgLite.verifiers.length
14555                                + " optional verifiers");
14556                    }
14557
14558                    final int verificationId = mPendingVerificationToken++;
14559
14560                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14561
14562                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14563                            installerPackageName);
14564
14565                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14566                            installFlags);
14567
14568                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14569                            pkgLite.packageName);
14570
14571                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14572                            pkgLite.versionCode);
14573
14574                    if (verificationInfo != null) {
14575                        if (verificationInfo.originatingUri != null) {
14576                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14577                                    verificationInfo.originatingUri);
14578                        }
14579                        if (verificationInfo.referrer != null) {
14580                            verification.putExtra(Intent.EXTRA_REFERRER,
14581                                    verificationInfo.referrer);
14582                        }
14583                        if (verificationInfo.originatingUid >= 0) {
14584                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14585                                    verificationInfo.originatingUid);
14586                        }
14587                        if (verificationInfo.installerUid >= 0) {
14588                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14589                                    verificationInfo.installerUid);
14590                        }
14591                    }
14592
14593                    final PackageVerificationState verificationState = new PackageVerificationState(
14594                            requiredUid, args);
14595
14596                    mPendingVerification.append(verificationId, verificationState);
14597
14598                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14599                            receivers, verificationState);
14600
14601                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14602                    final long idleDuration = getVerificationTimeout();
14603
14604                    /*
14605                     * If any sufficient verifiers were listed in the package
14606                     * manifest, attempt to ask them.
14607                     */
14608                    if (sufficientVerifiers != null) {
14609                        final int N = sufficientVerifiers.size();
14610                        if (N == 0) {
14611                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14612                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14613                        } else {
14614                            for (int i = 0; i < N; i++) {
14615                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14616                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14617                                        verifierComponent.getPackageName(), idleDuration,
14618                                        verifierUser.getIdentifier(), false, "package verifier");
14619
14620                                final Intent sufficientIntent = new Intent(verification);
14621                                sufficientIntent.setComponent(verifierComponent);
14622                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14623                            }
14624                        }
14625                    }
14626
14627                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14628                            mRequiredVerifierPackage, receivers);
14629                    if (ret == PackageManager.INSTALL_SUCCEEDED
14630                            && mRequiredVerifierPackage != null) {
14631                        Trace.asyncTraceBegin(
14632                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14633                        /*
14634                         * Send the intent to the required verification agent,
14635                         * but only start the verification timeout after the
14636                         * target BroadcastReceivers have run.
14637                         */
14638                        verification.setComponent(requiredVerifierComponent);
14639                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14640                                mRequiredVerifierPackage, idleDuration,
14641                                verifierUser.getIdentifier(), false, "package verifier");
14642                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14643                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14644                                new BroadcastReceiver() {
14645                                    @Override
14646                                    public void onReceive(Context context, Intent intent) {
14647                                        final Message msg = mHandler
14648                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14649                                        msg.arg1 = verificationId;
14650                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14651                                    }
14652                                }, null, 0, null, null);
14653
14654                        /*
14655                         * We don't want the copy to proceed until verification
14656                         * succeeds, so null out this field.
14657                         */
14658                        mArgs = null;
14659                    }
14660                } else {
14661                    /*
14662                     * No package verification is enabled, so immediately start
14663                     * the remote call to initiate copy using temporary file.
14664                     */
14665                    ret = args.copyApk(mContainerService, true);
14666                }
14667            }
14668
14669            mRet = ret;
14670        }
14671
14672        @Override
14673        void handleReturnCode() {
14674            // If mArgs is null, then MCS couldn't be reached. When it
14675            // reconnects, it will try again to install. At that point, this
14676            // will succeed.
14677            if (mArgs != null) {
14678                processPendingInstall(mArgs, mRet);
14679            }
14680        }
14681
14682        @Override
14683        void handleServiceError() {
14684            mArgs = createInstallArgs(this);
14685            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14686        }
14687
14688        public boolean isForwardLocked() {
14689            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14690        }
14691    }
14692
14693    /**
14694     * Used during creation of InstallArgs
14695     *
14696     * @param installFlags package installation flags
14697     * @return true if should be installed on external storage
14698     */
14699    private static boolean installOnExternalAsec(int installFlags) {
14700        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14701            return false;
14702        }
14703        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14704            return true;
14705        }
14706        return false;
14707    }
14708
14709    /**
14710     * Used during creation of InstallArgs
14711     *
14712     * @param installFlags package installation flags
14713     * @return true if should be installed as forward locked
14714     */
14715    private static boolean installForwardLocked(int installFlags) {
14716        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14717    }
14718
14719    private InstallArgs createInstallArgs(InstallParams params) {
14720        if (params.move != null) {
14721            return new MoveInstallArgs(params);
14722        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14723            return new AsecInstallArgs(params);
14724        } else {
14725            return new FileInstallArgs(params);
14726        }
14727    }
14728
14729    /**
14730     * Create args that describe an existing installed package. Typically used
14731     * when cleaning up old installs, or used as a move source.
14732     */
14733    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14734            String resourcePath, String[] instructionSets) {
14735        final boolean isInAsec;
14736        if (installOnExternalAsec(installFlags)) {
14737            /* Apps on SD card are always in ASEC containers. */
14738            isInAsec = true;
14739        } else if (installForwardLocked(installFlags)
14740                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14741            /*
14742             * Forward-locked apps are only in ASEC containers if they're the
14743             * new style
14744             */
14745            isInAsec = true;
14746        } else {
14747            isInAsec = false;
14748        }
14749
14750        if (isInAsec) {
14751            return new AsecInstallArgs(codePath, instructionSets,
14752                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14753        } else {
14754            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14755        }
14756    }
14757
14758    static abstract class InstallArgs {
14759        /** @see InstallParams#origin */
14760        final OriginInfo origin;
14761        /** @see InstallParams#move */
14762        final MoveInfo move;
14763
14764        final IPackageInstallObserver2 observer;
14765        // Always refers to PackageManager flags only
14766        final int installFlags;
14767        final String installerPackageName;
14768        final String volumeUuid;
14769        final UserHandle user;
14770        final String abiOverride;
14771        final String[] installGrantPermissions;
14772        /** If non-null, drop an async trace when the install completes */
14773        final String traceMethod;
14774        final int traceCookie;
14775        final Certificate[][] certificates;
14776        final int installReason;
14777
14778        // The list of instruction sets supported by this app. This is currently
14779        // only used during the rmdex() phase to clean up resources. We can get rid of this
14780        // if we move dex files under the common app path.
14781        /* nullable */ String[] instructionSets;
14782
14783        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14784                int installFlags, String installerPackageName, String volumeUuid,
14785                UserHandle user, String[] instructionSets,
14786                String abiOverride, String[] installGrantPermissions,
14787                String traceMethod, int traceCookie, Certificate[][] certificates,
14788                int installReason) {
14789            this.origin = origin;
14790            this.move = move;
14791            this.installFlags = installFlags;
14792            this.observer = observer;
14793            this.installerPackageName = installerPackageName;
14794            this.volumeUuid = volumeUuid;
14795            this.user = user;
14796            this.instructionSets = instructionSets;
14797            this.abiOverride = abiOverride;
14798            this.installGrantPermissions = installGrantPermissions;
14799            this.traceMethod = traceMethod;
14800            this.traceCookie = traceCookie;
14801            this.certificates = certificates;
14802            this.installReason = installReason;
14803        }
14804
14805        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14806        abstract int doPreInstall(int status);
14807
14808        /**
14809         * Rename package into final resting place. All paths on the given
14810         * scanned package should be updated to reflect the rename.
14811         */
14812        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14813        abstract int doPostInstall(int status, int uid);
14814
14815        /** @see PackageSettingBase#codePathString */
14816        abstract String getCodePath();
14817        /** @see PackageSettingBase#resourcePathString */
14818        abstract String getResourcePath();
14819
14820        // Need installer lock especially for dex file removal.
14821        abstract void cleanUpResourcesLI();
14822        abstract boolean doPostDeleteLI(boolean delete);
14823
14824        /**
14825         * Called before the source arguments are copied. This is used mostly
14826         * for MoveParams when it needs to read the source file to put it in the
14827         * destination.
14828         */
14829        int doPreCopy() {
14830            return PackageManager.INSTALL_SUCCEEDED;
14831        }
14832
14833        /**
14834         * Called after the source arguments are copied. This is used mostly for
14835         * MoveParams when it needs to read the source file to put it in the
14836         * destination.
14837         */
14838        int doPostCopy(int uid) {
14839            return PackageManager.INSTALL_SUCCEEDED;
14840        }
14841
14842        protected boolean isFwdLocked() {
14843            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14844        }
14845
14846        protected boolean isExternalAsec() {
14847            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14848        }
14849
14850        protected boolean isEphemeral() {
14851            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14852        }
14853
14854        UserHandle getUser() {
14855            return user;
14856        }
14857    }
14858
14859    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14860        if (!allCodePaths.isEmpty()) {
14861            if (instructionSets == null) {
14862                throw new IllegalStateException("instructionSet == null");
14863            }
14864            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14865            for (String codePath : allCodePaths) {
14866                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14867                    try {
14868                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14869                    } catch (InstallerException ignored) {
14870                    }
14871                }
14872            }
14873        }
14874    }
14875
14876    /**
14877     * Logic to handle installation of non-ASEC applications, including copying
14878     * and renaming logic.
14879     */
14880    class FileInstallArgs extends InstallArgs {
14881        private File codeFile;
14882        private File resourceFile;
14883
14884        // Example topology:
14885        // /data/app/com.example/base.apk
14886        // /data/app/com.example/split_foo.apk
14887        // /data/app/com.example/lib/arm/libfoo.so
14888        // /data/app/com.example/lib/arm64/libfoo.so
14889        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14890
14891        /** New install */
14892        FileInstallArgs(InstallParams params) {
14893            super(params.origin, params.move, params.observer, params.installFlags,
14894                    params.installerPackageName, params.volumeUuid,
14895                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14896                    params.grantedRuntimePermissions,
14897                    params.traceMethod, params.traceCookie, params.certificates,
14898                    params.installReason);
14899            if (isFwdLocked()) {
14900                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14901            }
14902        }
14903
14904        /** Existing install */
14905        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14906            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14907                    null, null, null, 0, null /*certificates*/,
14908                    PackageManager.INSTALL_REASON_UNKNOWN);
14909            this.codeFile = (codePath != null) ? new File(codePath) : null;
14910            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14911        }
14912
14913        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14914            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14915            try {
14916                return doCopyApk(imcs, temp);
14917            } finally {
14918                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14919            }
14920        }
14921
14922        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14923            if (origin.staged) {
14924                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14925                codeFile = origin.file;
14926                resourceFile = origin.file;
14927                return PackageManager.INSTALL_SUCCEEDED;
14928            }
14929
14930            try {
14931                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14932                final File tempDir =
14933                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14934                codeFile = tempDir;
14935                resourceFile = tempDir;
14936            } catch (IOException e) {
14937                Slog.w(TAG, "Failed to create copy file: " + e);
14938                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14939            }
14940
14941            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14942                @Override
14943                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14944                    if (!FileUtils.isValidExtFilename(name)) {
14945                        throw new IllegalArgumentException("Invalid filename: " + name);
14946                    }
14947                    try {
14948                        final File file = new File(codeFile, name);
14949                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14950                                O_RDWR | O_CREAT, 0644);
14951                        Os.chmod(file.getAbsolutePath(), 0644);
14952                        return new ParcelFileDescriptor(fd);
14953                    } catch (ErrnoException e) {
14954                        throw new RemoteException("Failed to open: " + e.getMessage());
14955                    }
14956                }
14957            };
14958
14959            int ret = PackageManager.INSTALL_SUCCEEDED;
14960            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14961            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14962                Slog.e(TAG, "Failed to copy package");
14963                return ret;
14964            }
14965
14966            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14967            NativeLibraryHelper.Handle handle = null;
14968            try {
14969                handle = NativeLibraryHelper.Handle.create(codeFile);
14970                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14971                        abiOverride);
14972            } catch (IOException e) {
14973                Slog.e(TAG, "Copying native libraries failed", e);
14974                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14975            } finally {
14976                IoUtils.closeQuietly(handle);
14977            }
14978
14979            return ret;
14980        }
14981
14982        int doPreInstall(int status) {
14983            if (status != PackageManager.INSTALL_SUCCEEDED) {
14984                cleanUp();
14985            }
14986            return status;
14987        }
14988
14989        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14990            if (status != PackageManager.INSTALL_SUCCEEDED) {
14991                cleanUp();
14992                return false;
14993            }
14994
14995            final File targetDir = codeFile.getParentFile();
14996            final File beforeCodeFile = codeFile;
14997            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14998
14999            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15000            try {
15001                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15002            } catch (ErrnoException e) {
15003                Slog.w(TAG, "Failed to rename", e);
15004                return false;
15005            }
15006
15007            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15008                Slog.w(TAG, "Failed to restorecon");
15009                return false;
15010            }
15011
15012            // Reflect the rename internally
15013            codeFile = afterCodeFile;
15014            resourceFile = afterCodeFile;
15015
15016            // Reflect the rename in scanned details
15017            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15018            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15019                    afterCodeFile, pkg.baseCodePath));
15020            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15021                    afterCodeFile, pkg.splitCodePaths));
15022
15023            // Reflect the rename in app info
15024            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15025            pkg.setApplicationInfoCodePath(pkg.codePath);
15026            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15027            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15028            pkg.setApplicationInfoResourcePath(pkg.codePath);
15029            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15030            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15031
15032            return true;
15033        }
15034
15035        int doPostInstall(int status, int uid) {
15036            if (status != PackageManager.INSTALL_SUCCEEDED) {
15037                cleanUp();
15038            }
15039            return status;
15040        }
15041
15042        @Override
15043        String getCodePath() {
15044            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15045        }
15046
15047        @Override
15048        String getResourcePath() {
15049            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15050        }
15051
15052        private boolean cleanUp() {
15053            if (codeFile == null || !codeFile.exists()) {
15054                return false;
15055            }
15056
15057            removeCodePathLI(codeFile);
15058
15059            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15060                resourceFile.delete();
15061            }
15062
15063            return true;
15064        }
15065
15066        void cleanUpResourcesLI() {
15067            // Try enumerating all code paths before deleting
15068            List<String> allCodePaths = Collections.EMPTY_LIST;
15069            if (codeFile != null && codeFile.exists()) {
15070                try {
15071                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15072                    allCodePaths = pkg.getAllCodePaths();
15073                } catch (PackageParserException e) {
15074                    // Ignored; we tried our best
15075                }
15076            }
15077
15078            cleanUp();
15079            removeDexFiles(allCodePaths, instructionSets);
15080        }
15081
15082        boolean doPostDeleteLI(boolean delete) {
15083            // XXX err, shouldn't we respect the delete flag?
15084            cleanUpResourcesLI();
15085            return true;
15086        }
15087    }
15088
15089    private boolean isAsecExternal(String cid) {
15090        final String asecPath = PackageHelper.getSdFilesystem(cid);
15091        return !asecPath.startsWith(mAsecInternalPath);
15092    }
15093
15094    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15095            PackageManagerException {
15096        if (copyRet < 0) {
15097            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15098                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15099                throw new PackageManagerException(copyRet, message);
15100            }
15101        }
15102    }
15103
15104    /**
15105     * Extract the StorageManagerService "container ID" from the full code path of an
15106     * .apk.
15107     */
15108    static String cidFromCodePath(String fullCodePath) {
15109        int eidx = fullCodePath.lastIndexOf("/");
15110        String subStr1 = fullCodePath.substring(0, eidx);
15111        int sidx = subStr1.lastIndexOf("/");
15112        return subStr1.substring(sidx+1, eidx);
15113    }
15114
15115    /**
15116     * Logic to handle installation of ASEC applications, including copying and
15117     * renaming logic.
15118     */
15119    class AsecInstallArgs extends InstallArgs {
15120        static final String RES_FILE_NAME = "pkg.apk";
15121        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15122
15123        String cid;
15124        String packagePath;
15125        String resourcePath;
15126
15127        /** New install */
15128        AsecInstallArgs(InstallParams params) {
15129            super(params.origin, params.move, params.observer, params.installFlags,
15130                    params.installerPackageName, params.volumeUuid,
15131                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15132                    params.grantedRuntimePermissions,
15133                    params.traceMethod, params.traceCookie, params.certificates,
15134                    params.installReason);
15135        }
15136
15137        /** Existing install */
15138        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15139                        boolean isExternal, boolean isForwardLocked) {
15140            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15141                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15142                    instructionSets, null, null, null, 0, null /*certificates*/,
15143                    PackageManager.INSTALL_REASON_UNKNOWN);
15144            // Hackily pretend we're still looking at a full code path
15145            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15146                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15147            }
15148
15149            // Extract cid from fullCodePath
15150            int eidx = fullCodePath.lastIndexOf("/");
15151            String subStr1 = fullCodePath.substring(0, eidx);
15152            int sidx = subStr1.lastIndexOf("/");
15153            cid = subStr1.substring(sidx+1, eidx);
15154            setMountPath(subStr1);
15155        }
15156
15157        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15158            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15159                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15160                    instructionSets, null, null, null, 0, null /*certificates*/,
15161                    PackageManager.INSTALL_REASON_UNKNOWN);
15162            this.cid = cid;
15163            setMountPath(PackageHelper.getSdDir(cid));
15164        }
15165
15166        void createCopyFile() {
15167            cid = mInstallerService.allocateExternalStageCidLegacy();
15168        }
15169
15170        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15171            if (origin.staged && origin.cid != null) {
15172                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15173                cid = origin.cid;
15174                setMountPath(PackageHelper.getSdDir(cid));
15175                return PackageManager.INSTALL_SUCCEEDED;
15176            }
15177
15178            if (temp) {
15179                createCopyFile();
15180            } else {
15181                /*
15182                 * Pre-emptively destroy the container since it's destroyed if
15183                 * copying fails due to it existing anyway.
15184                 */
15185                PackageHelper.destroySdDir(cid);
15186            }
15187
15188            final String newMountPath = imcs.copyPackageToContainer(
15189                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15190                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15191
15192            if (newMountPath != null) {
15193                setMountPath(newMountPath);
15194                return PackageManager.INSTALL_SUCCEEDED;
15195            } else {
15196                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15197            }
15198        }
15199
15200        @Override
15201        String getCodePath() {
15202            return packagePath;
15203        }
15204
15205        @Override
15206        String getResourcePath() {
15207            return resourcePath;
15208        }
15209
15210        int doPreInstall(int status) {
15211            if (status != PackageManager.INSTALL_SUCCEEDED) {
15212                // Destroy container
15213                PackageHelper.destroySdDir(cid);
15214            } else {
15215                boolean mounted = PackageHelper.isContainerMounted(cid);
15216                if (!mounted) {
15217                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15218                            Process.SYSTEM_UID);
15219                    if (newMountPath != null) {
15220                        setMountPath(newMountPath);
15221                    } else {
15222                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15223                    }
15224                }
15225            }
15226            return status;
15227        }
15228
15229        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15230            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15231            String newMountPath = null;
15232            if (PackageHelper.isContainerMounted(cid)) {
15233                // Unmount the container
15234                if (!PackageHelper.unMountSdDir(cid)) {
15235                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15236                    return false;
15237                }
15238            }
15239            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15240                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15241                        " which might be stale. Will try to clean up.");
15242                // Clean up the stale container and proceed to recreate.
15243                if (!PackageHelper.destroySdDir(newCacheId)) {
15244                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15245                    return false;
15246                }
15247                // Successfully cleaned up stale container. Try to rename again.
15248                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15249                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15250                            + " inspite of cleaning it up.");
15251                    return false;
15252                }
15253            }
15254            if (!PackageHelper.isContainerMounted(newCacheId)) {
15255                Slog.w(TAG, "Mounting container " + newCacheId);
15256                newMountPath = PackageHelper.mountSdDir(newCacheId,
15257                        getEncryptKey(), Process.SYSTEM_UID);
15258            } else {
15259                newMountPath = PackageHelper.getSdDir(newCacheId);
15260            }
15261            if (newMountPath == null) {
15262                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15263                return false;
15264            }
15265            Log.i(TAG, "Succesfully renamed " + cid +
15266                    " to " + newCacheId +
15267                    " at new path: " + newMountPath);
15268            cid = newCacheId;
15269
15270            final File beforeCodeFile = new File(packagePath);
15271            setMountPath(newMountPath);
15272            final File afterCodeFile = new File(packagePath);
15273
15274            // Reflect the rename in scanned details
15275            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15276            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15277                    afterCodeFile, pkg.baseCodePath));
15278            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15279                    afterCodeFile, pkg.splitCodePaths));
15280
15281            // Reflect the rename in app info
15282            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15283            pkg.setApplicationInfoCodePath(pkg.codePath);
15284            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15285            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15286            pkg.setApplicationInfoResourcePath(pkg.codePath);
15287            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15288            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15289
15290            return true;
15291        }
15292
15293        private void setMountPath(String mountPath) {
15294            final File mountFile = new File(mountPath);
15295
15296            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15297            if (monolithicFile.exists()) {
15298                packagePath = monolithicFile.getAbsolutePath();
15299                if (isFwdLocked()) {
15300                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15301                } else {
15302                    resourcePath = packagePath;
15303                }
15304            } else {
15305                packagePath = mountFile.getAbsolutePath();
15306                resourcePath = packagePath;
15307            }
15308        }
15309
15310        int doPostInstall(int status, int uid) {
15311            if (status != PackageManager.INSTALL_SUCCEEDED) {
15312                cleanUp();
15313            } else {
15314                final int groupOwner;
15315                final String protectedFile;
15316                if (isFwdLocked()) {
15317                    groupOwner = UserHandle.getSharedAppGid(uid);
15318                    protectedFile = RES_FILE_NAME;
15319                } else {
15320                    groupOwner = -1;
15321                    protectedFile = null;
15322                }
15323
15324                if (uid < Process.FIRST_APPLICATION_UID
15325                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15326                    Slog.e(TAG, "Failed to finalize " + cid);
15327                    PackageHelper.destroySdDir(cid);
15328                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15329                }
15330
15331                boolean mounted = PackageHelper.isContainerMounted(cid);
15332                if (!mounted) {
15333                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15334                }
15335            }
15336            return status;
15337        }
15338
15339        private void cleanUp() {
15340            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15341
15342            // Destroy secure container
15343            PackageHelper.destroySdDir(cid);
15344        }
15345
15346        private List<String> getAllCodePaths() {
15347            final File codeFile = new File(getCodePath());
15348            if (codeFile != null && codeFile.exists()) {
15349                try {
15350                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15351                    return pkg.getAllCodePaths();
15352                } catch (PackageParserException e) {
15353                    // Ignored; we tried our best
15354                }
15355            }
15356            return Collections.EMPTY_LIST;
15357        }
15358
15359        void cleanUpResourcesLI() {
15360            // Enumerate all code paths before deleting
15361            cleanUpResourcesLI(getAllCodePaths());
15362        }
15363
15364        private void cleanUpResourcesLI(List<String> allCodePaths) {
15365            cleanUp();
15366            removeDexFiles(allCodePaths, instructionSets);
15367        }
15368
15369        String getPackageName() {
15370            return getAsecPackageName(cid);
15371        }
15372
15373        boolean doPostDeleteLI(boolean delete) {
15374            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15375            final List<String> allCodePaths = getAllCodePaths();
15376            boolean mounted = PackageHelper.isContainerMounted(cid);
15377            if (mounted) {
15378                // Unmount first
15379                if (PackageHelper.unMountSdDir(cid)) {
15380                    mounted = false;
15381                }
15382            }
15383            if (!mounted && delete) {
15384                cleanUpResourcesLI(allCodePaths);
15385            }
15386            return !mounted;
15387        }
15388
15389        @Override
15390        int doPreCopy() {
15391            if (isFwdLocked()) {
15392                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15393                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15394                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15395                }
15396            }
15397
15398            return PackageManager.INSTALL_SUCCEEDED;
15399        }
15400
15401        @Override
15402        int doPostCopy(int uid) {
15403            if (isFwdLocked()) {
15404                if (uid < Process.FIRST_APPLICATION_UID
15405                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15406                                RES_FILE_NAME)) {
15407                    Slog.e(TAG, "Failed to finalize " + cid);
15408                    PackageHelper.destroySdDir(cid);
15409                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15410                }
15411            }
15412
15413            return PackageManager.INSTALL_SUCCEEDED;
15414        }
15415    }
15416
15417    /**
15418     * Logic to handle movement of existing installed applications.
15419     */
15420    class MoveInstallArgs extends InstallArgs {
15421        private File codeFile;
15422        private File resourceFile;
15423
15424        /** New install */
15425        MoveInstallArgs(InstallParams params) {
15426            super(params.origin, params.move, params.observer, params.installFlags,
15427                    params.installerPackageName, params.volumeUuid,
15428                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15429                    params.grantedRuntimePermissions,
15430                    params.traceMethod, params.traceCookie, params.certificates,
15431                    params.installReason);
15432        }
15433
15434        int copyApk(IMediaContainerService imcs, boolean temp) {
15435            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15436                    + move.fromUuid + " to " + move.toUuid);
15437            synchronized (mInstaller) {
15438                try {
15439                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15440                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15441                } catch (InstallerException e) {
15442                    Slog.w(TAG, "Failed to move app", e);
15443                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15444                }
15445            }
15446
15447            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15448            resourceFile = codeFile;
15449            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15450
15451            return PackageManager.INSTALL_SUCCEEDED;
15452        }
15453
15454        int doPreInstall(int status) {
15455            if (status != PackageManager.INSTALL_SUCCEEDED) {
15456                cleanUp(move.toUuid);
15457            }
15458            return status;
15459        }
15460
15461        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15462            if (status != PackageManager.INSTALL_SUCCEEDED) {
15463                cleanUp(move.toUuid);
15464                return false;
15465            }
15466
15467            // Reflect the move in app info
15468            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15469            pkg.setApplicationInfoCodePath(pkg.codePath);
15470            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15471            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15472            pkg.setApplicationInfoResourcePath(pkg.codePath);
15473            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15474            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15475
15476            return true;
15477        }
15478
15479        int doPostInstall(int status, int uid) {
15480            if (status == PackageManager.INSTALL_SUCCEEDED) {
15481                cleanUp(move.fromUuid);
15482            } else {
15483                cleanUp(move.toUuid);
15484            }
15485            return status;
15486        }
15487
15488        @Override
15489        String getCodePath() {
15490            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15491        }
15492
15493        @Override
15494        String getResourcePath() {
15495            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15496        }
15497
15498        private boolean cleanUp(String volumeUuid) {
15499            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15500                    move.dataAppName);
15501            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15502            final int[] userIds = sUserManager.getUserIds();
15503            synchronized (mInstallLock) {
15504                // Clean up both app data and code
15505                // All package moves are frozen until finished
15506                for (int userId : userIds) {
15507                    try {
15508                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15509                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15510                    } catch (InstallerException e) {
15511                        Slog.w(TAG, String.valueOf(e));
15512                    }
15513                }
15514                removeCodePathLI(codeFile);
15515            }
15516            return true;
15517        }
15518
15519        void cleanUpResourcesLI() {
15520            throw new UnsupportedOperationException();
15521        }
15522
15523        boolean doPostDeleteLI(boolean delete) {
15524            throw new UnsupportedOperationException();
15525        }
15526    }
15527
15528    static String getAsecPackageName(String packageCid) {
15529        int idx = packageCid.lastIndexOf("-");
15530        if (idx == -1) {
15531            return packageCid;
15532        }
15533        return packageCid.substring(0, idx);
15534    }
15535
15536    // Utility method used to create code paths based on package name and available index.
15537    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15538        String idxStr = "";
15539        int idx = 1;
15540        // Fall back to default value of idx=1 if prefix is not
15541        // part of oldCodePath
15542        if (oldCodePath != null) {
15543            String subStr = oldCodePath;
15544            // Drop the suffix right away
15545            if (suffix != null && subStr.endsWith(suffix)) {
15546                subStr = subStr.substring(0, subStr.length() - suffix.length());
15547            }
15548            // If oldCodePath already contains prefix find out the
15549            // ending index to either increment or decrement.
15550            int sidx = subStr.lastIndexOf(prefix);
15551            if (sidx != -1) {
15552                subStr = subStr.substring(sidx + prefix.length());
15553                if (subStr != null) {
15554                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15555                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15556                    }
15557                    try {
15558                        idx = Integer.parseInt(subStr);
15559                        if (idx <= 1) {
15560                            idx++;
15561                        } else {
15562                            idx--;
15563                        }
15564                    } catch(NumberFormatException e) {
15565                    }
15566                }
15567            }
15568        }
15569        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15570        return prefix + idxStr;
15571    }
15572
15573    private File getNextCodePath(File targetDir, String packageName) {
15574        File result;
15575        SecureRandom random = new SecureRandom();
15576        byte[] bytes = new byte[16];
15577        do {
15578            random.nextBytes(bytes);
15579            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15580            result = new File(targetDir, packageName + "-" + suffix);
15581        } while (result.exists());
15582        return result;
15583    }
15584
15585    // Utility method that returns the relative package path with respect
15586    // to the installation directory. Like say for /data/data/com.test-1.apk
15587    // string com.test-1 is returned.
15588    static String deriveCodePathName(String codePath) {
15589        if (codePath == null) {
15590            return null;
15591        }
15592        final File codeFile = new File(codePath);
15593        final String name = codeFile.getName();
15594        if (codeFile.isDirectory()) {
15595            return name;
15596        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15597            final int lastDot = name.lastIndexOf('.');
15598            return name.substring(0, lastDot);
15599        } else {
15600            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15601            return null;
15602        }
15603    }
15604
15605    static class PackageInstalledInfo {
15606        String name;
15607        int uid;
15608        // The set of users that originally had this package installed.
15609        int[] origUsers;
15610        // The set of users that now have this package installed.
15611        int[] newUsers;
15612        PackageParser.Package pkg;
15613        int returnCode;
15614        String returnMsg;
15615        PackageRemovedInfo removedInfo;
15616        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15617
15618        public void setError(int code, String msg) {
15619            setReturnCode(code);
15620            setReturnMessage(msg);
15621            Slog.w(TAG, msg);
15622        }
15623
15624        public void setError(String msg, PackageParserException e) {
15625            setReturnCode(e.error);
15626            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15627            Slog.w(TAG, msg, e);
15628        }
15629
15630        public void setError(String msg, PackageManagerException e) {
15631            returnCode = e.error;
15632            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15633            Slog.w(TAG, msg, e);
15634        }
15635
15636        public void setReturnCode(int returnCode) {
15637            this.returnCode = returnCode;
15638            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15639            for (int i = 0; i < childCount; i++) {
15640                addedChildPackages.valueAt(i).returnCode = returnCode;
15641            }
15642        }
15643
15644        private void setReturnMessage(String returnMsg) {
15645            this.returnMsg = returnMsg;
15646            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15647            for (int i = 0; i < childCount; i++) {
15648                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15649            }
15650        }
15651
15652        // In some error cases we want to convey more info back to the observer
15653        String origPackage;
15654        String origPermission;
15655    }
15656
15657    /*
15658     * Install a non-existing package.
15659     */
15660    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15661            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15662            PackageInstalledInfo res, int installReason) {
15663        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15664
15665        // Remember this for later, in case we need to rollback this install
15666        String pkgName = pkg.packageName;
15667
15668        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15669
15670        synchronized(mPackages) {
15671            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15672            if (renamedPackage != null) {
15673                // A package with the same name is already installed, though
15674                // it has been renamed to an older name.  The package we
15675                // are trying to install should be installed as an update to
15676                // the existing one, but that has not been requested, so bail.
15677                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15678                        + " without first uninstalling package running as "
15679                        + renamedPackage);
15680                return;
15681            }
15682            if (mPackages.containsKey(pkgName)) {
15683                // Don't allow installation over an existing package with the same name.
15684                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15685                        + " without first uninstalling.");
15686                return;
15687            }
15688        }
15689
15690        try {
15691            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15692                    System.currentTimeMillis(), user);
15693
15694            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15695
15696            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15697                prepareAppDataAfterInstallLIF(newPackage);
15698
15699            } else {
15700                // Remove package from internal structures, but keep around any
15701                // data that might have already existed
15702                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15703                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15704            }
15705        } catch (PackageManagerException e) {
15706            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15707        }
15708
15709        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15710    }
15711
15712    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15713        // Can't rotate keys during boot or if sharedUser.
15714        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15715                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15716            return false;
15717        }
15718        // app is using upgradeKeySets; make sure all are valid
15719        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15720        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15721        for (int i = 0; i < upgradeKeySets.length; i++) {
15722            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15723                Slog.wtf(TAG, "Package "
15724                         + (oldPs.name != null ? oldPs.name : "<null>")
15725                         + " contains upgrade-key-set reference to unknown key-set: "
15726                         + upgradeKeySets[i]
15727                         + " reverting to signatures check.");
15728                return false;
15729            }
15730        }
15731        return true;
15732    }
15733
15734    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15735        // Upgrade keysets are being used.  Determine if new package has a superset of the
15736        // required keys.
15737        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15738        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15739        for (int i = 0; i < upgradeKeySets.length; i++) {
15740            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15741            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15742                return true;
15743            }
15744        }
15745        return false;
15746    }
15747
15748    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15749        try (DigestInputStream digestStream =
15750                new DigestInputStream(new FileInputStream(file), digest)) {
15751            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15752        }
15753    }
15754
15755    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15756            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15757            int installReason) {
15758        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15759
15760        final PackageParser.Package oldPackage;
15761        final String pkgName = pkg.packageName;
15762        final int[] allUsers;
15763        final int[] installedUsers;
15764
15765        synchronized(mPackages) {
15766            oldPackage = mPackages.get(pkgName);
15767            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15768
15769            // don't allow upgrade to target a release SDK from a pre-release SDK
15770            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15771                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15772            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15773                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15774            if (oldTargetsPreRelease
15775                    && !newTargetsPreRelease
15776                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15777                Slog.w(TAG, "Can't install package targeting released sdk");
15778                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15779                return;
15780            }
15781
15782            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15783
15784            // verify signatures are valid
15785            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15786                if (!checkUpgradeKeySetLP(ps, pkg)) {
15787                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15788                            "New package not signed by keys specified by upgrade-keysets: "
15789                                    + pkgName);
15790                    return;
15791                }
15792            } else {
15793                // default to original signature matching
15794                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15795                        != PackageManager.SIGNATURE_MATCH) {
15796                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15797                            "New package has a different signature: " + pkgName);
15798                    return;
15799                }
15800            }
15801
15802            // don't allow a system upgrade unless the upgrade hash matches
15803            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15804                byte[] digestBytes = null;
15805                try {
15806                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15807                    updateDigest(digest, new File(pkg.baseCodePath));
15808                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15809                        for (String path : pkg.splitCodePaths) {
15810                            updateDigest(digest, new File(path));
15811                        }
15812                    }
15813                    digestBytes = digest.digest();
15814                } catch (NoSuchAlgorithmException | IOException e) {
15815                    res.setError(INSTALL_FAILED_INVALID_APK,
15816                            "Could not compute hash: " + pkgName);
15817                    return;
15818                }
15819                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15820                    res.setError(INSTALL_FAILED_INVALID_APK,
15821                            "New package fails restrict-update check: " + pkgName);
15822                    return;
15823                }
15824                // retain upgrade restriction
15825                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15826            }
15827
15828            // Check for shared user id changes
15829            String invalidPackageName =
15830                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15831            if (invalidPackageName != null) {
15832                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15833                        "Package " + invalidPackageName + " tried to change user "
15834                                + oldPackage.mSharedUserId);
15835                return;
15836            }
15837
15838            // In case of rollback, remember per-user/profile install state
15839            allUsers = sUserManager.getUserIds();
15840            installedUsers = ps.queryInstalledUsers(allUsers, true);
15841
15842            // don't allow an upgrade from full to ephemeral
15843            if (isInstantApp) {
15844                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15845                    for (int currentUser : allUsers) {
15846                        if (!ps.getInstantApp(currentUser)) {
15847                            // can't downgrade from full to instant
15848                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15849                                    + " for user: " + currentUser);
15850                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15851                            return;
15852                        }
15853                    }
15854                } else if (!ps.getInstantApp(user.getIdentifier())) {
15855                    // can't downgrade from full to instant
15856                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15857                            + " for user: " + user.getIdentifier());
15858                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15859                    return;
15860                }
15861            }
15862        }
15863
15864        // Update what is removed
15865        res.removedInfo = new PackageRemovedInfo();
15866        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15867        res.removedInfo.removedPackage = oldPackage.packageName;
15868        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15869        res.removedInfo.isUpdate = true;
15870        res.removedInfo.origUsers = installedUsers;
15871        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15872        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15873        for (int i = 0; i < installedUsers.length; i++) {
15874            final int userId = installedUsers[i];
15875            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15876        }
15877
15878        final int childCount = (oldPackage.childPackages != null)
15879                ? oldPackage.childPackages.size() : 0;
15880        for (int i = 0; i < childCount; i++) {
15881            boolean childPackageUpdated = false;
15882            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15883            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15884            if (res.addedChildPackages != null) {
15885                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15886                if (childRes != null) {
15887                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15888                    childRes.removedInfo.removedPackage = childPkg.packageName;
15889                    childRes.removedInfo.isUpdate = true;
15890                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15891                    childPackageUpdated = true;
15892                }
15893            }
15894            if (!childPackageUpdated) {
15895                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15896                childRemovedRes.removedPackage = childPkg.packageName;
15897                childRemovedRes.isUpdate = false;
15898                childRemovedRes.dataRemoved = true;
15899                synchronized (mPackages) {
15900                    if (childPs != null) {
15901                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15902                    }
15903                }
15904                if (res.removedInfo.removedChildPackages == null) {
15905                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15906                }
15907                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15908            }
15909        }
15910
15911        boolean sysPkg = (isSystemApp(oldPackage));
15912        if (sysPkg) {
15913            // Set the system/privileged flags as needed
15914            final boolean privileged =
15915                    (oldPackage.applicationInfo.privateFlags
15916                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15917            final int systemPolicyFlags = policyFlags
15918                    | PackageParser.PARSE_IS_SYSTEM
15919                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15920
15921            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15922                    user, allUsers, installerPackageName, res, installReason);
15923        } else {
15924            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15925                    user, allUsers, installerPackageName, res, installReason);
15926        }
15927    }
15928
15929    public List<String> getPreviousCodePaths(String packageName) {
15930        final PackageSetting ps = mSettings.mPackages.get(packageName);
15931        final List<String> result = new ArrayList<String>();
15932        if (ps != null && ps.oldCodePaths != null) {
15933            result.addAll(ps.oldCodePaths);
15934        }
15935        return result;
15936    }
15937
15938    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15939            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15940            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15941            int installReason) {
15942        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15943                + deletedPackage);
15944
15945        String pkgName = deletedPackage.packageName;
15946        boolean deletedPkg = true;
15947        boolean addedPkg = false;
15948        boolean updatedSettings = false;
15949        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15950        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15951                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15952
15953        final long origUpdateTime = (pkg.mExtras != null)
15954                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15955
15956        // First delete the existing package while retaining the data directory
15957        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15958                res.removedInfo, true, pkg)) {
15959            // If the existing package wasn't successfully deleted
15960            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15961            deletedPkg = false;
15962        } else {
15963            // Successfully deleted the old package; proceed with replace.
15964
15965            // If deleted package lived in a container, give users a chance to
15966            // relinquish resources before killing.
15967            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15968                if (DEBUG_INSTALL) {
15969                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15970                }
15971                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15972                final ArrayList<String> pkgList = new ArrayList<String>(1);
15973                pkgList.add(deletedPackage.applicationInfo.packageName);
15974                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15975            }
15976
15977            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15978                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15979            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15980
15981            try {
15982                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15983                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15984                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15985                        installReason);
15986
15987                // Update the in-memory copy of the previous code paths.
15988                PackageSetting ps = mSettings.mPackages.get(pkgName);
15989                if (!killApp) {
15990                    if (ps.oldCodePaths == null) {
15991                        ps.oldCodePaths = new ArraySet<>();
15992                    }
15993                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15994                    if (deletedPackage.splitCodePaths != null) {
15995                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15996                    }
15997                } else {
15998                    ps.oldCodePaths = null;
15999                }
16000                if (ps.childPackageNames != null) {
16001                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16002                        final String childPkgName = ps.childPackageNames.get(i);
16003                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16004                        childPs.oldCodePaths = ps.oldCodePaths;
16005                    }
16006                }
16007                // set instant app status, but, only if it's explicitly specified
16008                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16009                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16010                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16011                prepareAppDataAfterInstallLIF(newPackage);
16012                addedPkg = true;
16013                mDexManager.notifyPackageUpdated(newPackage.packageName,
16014                        newPackage.baseCodePath, newPackage.splitCodePaths);
16015            } catch (PackageManagerException e) {
16016                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16017            }
16018        }
16019
16020        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16021            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16022
16023            // Revert all internal state mutations and added folders for the failed install
16024            if (addedPkg) {
16025                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16026                        res.removedInfo, true, null);
16027            }
16028
16029            // Restore the old package
16030            if (deletedPkg) {
16031                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16032                File restoreFile = new File(deletedPackage.codePath);
16033                // Parse old package
16034                boolean oldExternal = isExternal(deletedPackage);
16035                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16036                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16037                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16038                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16039                try {
16040                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16041                            null);
16042                } catch (PackageManagerException e) {
16043                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16044                            + e.getMessage());
16045                    return;
16046                }
16047
16048                synchronized (mPackages) {
16049                    // Ensure the installer package name up to date
16050                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16051
16052                    // Update permissions for restored package
16053                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16054
16055                    mSettings.writeLPr();
16056                }
16057
16058                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16059            }
16060        } else {
16061            synchronized (mPackages) {
16062                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16063                if (ps != null) {
16064                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16065                    if (res.removedInfo.removedChildPackages != null) {
16066                        final int childCount = res.removedInfo.removedChildPackages.size();
16067                        // Iterate in reverse as we may modify the collection
16068                        for (int i = childCount - 1; i >= 0; i--) {
16069                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16070                            if (res.addedChildPackages.containsKey(childPackageName)) {
16071                                res.removedInfo.removedChildPackages.removeAt(i);
16072                            } else {
16073                                PackageRemovedInfo childInfo = res.removedInfo
16074                                        .removedChildPackages.valueAt(i);
16075                                childInfo.removedForAllUsers = mPackages.get(
16076                                        childInfo.removedPackage) == null;
16077                            }
16078                        }
16079                    }
16080                }
16081            }
16082        }
16083    }
16084
16085    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16086            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16087            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16088            int installReason) {
16089        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16090                + ", old=" + deletedPackage);
16091
16092        final boolean disabledSystem;
16093
16094        // Remove existing system package
16095        removePackageLI(deletedPackage, true);
16096
16097        synchronized (mPackages) {
16098            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16099        }
16100        if (!disabledSystem) {
16101            // We didn't need to disable the .apk as a current system package,
16102            // which means we are replacing another update that is already
16103            // installed.  We need to make sure to delete the older one's .apk.
16104            res.removedInfo.args = createInstallArgsForExisting(0,
16105                    deletedPackage.applicationInfo.getCodePath(),
16106                    deletedPackage.applicationInfo.getResourcePath(),
16107                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16108        } else {
16109            res.removedInfo.args = null;
16110        }
16111
16112        // Successfully disabled the old package. Now proceed with re-installation
16113        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16114                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16115        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16116
16117        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16118        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16119                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16120
16121        PackageParser.Package newPackage = null;
16122        try {
16123            // Add the package to the internal data structures
16124            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16125
16126            // Set the update and install times
16127            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16128            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16129                    System.currentTimeMillis());
16130
16131            // Update the package dynamic state if succeeded
16132            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16133                // Now that the install succeeded make sure we remove data
16134                // directories for any child package the update removed.
16135                final int deletedChildCount = (deletedPackage.childPackages != null)
16136                        ? deletedPackage.childPackages.size() : 0;
16137                final int newChildCount = (newPackage.childPackages != null)
16138                        ? newPackage.childPackages.size() : 0;
16139                for (int i = 0; i < deletedChildCount; i++) {
16140                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16141                    boolean childPackageDeleted = true;
16142                    for (int j = 0; j < newChildCount; j++) {
16143                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16144                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16145                            childPackageDeleted = false;
16146                            break;
16147                        }
16148                    }
16149                    if (childPackageDeleted) {
16150                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16151                                deletedChildPkg.packageName);
16152                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16153                            PackageRemovedInfo removedChildRes = res.removedInfo
16154                                    .removedChildPackages.get(deletedChildPkg.packageName);
16155                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16156                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16157                        }
16158                    }
16159                }
16160
16161                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16162                        installReason);
16163                prepareAppDataAfterInstallLIF(newPackage);
16164
16165                mDexManager.notifyPackageUpdated(newPackage.packageName,
16166                            newPackage.baseCodePath, newPackage.splitCodePaths);
16167            }
16168        } catch (PackageManagerException e) {
16169            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16170            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16171        }
16172
16173        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16174            // Re installation failed. Restore old information
16175            // Remove new pkg information
16176            if (newPackage != null) {
16177                removeInstalledPackageLI(newPackage, true);
16178            }
16179            // Add back the old system package
16180            try {
16181                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16182            } catch (PackageManagerException e) {
16183                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16184            }
16185
16186            synchronized (mPackages) {
16187                if (disabledSystem) {
16188                    enableSystemPackageLPw(deletedPackage);
16189                }
16190
16191                // Ensure the installer package name up to date
16192                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16193
16194                // Update permissions for restored package
16195                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16196
16197                mSettings.writeLPr();
16198            }
16199
16200            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16201                    + " after failed upgrade");
16202        }
16203    }
16204
16205    /**
16206     * Checks whether the parent or any of the child packages have a change shared
16207     * user. For a package to be a valid update the shred users of the parent and
16208     * the children should match. We may later support changing child shared users.
16209     * @param oldPkg The updated package.
16210     * @param newPkg The update package.
16211     * @return The shared user that change between the versions.
16212     */
16213    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16214            PackageParser.Package newPkg) {
16215        // Check parent shared user
16216        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16217            return newPkg.packageName;
16218        }
16219        // Check child shared users
16220        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16221        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16222        for (int i = 0; i < newChildCount; i++) {
16223            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16224            // If this child was present, did it have the same shared user?
16225            for (int j = 0; j < oldChildCount; j++) {
16226                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16227                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16228                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16229                    return newChildPkg.packageName;
16230                }
16231            }
16232        }
16233        return null;
16234    }
16235
16236    private void removeNativeBinariesLI(PackageSetting ps) {
16237        // Remove the lib path for the parent package
16238        if (ps != null) {
16239            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16240            // Remove the lib path for the child packages
16241            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16242            for (int i = 0; i < childCount; i++) {
16243                PackageSetting childPs = null;
16244                synchronized (mPackages) {
16245                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16246                }
16247                if (childPs != null) {
16248                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16249                            .legacyNativeLibraryPathString);
16250                }
16251            }
16252        }
16253    }
16254
16255    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16256        // Enable the parent package
16257        mSettings.enableSystemPackageLPw(pkg.packageName);
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.enableSystemPackageLPw(childPkg.packageName);
16263        }
16264    }
16265
16266    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16267            PackageParser.Package newPkg) {
16268        // Disable the parent package (parent always replaced)
16269        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16270        // Disable the child packages
16271        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16272        for (int i = 0; i < childCount; i++) {
16273            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16274            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16275            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16276        }
16277        return disabled;
16278    }
16279
16280    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16281            String installerPackageName) {
16282        // Enable the parent package
16283        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16284        // Enable the child packages
16285        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16286        for (int i = 0; i < childCount; i++) {
16287            PackageParser.Package childPkg = pkg.childPackages.get(i);
16288            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16289        }
16290    }
16291
16292    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16293        // Collect all used permissions in the UID
16294        ArraySet<String> usedPermissions = new ArraySet<>();
16295        final int packageCount = su.packages.size();
16296        for (int i = 0; i < packageCount; i++) {
16297            PackageSetting ps = su.packages.valueAt(i);
16298            if (ps.pkg == null) {
16299                continue;
16300            }
16301            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16302            for (int j = 0; j < requestedPermCount; j++) {
16303                String permission = ps.pkg.requestedPermissions.get(j);
16304                BasePermission bp = mSettings.mPermissions.get(permission);
16305                if (bp != null) {
16306                    usedPermissions.add(permission);
16307                }
16308            }
16309        }
16310
16311        PermissionsState permissionsState = su.getPermissionsState();
16312        // Prune install permissions
16313        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16314        final int installPermCount = installPermStates.size();
16315        for (int i = installPermCount - 1; i >= 0;  i--) {
16316            PermissionState permissionState = installPermStates.get(i);
16317            if (!usedPermissions.contains(permissionState.getName())) {
16318                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16319                if (bp != null) {
16320                    permissionsState.revokeInstallPermission(bp);
16321                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16322                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16323                }
16324            }
16325        }
16326
16327        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16328
16329        // Prune runtime permissions
16330        for (int userId : allUserIds) {
16331            List<PermissionState> runtimePermStates = permissionsState
16332                    .getRuntimePermissionStates(userId);
16333            final int runtimePermCount = runtimePermStates.size();
16334            for (int i = runtimePermCount - 1; i >= 0; i--) {
16335                PermissionState permissionState = runtimePermStates.get(i);
16336                if (!usedPermissions.contains(permissionState.getName())) {
16337                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16338                    if (bp != null) {
16339                        permissionsState.revokeRuntimePermission(bp, userId);
16340                        permissionsState.updatePermissionFlags(bp, userId,
16341                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16342                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16343                                runtimePermissionChangedUserIds, userId);
16344                    }
16345                }
16346            }
16347        }
16348
16349        return runtimePermissionChangedUserIds;
16350    }
16351
16352    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16353            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16354        // Update the parent package setting
16355        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16356                res, user, installReason);
16357        // Update the child packages setting
16358        final int childCount = (newPackage.childPackages != null)
16359                ? newPackage.childPackages.size() : 0;
16360        for (int i = 0; i < childCount; i++) {
16361            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16362            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16363            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16364                    childRes.origUsers, childRes, user, installReason);
16365        }
16366    }
16367
16368    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16369            String installerPackageName, int[] allUsers, int[] installedForUsers,
16370            PackageInstalledInfo res, UserHandle user, int installReason) {
16371        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16372
16373        String pkgName = newPackage.packageName;
16374        synchronized (mPackages) {
16375            //write settings. the installStatus will be incomplete at this stage.
16376            //note that the new package setting would have already been
16377            //added to mPackages. It hasn't been persisted yet.
16378            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16379            // TODO: Remove this write? It's also written at the end of this method
16380            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16381            mSettings.writeLPr();
16382            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16383        }
16384
16385        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16386        synchronized (mPackages) {
16387            updatePermissionsLPw(newPackage.packageName, newPackage,
16388                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16389                            ? UPDATE_PERMISSIONS_ALL : 0));
16390            // For system-bundled packages, we assume that installing an upgraded version
16391            // of the package implies that the user actually wants to run that new code,
16392            // so we enable the package.
16393            PackageSetting ps = mSettings.mPackages.get(pkgName);
16394            final int userId = user.getIdentifier();
16395            if (ps != null) {
16396                if (isSystemApp(newPackage)) {
16397                    if (DEBUG_INSTALL) {
16398                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16399                    }
16400                    // Enable system package for requested users
16401                    if (res.origUsers != null) {
16402                        for (int origUserId : res.origUsers) {
16403                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16404                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16405                                        origUserId, installerPackageName);
16406                            }
16407                        }
16408                    }
16409                    // Also convey the prior install/uninstall state
16410                    if (allUsers != null && installedForUsers != null) {
16411                        for (int currentUserId : allUsers) {
16412                            final boolean installed = ArrayUtils.contains(
16413                                    installedForUsers, currentUserId);
16414                            if (DEBUG_INSTALL) {
16415                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16416                            }
16417                            ps.setInstalled(installed, currentUserId);
16418                        }
16419                        // these install state changes will be persisted in the
16420                        // upcoming call to mSettings.writeLPr().
16421                    }
16422                }
16423                // It's implied that when a user requests installation, they want the app to be
16424                // installed and enabled.
16425                if (userId != UserHandle.USER_ALL) {
16426                    ps.setInstalled(true, userId);
16427                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16428                }
16429
16430                // When replacing an existing package, preserve the original install reason for all
16431                // users that had the package installed before.
16432                final Set<Integer> previousUserIds = new ArraySet<>();
16433                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16434                    final int installReasonCount = res.removedInfo.installReasons.size();
16435                    for (int i = 0; i < installReasonCount; i++) {
16436                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16437                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16438                        ps.setInstallReason(previousInstallReason, previousUserId);
16439                        previousUserIds.add(previousUserId);
16440                    }
16441                }
16442
16443                // Set install reason for users that are having the package newly installed.
16444                if (userId == UserHandle.USER_ALL) {
16445                    for (int currentUserId : sUserManager.getUserIds()) {
16446                        if (!previousUserIds.contains(currentUserId)) {
16447                            ps.setInstallReason(installReason, currentUserId);
16448                        }
16449                    }
16450                } else if (!previousUserIds.contains(userId)) {
16451                    ps.setInstallReason(installReason, userId);
16452                }
16453                mSettings.writeKernelMappingLPr(ps);
16454            }
16455            res.name = pkgName;
16456            res.uid = newPackage.applicationInfo.uid;
16457            res.pkg = newPackage;
16458            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16459            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16460            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16461            //to update install status
16462            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16463            mSettings.writeLPr();
16464            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16465        }
16466
16467        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16468    }
16469
16470    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16471        try {
16472            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16473            installPackageLI(args, res);
16474        } finally {
16475            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16476        }
16477    }
16478
16479    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16480        final int installFlags = args.installFlags;
16481        final String installerPackageName = args.installerPackageName;
16482        final String volumeUuid = args.volumeUuid;
16483        final File tmpPackageFile = new File(args.getCodePath());
16484        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16485        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16486                || (args.volumeUuid != null));
16487        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16488        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16489        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16490        boolean replace = false;
16491        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16492        if (args.move != null) {
16493            // moving a complete application; perform an initial scan on the new install location
16494            scanFlags |= SCAN_INITIAL;
16495        }
16496        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16497            scanFlags |= SCAN_DONT_KILL_APP;
16498        }
16499        if (instantApp) {
16500            scanFlags |= SCAN_AS_INSTANT_APP;
16501        }
16502        if (fullApp) {
16503            scanFlags |= SCAN_AS_FULL_APP;
16504        }
16505
16506        // Result object to be returned
16507        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16508
16509        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16510
16511        // Sanity check
16512        if (instantApp && (forwardLocked || onExternal)) {
16513            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16514                    + " external=" + onExternal);
16515            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16516            return;
16517        }
16518
16519        // Retrieve PackageSettings and parse package
16520        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16521                | PackageParser.PARSE_ENFORCE_CODE
16522                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16523                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16524                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16525                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16526        PackageParser pp = new PackageParser();
16527        pp.setSeparateProcesses(mSeparateProcesses);
16528        pp.setDisplayMetrics(mMetrics);
16529        pp.setCallback(mPackageParserCallback);
16530
16531        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16532        final PackageParser.Package pkg;
16533        try {
16534            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16535        } catch (PackageParserException e) {
16536            res.setError("Failed parse during installPackageLI", e);
16537            return;
16538        } finally {
16539            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16540        }
16541
16542        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16543        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16544            Slog.w(TAG, "Instant app package " + pkg.packageName
16545                    + " does not target O, this will be a fatal error.");
16546            // STOPSHIP: Make this a fatal error
16547            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16548        }
16549        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16550            Slog.w(TAG, "Instant app package " + pkg.packageName
16551                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16552            // STOPSHIP: Make this a fatal error
16553            pkg.applicationInfo.targetSandboxVersion = 2;
16554        }
16555
16556        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16557            // Static shared libraries have synthetic package names
16558            renameStaticSharedLibraryPackage(pkg);
16559
16560            // No static shared libs on external storage
16561            if (onExternal) {
16562                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16563                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16564                        "Packages declaring static-shared libs cannot be updated");
16565                return;
16566            }
16567        }
16568
16569        // If we are installing a clustered package add results for the children
16570        if (pkg.childPackages != null) {
16571            synchronized (mPackages) {
16572                final int childCount = pkg.childPackages.size();
16573                for (int i = 0; i < childCount; i++) {
16574                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16575                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16576                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16577                    childRes.pkg = childPkg;
16578                    childRes.name = childPkg.packageName;
16579                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16580                    if (childPs != null) {
16581                        childRes.origUsers = childPs.queryInstalledUsers(
16582                                sUserManager.getUserIds(), true);
16583                    }
16584                    if ((mPackages.containsKey(childPkg.packageName))) {
16585                        childRes.removedInfo = new PackageRemovedInfo();
16586                        childRes.removedInfo.removedPackage = childPkg.packageName;
16587                    }
16588                    if (res.addedChildPackages == null) {
16589                        res.addedChildPackages = new ArrayMap<>();
16590                    }
16591                    res.addedChildPackages.put(childPkg.packageName, childRes);
16592                }
16593            }
16594        }
16595
16596        // If package doesn't declare API override, mark that we have an install
16597        // time CPU ABI override.
16598        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16599            pkg.cpuAbiOverride = args.abiOverride;
16600        }
16601
16602        String pkgName = res.name = pkg.packageName;
16603        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16604            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16605                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16606                return;
16607            }
16608        }
16609
16610        try {
16611            // either use what we've been given or parse directly from the APK
16612            if (args.certificates != null) {
16613                try {
16614                    PackageParser.populateCertificates(pkg, args.certificates);
16615                } catch (PackageParserException e) {
16616                    // there was something wrong with the certificates we were given;
16617                    // try to pull them from the APK
16618                    PackageParser.collectCertificates(pkg, parseFlags);
16619                }
16620            } else {
16621                PackageParser.collectCertificates(pkg, parseFlags);
16622            }
16623        } catch (PackageParserException e) {
16624            res.setError("Failed collect during installPackageLI", e);
16625            return;
16626        }
16627
16628        // Get rid of all references to package scan path via parser.
16629        pp = null;
16630        String oldCodePath = null;
16631        boolean systemApp = false;
16632        synchronized (mPackages) {
16633            // Check if installing already existing package
16634            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16635                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16636                if (pkg.mOriginalPackages != null
16637                        && pkg.mOriginalPackages.contains(oldName)
16638                        && mPackages.containsKey(oldName)) {
16639                    // This package is derived from an original package,
16640                    // and this device has been updating from that original
16641                    // name.  We must continue using the original name, so
16642                    // rename the new package here.
16643                    pkg.setPackageName(oldName);
16644                    pkgName = pkg.packageName;
16645                    replace = true;
16646                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16647                            + oldName + " pkgName=" + pkgName);
16648                } else if (mPackages.containsKey(pkgName)) {
16649                    // This package, under its official name, already exists
16650                    // on the device; we should replace it.
16651                    replace = true;
16652                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16653                }
16654
16655                // Child packages are installed through the parent package
16656                if (pkg.parentPackage != null) {
16657                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16658                            "Package " + pkg.packageName + " is child of package "
16659                                    + pkg.parentPackage.parentPackage + ". Child packages "
16660                                    + "can be updated only through the parent package.");
16661                    return;
16662                }
16663
16664                if (replace) {
16665                    // Prevent apps opting out from runtime permissions
16666                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16667                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16668                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16669                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16670                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16671                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16672                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16673                                        + " doesn't support runtime permissions but the old"
16674                                        + " target SDK " + oldTargetSdk + " does.");
16675                        return;
16676                    }
16677
16678                    // Prevent installing of child packages
16679                    if (oldPackage.parentPackage != null) {
16680                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16681                                "Package " + pkg.packageName + " is child of package "
16682                                        + oldPackage.parentPackage + ". Child packages "
16683                                        + "can be updated only through the parent package.");
16684                        return;
16685                    }
16686                }
16687            }
16688
16689            PackageSetting ps = mSettings.mPackages.get(pkgName);
16690            if (ps != null) {
16691                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16692
16693                // Static shared libs have same package with different versions where
16694                // we internally use a synthetic package name to allow multiple versions
16695                // of the same package, therefore we need to compare signatures against
16696                // the package setting for the latest library version.
16697                PackageSetting signatureCheckPs = ps;
16698                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16699                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16700                    if (libraryEntry != null) {
16701                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16702                    }
16703                }
16704
16705                // Quick sanity check that we're signed correctly if updating;
16706                // we'll check this again later when scanning, but we want to
16707                // bail early here before tripping over redefined permissions.
16708                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16709                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16710                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16711                                + pkg.packageName + " upgrade keys do not match the "
16712                                + "previously installed version");
16713                        return;
16714                    }
16715                } else {
16716                    try {
16717                        verifySignaturesLP(signatureCheckPs, pkg);
16718                    } catch (PackageManagerException e) {
16719                        res.setError(e.error, e.getMessage());
16720                        return;
16721                    }
16722                }
16723
16724                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16725                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16726                    systemApp = (ps.pkg.applicationInfo.flags &
16727                            ApplicationInfo.FLAG_SYSTEM) != 0;
16728                }
16729                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16730            }
16731
16732            int N = pkg.permissions.size();
16733            for (int i = N-1; i >= 0; i--) {
16734                PackageParser.Permission perm = pkg.permissions.get(i);
16735                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16736
16737                // Don't allow anyone but the platform to define ephemeral permissions.
16738                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16739                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16740                    Slog.w(TAG, "Package " + pkg.packageName
16741                            + " attempting to delcare ephemeral permission "
16742                            + perm.info.name + "; Removing ephemeral.");
16743                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16744                }
16745                // Check whether the newly-scanned package wants to define an already-defined perm
16746                if (bp != null) {
16747                    // If the defining package is signed with our cert, it's okay.  This
16748                    // also includes the "updating the same package" case, of course.
16749                    // "updating same package" could also involve key-rotation.
16750                    final boolean sigsOk;
16751                    if (bp.sourcePackage.equals(pkg.packageName)
16752                            && (bp.packageSetting instanceof PackageSetting)
16753                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16754                                    scanFlags))) {
16755                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16756                    } else {
16757                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16758                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16759                    }
16760                    if (!sigsOk) {
16761                        // If the owning package is the system itself, we log but allow
16762                        // install to proceed; we fail the install on all other permission
16763                        // redefinitions.
16764                        if (!bp.sourcePackage.equals("android")) {
16765                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16766                                    + pkg.packageName + " attempting to redeclare permission "
16767                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16768                            res.origPermission = perm.info.name;
16769                            res.origPackage = bp.sourcePackage;
16770                            return;
16771                        } else {
16772                            Slog.w(TAG, "Package " + pkg.packageName
16773                                    + " attempting to redeclare system permission "
16774                                    + perm.info.name + "; ignoring new declaration");
16775                            pkg.permissions.remove(i);
16776                        }
16777                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16778                        // Prevent apps to change protection level to dangerous from any other
16779                        // type as this would allow a privilege escalation where an app adds a
16780                        // normal/signature permission in other app's group and later redefines
16781                        // it as dangerous leading to the group auto-grant.
16782                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16783                                == PermissionInfo.PROTECTION_DANGEROUS) {
16784                            if (bp != null && !bp.isRuntime()) {
16785                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16786                                        + "non-runtime permission " + perm.info.name
16787                                        + " to runtime; keeping old protection level");
16788                                perm.info.protectionLevel = bp.protectionLevel;
16789                            }
16790                        }
16791                    }
16792                }
16793            }
16794        }
16795
16796        if (systemApp) {
16797            if (onExternal) {
16798                // Abort update; system app can't be replaced with app on sdcard
16799                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16800                        "Cannot install updates to system apps on sdcard");
16801                return;
16802            } else if (instantApp) {
16803                // Abort update; system app can't be replaced with an instant app
16804                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16805                        "Cannot update a system app with an instant app");
16806                return;
16807            }
16808        }
16809
16810        if (args.move != null) {
16811            // We did an in-place move, so dex is ready to roll
16812            scanFlags |= SCAN_NO_DEX;
16813            scanFlags |= SCAN_MOVE;
16814
16815            synchronized (mPackages) {
16816                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16817                if (ps == null) {
16818                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16819                            "Missing settings for moved package " + pkgName);
16820                }
16821
16822                // We moved the entire application as-is, so bring over the
16823                // previously derived ABI information.
16824                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16825                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16826            }
16827
16828        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16829            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16830            scanFlags |= SCAN_NO_DEX;
16831
16832            try {
16833                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16834                    args.abiOverride : pkg.cpuAbiOverride);
16835                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16836                        true /*extractLibs*/, mAppLib32InstallDir);
16837            } catch (PackageManagerException pme) {
16838                Slog.e(TAG, "Error deriving application ABI", pme);
16839                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16840                return;
16841            }
16842
16843            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16844            // Do not run PackageDexOptimizer through the local performDexOpt
16845            // method because `pkg` may not be in `mPackages` yet.
16846            //
16847            // Also, don't fail application installs if the dexopt step fails.
16848            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16849                    null /* instructionSets */, false /* checkProfiles */,
16850                    getCompilerFilterForReason(REASON_INSTALL),
16851                    getOrCreateCompilerPackageStats(pkg),
16852                    mDexManager.isUsedByOtherApps(pkg.packageName));
16853            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16854
16855            // Notify BackgroundDexOptService that the package has been changed.
16856            // If this is an update of a package which used to fail to compile,
16857            // BDOS will remove it from its blacklist.
16858            // TODO: Layering violation
16859            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16860        }
16861
16862        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16863            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16864            return;
16865        }
16866
16867        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16868
16869        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16870                "installPackageLI")) {
16871            if (replace) {
16872                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16873                    // Static libs have a synthetic package name containing the version
16874                    // and cannot be updated as an update would get a new package name,
16875                    // unless this is the exact same version code which is useful for
16876                    // development.
16877                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16878                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16879                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16880                                + "static-shared libs cannot be updated");
16881                        return;
16882                    }
16883                }
16884                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16885                        installerPackageName, res, args.installReason);
16886            } else {
16887                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16888                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16889            }
16890        }
16891        synchronized (mPackages) {
16892            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16893            if (ps != null) {
16894                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16895                ps.setUpdateAvailable(false /*updateAvailable*/);
16896            }
16897
16898            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16899            for (int i = 0; i < childCount; i++) {
16900                PackageParser.Package childPkg = pkg.childPackages.get(i);
16901                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16902                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16903                if (childPs != null) {
16904                    childRes.newUsers = childPs.queryInstalledUsers(
16905                            sUserManager.getUserIds(), true);
16906                }
16907            }
16908
16909            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16910                updateSequenceNumberLP(pkgName, res.newUsers);
16911            }
16912        }
16913    }
16914
16915    private void startIntentFilterVerifications(int userId, boolean replacing,
16916            PackageParser.Package pkg) {
16917        if (mIntentFilterVerifierComponent == null) {
16918            Slog.w(TAG, "No IntentFilter verification will not be done as "
16919                    + "there is no IntentFilterVerifier available!");
16920            return;
16921        }
16922
16923        final int verifierUid = getPackageUid(
16924                mIntentFilterVerifierComponent.getPackageName(),
16925                MATCH_DEBUG_TRIAGED_MISSING,
16926                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16927
16928        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16929        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16930        mHandler.sendMessage(msg);
16931
16932        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16933        for (int i = 0; i < childCount; i++) {
16934            PackageParser.Package childPkg = pkg.childPackages.get(i);
16935            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16936            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16937            mHandler.sendMessage(msg);
16938        }
16939    }
16940
16941    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16942            PackageParser.Package pkg) {
16943        int size = pkg.activities.size();
16944        if (size == 0) {
16945            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16946                    "No activity, so no need to verify any IntentFilter!");
16947            return;
16948        }
16949
16950        final boolean hasDomainURLs = hasDomainURLs(pkg);
16951        if (!hasDomainURLs) {
16952            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16953                    "No domain URLs, so no need to verify any IntentFilter!");
16954            return;
16955        }
16956
16957        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16958                + " if any IntentFilter from the " + size
16959                + " Activities needs verification ...");
16960
16961        int count = 0;
16962        final String packageName = pkg.packageName;
16963
16964        synchronized (mPackages) {
16965            // If this is a new install and we see that we've already run verification for this
16966            // package, we have nothing to do: it means the state was restored from backup.
16967            if (!replacing) {
16968                IntentFilterVerificationInfo ivi =
16969                        mSettings.getIntentFilterVerificationLPr(packageName);
16970                if (ivi != null) {
16971                    if (DEBUG_DOMAIN_VERIFICATION) {
16972                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16973                                + ivi.getStatusString());
16974                    }
16975                    return;
16976                }
16977            }
16978
16979            // If any filters need to be verified, then all need to be.
16980            boolean needToVerify = false;
16981            for (PackageParser.Activity a : pkg.activities) {
16982                for (ActivityIntentInfo filter : a.intents) {
16983                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16984                        if (DEBUG_DOMAIN_VERIFICATION) {
16985                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16986                        }
16987                        needToVerify = true;
16988                        break;
16989                    }
16990                }
16991            }
16992
16993            if (needToVerify) {
16994                final int verificationId = mIntentFilterVerificationToken++;
16995                for (PackageParser.Activity a : pkg.activities) {
16996                    for (ActivityIntentInfo filter : a.intents) {
16997                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16998                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16999                                    "Verification needed for IntentFilter:" + filter.toString());
17000                            mIntentFilterVerifier.addOneIntentFilterVerification(
17001                                    verifierUid, userId, verificationId, filter, packageName);
17002                            count++;
17003                        }
17004                    }
17005                }
17006            }
17007        }
17008
17009        if (count > 0) {
17010            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17011                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17012                    +  " for userId:" + userId);
17013            mIntentFilterVerifier.startVerifications(userId);
17014        } else {
17015            if (DEBUG_DOMAIN_VERIFICATION) {
17016                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17017            }
17018        }
17019    }
17020
17021    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17022        final ComponentName cn  = filter.activity.getComponentName();
17023        final String packageName = cn.getPackageName();
17024
17025        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17026                packageName);
17027        if (ivi == null) {
17028            return true;
17029        }
17030        int status = ivi.getStatus();
17031        switch (status) {
17032            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17033            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17034                return true;
17035
17036            default:
17037                // Nothing to do
17038                return false;
17039        }
17040    }
17041
17042    private static boolean isMultiArch(ApplicationInfo info) {
17043        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17044    }
17045
17046    private static boolean isExternal(PackageParser.Package pkg) {
17047        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17048    }
17049
17050    private static boolean isExternal(PackageSetting ps) {
17051        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17052    }
17053
17054    private static boolean isSystemApp(PackageParser.Package pkg) {
17055        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17056    }
17057
17058    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17059        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17060    }
17061
17062    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17063        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17064    }
17065
17066    private static boolean isSystemApp(PackageSetting ps) {
17067        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17068    }
17069
17070    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17071        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17072    }
17073
17074    private int packageFlagsToInstallFlags(PackageSetting ps) {
17075        int installFlags = 0;
17076        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17077            // This existing package was an external ASEC install when we have
17078            // the external flag without a UUID
17079            installFlags |= PackageManager.INSTALL_EXTERNAL;
17080        }
17081        if (ps.isForwardLocked()) {
17082            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17083        }
17084        return installFlags;
17085    }
17086
17087    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17088        if (isExternal(pkg)) {
17089            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17090                return StorageManager.UUID_PRIMARY_PHYSICAL;
17091            } else {
17092                return pkg.volumeUuid;
17093            }
17094        } else {
17095            return StorageManager.UUID_PRIVATE_INTERNAL;
17096        }
17097    }
17098
17099    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17100        if (isExternal(pkg)) {
17101            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17102                return mSettings.getExternalVersion();
17103            } else {
17104                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17105            }
17106        } else {
17107            return mSettings.getInternalVersion();
17108        }
17109    }
17110
17111    private void deleteTempPackageFiles() {
17112        final FilenameFilter filter = new FilenameFilter() {
17113            public boolean accept(File dir, String name) {
17114                return name.startsWith("vmdl") && name.endsWith(".tmp");
17115            }
17116        };
17117        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17118            file.delete();
17119        }
17120    }
17121
17122    @Override
17123    public void deletePackageAsUser(String packageName, int versionCode,
17124            IPackageDeleteObserver observer, int userId, int flags) {
17125        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17126                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17127    }
17128
17129    @Override
17130    public void deletePackageVersioned(VersionedPackage versionedPackage,
17131            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17132        mContext.enforceCallingOrSelfPermission(
17133                android.Manifest.permission.DELETE_PACKAGES, null);
17134        Preconditions.checkNotNull(versionedPackage);
17135        Preconditions.checkNotNull(observer);
17136        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17137                PackageManager.VERSION_CODE_HIGHEST,
17138                Integer.MAX_VALUE, "versionCode must be >= -1");
17139
17140        final String packageName = versionedPackage.getPackageName();
17141        // TODO: We will change version code to long, so in the new API it is long
17142        final int versionCode = (int) versionedPackage.getVersionCode();
17143        final String internalPackageName;
17144        synchronized (mPackages) {
17145            // Normalize package name to handle renamed packages and static libs
17146            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17147                    // TODO: We will change version code to long, so in the new API it is long
17148                    (int) versionedPackage.getVersionCode());
17149        }
17150
17151        final int uid = Binder.getCallingUid();
17152        if (!isOrphaned(internalPackageName)
17153                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17154            try {
17155                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17156                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17157                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17158                observer.onUserActionRequired(intent);
17159            } catch (RemoteException re) {
17160            }
17161            return;
17162        }
17163        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17164        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17165        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17166            mContext.enforceCallingOrSelfPermission(
17167                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17168                    "deletePackage for user " + userId);
17169        }
17170
17171        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17172            try {
17173                observer.onPackageDeleted(packageName,
17174                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17175            } catch (RemoteException re) {
17176            }
17177            return;
17178        }
17179
17180        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17181            try {
17182                observer.onPackageDeleted(packageName,
17183                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17184            } catch (RemoteException re) {
17185            }
17186            return;
17187        }
17188
17189        if (DEBUG_REMOVE) {
17190            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17191                    + " deleteAllUsers: " + deleteAllUsers + " version="
17192                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17193                    ? "VERSION_CODE_HIGHEST" : versionCode));
17194        }
17195        // Queue up an async operation since the package deletion may take a little while.
17196        mHandler.post(new Runnable() {
17197            public void run() {
17198                mHandler.removeCallbacks(this);
17199                int returnCode;
17200                if (!deleteAllUsers) {
17201                    returnCode = deletePackageX(internalPackageName, versionCode,
17202                            userId, deleteFlags);
17203                } else {
17204                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17205                            internalPackageName, users);
17206                    // If nobody is blocking uninstall, proceed with delete for all users
17207                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17208                        returnCode = deletePackageX(internalPackageName, versionCode,
17209                                userId, deleteFlags);
17210                    } else {
17211                        // Otherwise uninstall individually for users with blockUninstalls=false
17212                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17213                        for (int userId : users) {
17214                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17215                                returnCode = deletePackageX(internalPackageName, versionCode,
17216                                        userId, userFlags);
17217                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17218                                    Slog.w(TAG, "Package delete failed for user " + userId
17219                                            + ", returnCode " + returnCode);
17220                                }
17221                            }
17222                        }
17223                        // The app has only been marked uninstalled for certain users.
17224                        // We still need to report that delete was blocked
17225                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17226                    }
17227                }
17228                try {
17229                    observer.onPackageDeleted(packageName, returnCode, null);
17230                } catch (RemoteException e) {
17231                    Log.i(TAG, "Observer no longer exists.");
17232                } //end catch
17233            } //end run
17234        });
17235    }
17236
17237    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17238        if (pkg.staticSharedLibName != null) {
17239            return pkg.manifestPackageName;
17240        }
17241        return pkg.packageName;
17242    }
17243
17244    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17245        // Handle renamed packages
17246        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17247        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17248
17249        // Is this a static library?
17250        SparseArray<SharedLibraryEntry> versionedLib =
17251                mStaticLibsByDeclaringPackage.get(packageName);
17252        if (versionedLib == null || versionedLib.size() <= 0) {
17253            return packageName;
17254        }
17255
17256        // Figure out which lib versions the caller can see
17257        SparseIntArray versionsCallerCanSee = null;
17258        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17259        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17260                && callingAppId != Process.ROOT_UID) {
17261            versionsCallerCanSee = new SparseIntArray();
17262            String libName = versionedLib.valueAt(0).info.getName();
17263            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17264            if (uidPackages != null) {
17265                for (String uidPackage : uidPackages) {
17266                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17267                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17268                    if (libIdx >= 0) {
17269                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17270                        versionsCallerCanSee.append(libVersion, libVersion);
17271                    }
17272                }
17273            }
17274        }
17275
17276        // Caller can see nothing - done
17277        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17278            return packageName;
17279        }
17280
17281        // Find the version the caller can see and the app version code
17282        SharedLibraryEntry highestVersion = null;
17283        final int versionCount = versionedLib.size();
17284        for (int i = 0; i < versionCount; i++) {
17285            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17286            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17287                    libEntry.info.getVersion()) < 0) {
17288                continue;
17289            }
17290            // TODO: We will change version code to long, so in the new API it is long
17291            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17292            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17293                if (libVersionCode == versionCode) {
17294                    return libEntry.apk;
17295                }
17296            } else if (highestVersion == null) {
17297                highestVersion = libEntry;
17298            } else if (libVersionCode  > highestVersion.info
17299                    .getDeclaringPackage().getVersionCode()) {
17300                highestVersion = libEntry;
17301            }
17302        }
17303
17304        if (highestVersion != null) {
17305            return highestVersion.apk;
17306        }
17307
17308        return packageName;
17309    }
17310
17311    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17312        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17313              || callingUid == Process.SYSTEM_UID) {
17314            return true;
17315        }
17316        final int callingUserId = UserHandle.getUserId(callingUid);
17317        // If the caller installed the pkgName, then allow it to silently uninstall.
17318        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17319            return true;
17320        }
17321
17322        // Allow package verifier to silently uninstall.
17323        if (mRequiredVerifierPackage != null &&
17324                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17325            return true;
17326        }
17327
17328        // Allow package uninstaller to silently uninstall.
17329        if (mRequiredUninstallerPackage != null &&
17330                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17331            return true;
17332        }
17333
17334        // Allow storage manager to silently uninstall.
17335        if (mStorageManagerPackage != null &&
17336                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17337            return true;
17338        }
17339        return false;
17340    }
17341
17342    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17343        int[] result = EMPTY_INT_ARRAY;
17344        for (int userId : userIds) {
17345            if (getBlockUninstallForUser(packageName, userId)) {
17346                result = ArrayUtils.appendInt(result, userId);
17347            }
17348        }
17349        return result;
17350    }
17351
17352    @Override
17353    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17354        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17355    }
17356
17357    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17358        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17359                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17360        try {
17361            if (dpm != null) {
17362                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17363                        /* callingUserOnly =*/ false);
17364                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17365                        : deviceOwnerComponentName.getPackageName();
17366                // Does the package contains the device owner?
17367                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17368                // this check is probably not needed, since DO should be registered as a device
17369                // admin on some user too. (Original bug for this: b/17657954)
17370                if (packageName.equals(deviceOwnerPackageName)) {
17371                    return true;
17372                }
17373                // Does it contain a device admin for any user?
17374                int[] users;
17375                if (userId == UserHandle.USER_ALL) {
17376                    users = sUserManager.getUserIds();
17377                } else {
17378                    users = new int[]{userId};
17379                }
17380                for (int i = 0; i < users.length; ++i) {
17381                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17382                        return true;
17383                    }
17384                }
17385            }
17386        } catch (RemoteException e) {
17387        }
17388        return false;
17389    }
17390
17391    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17392        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17393    }
17394
17395    /**
17396     *  This method is an internal method that could be get invoked either
17397     *  to delete an installed package or to clean up a failed installation.
17398     *  After deleting an installed package, a broadcast is sent to notify any
17399     *  listeners that the package has been removed. For cleaning up a failed
17400     *  installation, the broadcast is not necessary since the package's
17401     *  installation wouldn't have sent the initial broadcast either
17402     *  The key steps in deleting a package are
17403     *  deleting the package information in internal structures like mPackages,
17404     *  deleting the packages base directories through installd
17405     *  updating mSettings to reflect current status
17406     *  persisting settings for later use
17407     *  sending a broadcast if necessary
17408     */
17409    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17410        final PackageRemovedInfo info = new PackageRemovedInfo();
17411        final boolean res;
17412
17413        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17414                ? UserHandle.USER_ALL : userId;
17415
17416        if (isPackageDeviceAdmin(packageName, removeUser)) {
17417            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17418            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17419        }
17420
17421        PackageSetting uninstalledPs = null;
17422        PackageParser.Package pkg = null;
17423
17424        // for the uninstall-updates case and restricted profiles, remember the per-
17425        // user handle installed state
17426        int[] allUsers;
17427        synchronized (mPackages) {
17428            uninstalledPs = mSettings.mPackages.get(packageName);
17429            if (uninstalledPs == null) {
17430                Slog.w(TAG, "Not removing non-existent package " + packageName);
17431                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17432            }
17433
17434            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17435                    && uninstalledPs.versionCode != versionCode) {
17436                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17437                        + uninstalledPs.versionCode + " != " + versionCode);
17438                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17439            }
17440
17441            // Static shared libs can be declared by any package, so let us not
17442            // allow removing a package if it provides a lib others depend on.
17443            pkg = mPackages.get(packageName);
17444            if (pkg != null && pkg.staticSharedLibName != null) {
17445                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17446                        pkg.staticSharedLibVersion);
17447                if (libEntry != null) {
17448                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17449                            libEntry.info, 0, userId);
17450                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17451                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17452                                + " hosting lib " + libEntry.info.getName() + " version "
17453                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17454                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17455                    }
17456                }
17457            }
17458
17459            allUsers = sUserManager.getUserIds();
17460            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17461        }
17462
17463        final int freezeUser;
17464        if (isUpdatedSystemApp(uninstalledPs)
17465                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17466            // We're downgrading a system app, which will apply to all users, so
17467            // freeze them all during the downgrade
17468            freezeUser = UserHandle.USER_ALL;
17469        } else {
17470            freezeUser = removeUser;
17471        }
17472
17473        synchronized (mInstallLock) {
17474            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17475            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17476                    deleteFlags, "deletePackageX")) {
17477                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17478                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17479            }
17480            synchronized (mPackages) {
17481                if (res) {
17482                    if (pkg != null) {
17483                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17484                    }
17485                    updateSequenceNumberLP(packageName, info.removedUsers);
17486                }
17487            }
17488        }
17489
17490        if (res) {
17491            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17492            info.sendPackageRemovedBroadcasts(killApp);
17493            info.sendSystemPackageUpdatedBroadcasts();
17494            info.sendSystemPackageAppearedBroadcasts();
17495        }
17496        // Force a gc here.
17497        Runtime.getRuntime().gc();
17498        // Delete the resources here after sending the broadcast to let
17499        // other processes clean up before deleting resources.
17500        if (info.args != null) {
17501            synchronized (mInstallLock) {
17502                info.args.doPostDeleteLI(true);
17503            }
17504        }
17505
17506        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17507    }
17508
17509    class PackageRemovedInfo {
17510        String removedPackage;
17511        int uid = -1;
17512        int removedAppId = -1;
17513        int[] origUsers;
17514        int[] removedUsers = null;
17515        SparseArray<Integer> installReasons;
17516        boolean isRemovedPackageSystemUpdate = false;
17517        boolean isUpdate;
17518        boolean dataRemoved;
17519        boolean removedForAllUsers;
17520        boolean isStaticSharedLib;
17521        // Clean up resources deleted packages.
17522        InstallArgs args = null;
17523        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17524        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17525
17526        void sendPackageRemovedBroadcasts(boolean killApp) {
17527            sendPackageRemovedBroadcastInternal(killApp);
17528            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17529            for (int i = 0; i < childCount; i++) {
17530                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17531                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17532            }
17533        }
17534
17535        void sendSystemPackageUpdatedBroadcasts() {
17536            if (isRemovedPackageSystemUpdate) {
17537                sendSystemPackageUpdatedBroadcastsInternal();
17538                final int childCount = (removedChildPackages != null)
17539                        ? removedChildPackages.size() : 0;
17540                for (int i = 0; i < childCount; i++) {
17541                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17542                    if (childInfo.isRemovedPackageSystemUpdate) {
17543                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17544                    }
17545                }
17546            }
17547        }
17548
17549        void sendSystemPackageAppearedBroadcasts() {
17550            final int packageCount = (appearedChildPackages != null)
17551                    ? appearedChildPackages.size() : 0;
17552            for (int i = 0; i < packageCount; i++) {
17553                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17554                sendPackageAddedForNewUsers(installedInfo.name, true,
17555                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17556            }
17557        }
17558
17559        private void sendSystemPackageUpdatedBroadcastsInternal() {
17560            Bundle extras = new Bundle(2);
17561            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17562            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17563            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17564                    extras, 0, null, null, null);
17565            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17566                    extras, 0, null, null, null);
17567            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17568                    null, 0, removedPackage, null, null);
17569        }
17570
17571        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17572            // Don't send static shared library removal broadcasts as these
17573            // libs are visible only the the apps that depend on them an one
17574            // cannot remove the library if it has a dependency.
17575            if (isStaticSharedLib) {
17576                return;
17577            }
17578            Bundle extras = new Bundle(2);
17579            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17580            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17581            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17582            if (isUpdate || isRemovedPackageSystemUpdate) {
17583                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17584            }
17585            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17586            if (removedPackage != null) {
17587                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17588                        extras, 0, null, null, removedUsers);
17589                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17590                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17591                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17592                            null, null, removedUsers);
17593                }
17594            }
17595            if (removedAppId >= 0) {
17596                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17597                        removedUsers);
17598            }
17599        }
17600    }
17601
17602    /*
17603     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17604     * flag is not set, the data directory is removed as well.
17605     * make sure this flag is set for partially installed apps. If not its meaningless to
17606     * delete a partially installed application.
17607     */
17608    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17609            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17610        String packageName = ps.name;
17611        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17612        // Retrieve object to delete permissions for shared user later on
17613        final PackageParser.Package deletedPkg;
17614        final PackageSetting deletedPs;
17615        // reader
17616        synchronized (mPackages) {
17617            deletedPkg = mPackages.get(packageName);
17618            deletedPs = mSettings.mPackages.get(packageName);
17619            if (outInfo != null) {
17620                outInfo.removedPackage = packageName;
17621                outInfo.isStaticSharedLib = deletedPkg != null
17622                        && deletedPkg.staticSharedLibName != null;
17623                outInfo.removedUsers = deletedPs != null
17624                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17625                        : null;
17626            }
17627        }
17628
17629        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17630
17631        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17632            final PackageParser.Package resolvedPkg;
17633            if (deletedPkg != null) {
17634                resolvedPkg = deletedPkg;
17635            } else {
17636                // We don't have a parsed package when it lives on an ejected
17637                // adopted storage device, so fake something together
17638                resolvedPkg = new PackageParser.Package(ps.name);
17639                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17640            }
17641            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17642                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17643            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17644            if (outInfo != null) {
17645                outInfo.dataRemoved = true;
17646            }
17647            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17648        }
17649
17650        int removedAppId = -1;
17651
17652        // writer
17653        synchronized (mPackages) {
17654            boolean installedStateChanged = false;
17655            if (deletedPs != null) {
17656                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17657                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17658                    clearDefaultBrowserIfNeeded(packageName);
17659                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17660                    removedAppId = mSettings.removePackageLPw(packageName);
17661                    if (outInfo != null) {
17662                        outInfo.removedAppId = removedAppId;
17663                    }
17664                    updatePermissionsLPw(deletedPs.name, null, 0);
17665                    if (deletedPs.sharedUser != null) {
17666                        // Remove permissions associated with package. Since runtime
17667                        // permissions are per user we have to kill the removed package
17668                        // or packages running under the shared user of the removed
17669                        // package if revoking the permissions requested only by the removed
17670                        // package is successful and this causes a change in gids.
17671                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17672                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17673                                    userId);
17674                            if (userIdToKill == UserHandle.USER_ALL
17675                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17676                                // If gids changed for this user, kill all affected packages.
17677                                mHandler.post(new Runnable() {
17678                                    @Override
17679                                    public void run() {
17680                                        // This has to happen with no lock held.
17681                                        killApplication(deletedPs.name, deletedPs.appId,
17682                                                KILL_APP_REASON_GIDS_CHANGED);
17683                                    }
17684                                });
17685                                break;
17686                            }
17687                        }
17688                    }
17689                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17690                }
17691                // make sure to preserve per-user disabled state if this removal was just
17692                // a downgrade of a system app to the factory package
17693                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17694                    if (DEBUG_REMOVE) {
17695                        Slog.d(TAG, "Propagating install state across downgrade");
17696                    }
17697                    for (int userId : allUserHandles) {
17698                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17699                        if (DEBUG_REMOVE) {
17700                            Slog.d(TAG, "    user " + userId + " => " + installed);
17701                        }
17702                        if (installed != ps.getInstalled(userId)) {
17703                            installedStateChanged = true;
17704                        }
17705                        ps.setInstalled(installed, userId);
17706                    }
17707                }
17708            }
17709            // can downgrade to reader
17710            if (writeSettings) {
17711                // Save settings now
17712                mSettings.writeLPr();
17713            }
17714            if (installedStateChanged) {
17715                mSettings.writeKernelMappingLPr(ps);
17716            }
17717        }
17718        if (removedAppId != -1) {
17719            // A user ID was deleted here. Go through all users and remove it
17720            // from KeyStore.
17721            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17722        }
17723    }
17724
17725    static boolean locationIsPrivileged(File path) {
17726        try {
17727            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17728                    .getCanonicalPath();
17729            return path.getCanonicalPath().startsWith(privilegedAppDir);
17730        } catch (IOException e) {
17731            Slog.e(TAG, "Unable to access code path " + path);
17732        }
17733        return false;
17734    }
17735
17736    /*
17737     * Tries to delete system package.
17738     */
17739    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17740            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17741            boolean writeSettings) {
17742        if (deletedPs.parentPackageName != null) {
17743            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17744            return false;
17745        }
17746
17747        final boolean applyUserRestrictions
17748                = (allUserHandles != null) && (outInfo.origUsers != null);
17749        final PackageSetting disabledPs;
17750        // Confirm if the system package has been updated
17751        // An updated system app can be deleted. This will also have to restore
17752        // the system pkg from system partition
17753        // reader
17754        synchronized (mPackages) {
17755            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17756        }
17757
17758        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17759                + " disabledPs=" + disabledPs);
17760
17761        if (disabledPs == null) {
17762            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17763            return false;
17764        } else if (DEBUG_REMOVE) {
17765            Slog.d(TAG, "Deleting system pkg from data partition");
17766        }
17767
17768        if (DEBUG_REMOVE) {
17769            if (applyUserRestrictions) {
17770                Slog.d(TAG, "Remembering install states:");
17771                for (int userId : allUserHandles) {
17772                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17773                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17774                }
17775            }
17776        }
17777
17778        // Delete the updated package
17779        outInfo.isRemovedPackageSystemUpdate = true;
17780        if (outInfo.removedChildPackages != null) {
17781            final int childCount = (deletedPs.childPackageNames != null)
17782                    ? deletedPs.childPackageNames.size() : 0;
17783            for (int i = 0; i < childCount; i++) {
17784                String childPackageName = deletedPs.childPackageNames.get(i);
17785                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17786                        .contains(childPackageName)) {
17787                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17788                            childPackageName);
17789                    if (childInfo != null) {
17790                        childInfo.isRemovedPackageSystemUpdate = true;
17791                    }
17792                }
17793            }
17794        }
17795
17796        if (disabledPs.versionCode < deletedPs.versionCode) {
17797            // Delete data for downgrades
17798            flags &= ~PackageManager.DELETE_KEEP_DATA;
17799        } else {
17800            // Preserve data by setting flag
17801            flags |= PackageManager.DELETE_KEEP_DATA;
17802        }
17803
17804        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17805                outInfo, writeSettings, disabledPs.pkg);
17806        if (!ret) {
17807            return false;
17808        }
17809
17810        // writer
17811        synchronized (mPackages) {
17812            // Reinstate the old system package
17813            enableSystemPackageLPw(disabledPs.pkg);
17814            // Remove any native libraries from the upgraded package.
17815            removeNativeBinariesLI(deletedPs);
17816        }
17817
17818        // Install the system package
17819        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17820        int parseFlags = mDefParseFlags
17821                | PackageParser.PARSE_MUST_BE_APK
17822                | PackageParser.PARSE_IS_SYSTEM
17823                | PackageParser.PARSE_IS_SYSTEM_DIR;
17824        if (locationIsPrivileged(disabledPs.codePath)) {
17825            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17826        }
17827
17828        final PackageParser.Package newPkg;
17829        try {
17830            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17831                0 /* currentTime */, null);
17832        } catch (PackageManagerException e) {
17833            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17834                    + e.getMessage());
17835            return false;
17836        }
17837
17838        try {
17839            // update shared libraries for the newly re-installed system package
17840            updateSharedLibrariesLPr(newPkg, null);
17841        } catch (PackageManagerException e) {
17842            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17843        }
17844
17845        prepareAppDataAfterInstallLIF(newPkg);
17846
17847        // writer
17848        synchronized (mPackages) {
17849            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17850
17851            // Propagate the permissions state as we do not want to drop on the floor
17852            // runtime permissions. The update permissions method below will take
17853            // care of removing obsolete permissions and grant install permissions.
17854            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17855            updatePermissionsLPw(newPkg.packageName, newPkg,
17856                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17857
17858            if (applyUserRestrictions) {
17859                boolean installedStateChanged = false;
17860                if (DEBUG_REMOVE) {
17861                    Slog.d(TAG, "Propagating install state across reinstall");
17862                }
17863                for (int userId : allUserHandles) {
17864                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17865                    if (DEBUG_REMOVE) {
17866                        Slog.d(TAG, "    user " + userId + " => " + installed);
17867                    }
17868                    if (installed != ps.getInstalled(userId)) {
17869                        installedStateChanged = true;
17870                    }
17871                    ps.setInstalled(installed, userId);
17872
17873                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17874                }
17875                // Regardless of writeSettings we need to ensure that this restriction
17876                // state propagation is persisted
17877                mSettings.writeAllUsersPackageRestrictionsLPr();
17878                if (installedStateChanged) {
17879                    mSettings.writeKernelMappingLPr(ps);
17880                }
17881            }
17882            // can downgrade to reader here
17883            if (writeSettings) {
17884                mSettings.writeLPr();
17885            }
17886        }
17887        return true;
17888    }
17889
17890    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17891            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17892            PackageRemovedInfo outInfo, boolean writeSettings,
17893            PackageParser.Package replacingPackage) {
17894        synchronized (mPackages) {
17895            if (outInfo != null) {
17896                outInfo.uid = ps.appId;
17897            }
17898
17899            if (outInfo != null && outInfo.removedChildPackages != null) {
17900                final int childCount = (ps.childPackageNames != null)
17901                        ? ps.childPackageNames.size() : 0;
17902                for (int i = 0; i < childCount; i++) {
17903                    String childPackageName = ps.childPackageNames.get(i);
17904                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17905                    if (childPs == null) {
17906                        return false;
17907                    }
17908                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17909                            childPackageName);
17910                    if (childInfo != null) {
17911                        childInfo.uid = childPs.appId;
17912                    }
17913                }
17914            }
17915        }
17916
17917        // Delete package data from internal structures and also remove data if flag is set
17918        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17919
17920        // Delete the child packages data
17921        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17922        for (int i = 0; i < childCount; i++) {
17923            PackageSetting childPs;
17924            synchronized (mPackages) {
17925                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17926            }
17927            if (childPs != null) {
17928                PackageRemovedInfo childOutInfo = (outInfo != null
17929                        && outInfo.removedChildPackages != null)
17930                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17931                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17932                        && (replacingPackage != null
17933                        && !replacingPackage.hasChildPackage(childPs.name))
17934                        ? flags & ~DELETE_KEEP_DATA : flags;
17935                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17936                        deleteFlags, writeSettings);
17937            }
17938        }
17939
17940        // Delete application code and resources only for parent packages
17941        if (ps.parentPackageName == null) {
17942            if (deleteCodeAndResources && (outInfo != null)) {
17943                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17944                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17945                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17946            }
17947        }
17948
17949        return true;
17950    }
17951
17952    @Override
17953    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17954            int userId) {
17955        mContext.enforceCallingOrSelfPermission(
17956                android.Manifest.permission.DELETE_PACKAGES, null);
17957        synchronized (mPackages) {
17958            PackageSetting ps = mSettings.mPackages.get(packageName);
17959            if (ps == null) {
17960                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17961                return false;
17962            }
17963            // Cannot block uninstall of static shared libs as they are
17964            // considered a part of the using app (emulating static linking).
17965            // Also static libs are installed always on internal storage.
17966            PackageParser.Package pkg = mPackages.get(packageName);
17967            if (pkg != null && pkg.staticSharedLibName != null) {
17968                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17969                        + " providing static shared library: " + pkg.staticSharedLibName);
17970                return false;
17971            }
17972            if (!ps.getInstalled(userId)) {
17973                // Can't block uninstall for an app that is not installed or enabled.
17974                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17975                return false;
17976            }
17977            ps.setBlockUninstall(blockUninstall, userId);
17978            mSettings.writePackageRestrictionsLPr(userId);
17979        }
17980        return true;
17981    }
17982
17983    @Override
17984    public boolean getBlockUninstallForUser(String packageName, int userId) {
17985        synchronized (mPackages) {
17986            PackageSetting ps = mSettings.mPackages.get(packageName);
17987            if (ps == null) {
17988                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17989                return false;
17990            }
17991            return ps.getBlockUninstall(userId);
17992        }
17993    }
17994
17995    @Override
17996    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17997        int callingUid = Binder.getCallingUid();
17998        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17999            throw new SecurityException(
18000                    "setRequiredForSystemUser can only be run by the system or root");
18001        }
18002        synchronized (mPackages) {
18003            PackageSetting ps = mSettings.mPackages.get(packageName);
18004            if (ps == null) {
18005                Log.w(TAG, "Package doesn't exist: " + packageName);
18006                return false;
18007            }
18008            if (systemUserApp) {
18009                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18010            } else {
18011                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18012            }
18013            mSettings.writeLPr();
18014        }
18015        return true;
18016    }
18017
18018    /*
18019     * This method handles package deletion in general
18020     */
18021    private boolean deletePackageLIF(String packageName, UserHandle user,
18022            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18023            PackageRemovedInfo outInfo, boolean writeSettings,
18024            PackageParser.Package replacingPackage) {
18025        if (packageName == null) {
18026            Slog.w(TAG, "Attempt to delete null packageName.");
18027            return false;
18028        }
18029
18030        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18031
18032        PackageSetting ps;
18033        synchronized (mPackages) {
18034            ps = mSettings.mPackages.get(packageName);
18035            if (ps == null) {
18036                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18037                return false;
18038            }
18039
18040            if (ps.parentPackageName != null && (!isSystemApp(ps)
18041                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18042                if (DEBUG_REMOVE) {
18043                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18044                            + ((user == null) ? UserHandle.USER_ALL : user));
18045                }
18046                final int removedUserId = (user != null) ? user.getIdentifier()
18047                        : UserHandle.USER_ALL;
18048                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18049                    return false;
18050                }
18051                markPackageUninstalledForUserLPw(ps, user);
18052                scheduleWritePackageRestrictionsLocked(user);
18053                return true;
18054            }
18055        }
18056
18057        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18058                && user.getIdentifier() != UserHandle.USER_ALL)) {
18059            // The caller is asking that the package only be deleted for a single
18060            // user.  To do this, we just mark its uninstalled state and delete
18061            // its data. If this is a system app, we only allow this to happen if
18062            // they have set the special DELETE_SYSTEM_APP which requests different
18063            // semantics than normal for uninstalling system apps.
18064            markPackageUninstalledForUserLPw(ps, user);
18065
18066            if (!isSystemApp(ps)) {
18067                // Do not uninstall the APK if an app should be cached
18068                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18069                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18070                    // Other user still have this package installed, so all
18071                    // we need to do is clear this user's data and save that
18072                    // it is uninstalled.
18073                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18074                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18075                        return false;
18076                    }
18077                    scheduleWritePackageRestrictionsLocked(user);
18078                    return true;
18079                } else {
18080                    // We need to set it back to 'installed' so the uninstall
18081                    // broadcasts will be sent correctly.
18082                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18083                    ps.setInstalled(true, user.getIdentifier());
18084                    mSettings.writeKernelMappingLPr(ps);
18085                }
18086            } else {
18087                // This is a system app, so we assume that the
18088                // other users still have this package installed, so all
18089                // we need to do is clear this user's data and save that
18090                // it is uninstalled.
18091                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18092                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18093                    return false;
18094                }
18095                scheduleWritePackageRestrictionsLocked(user);
18096                return true;
18097            }
18098        }
18099
18100        // If we are deleting a composite package for all users, keep track
18101        // of result for each child.
18102        if (ps.childPackageNames != null && outInfo != null) {
18103            synchronized (mPackages) {
18104                final int childCount = ps.childPackageNames.size();
18105                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18106                for (int i = 0; i < childCount; i++) {
18107                    String childPackageName = ps.childPackageNames.get(i);
18108                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18109                    childInfo.removedPackage = childPackageName;
18110                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18111                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18112                    if (childPs != null) {
18113                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18114                    }
18115                }
18116            }
18117        }
18118
18119        boolean ret = false;
18120        if (isSystemApp(ps)) {
18121            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18122            // When an updated system application is deleted we delete the existing resources
18123            // as well and fall back to existing code in system partition
18124            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18125        } else {
18126            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18127            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18128                    outInfo, writeSettings, replacingPackage);
18129        }
18130
18131        // Take a note whether we deleted the package for all users
18132        if (outInfo != null) {
18133            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18134            if (outInfo.removedChildPackages != null) {
18135                synchronized (mPackages) {
18136                    final int childCount = outInfo.removedChildPackages.size();
18137                    for (int i = 0; i < childCount; i++) {
18138                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18139                        if (childInfo != null) {
18140                            childInfo.removedForAllUsers = mPackages.get(
18141                                    childInfo.removedPackage) == null;
18142                        }
18143                    }
18144                }
18145            }
18146            // If we uninstalled an update to a system app there may be some
18147            // child packages that appeared as they are declared in the system
18148            // app but were not declared in the update.
18149            if (isSystemApp(ps)) {
18150                synchronized (mPackages) {
18151                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18152                    final int childCount = (updatedPs.childPackageNames != null)
18153                            ? updatedPs.childPackageNames.size() : 0;
18154                    for (int i = 0; i < childCount; i++) {
18155                        String childPackageName = updatedPs.childPackageNames.get(i);
18156                        if (outInfo.removedChildPackages == null
18157                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18158                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18159                            if (childPs == null) {
18160                                continue;
18161                            }
18162                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18163                            installRes.name = childPackageName;
18164                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18165                            installRes.pkg = mPackages.get(childPackageName);
18166                            installRes.uid = childPs.pkg.applicationInfo.uid;
18167                            if (outInfo.appearedChildPackages == null) {
18168                                outInfo.appearedChildPackages = new ArrayMap<>();
18169                            }
18170                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18171                        }
18172                    }
18173                }
18174            }
18175        }
18176
18177        return ret;
18178    }
18179
18180    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18181        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18182                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18183        for (int nextUserId : userIds) {
18184            if (DEBUG_REMOVE) {
18185                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18186            }
18187            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18188                    false /*installed*/,
18189                    true /*stopped*/,
18190                    true /*notLaunched*/,
18191                    false /*hidden*/,
18192                    false /*suspended*/,
18193                    false /*instantApp*/,
18194                    null /*lastDisableAppCaller*/,
18195                    null /*enabledComponents*/,
18196                    null /*disabledComponents*/,
18197                    false /*blockUninstall*/,
18198                    ps.readUserState(nextUserId).domainVerificationStatus,
18199                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18200        }
18201        mSettings.writeKernelMappingLPr(ps);
18202    }
18203
18204    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18205            PackageRemovedInfo outInfo) {
18206        final PackageParser.Package pkg;
18207        synchronized (mPackages) {
18208            pkg = mPackages.get(ps.name);
18209        }
18210
18211        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18212                : new int[] {userId};
18213        for (int nextUserId : userIds) {
18214            if (DEBUG_REMOVE) {
18215                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18216                        + nextUserId);
18217            }
18218
18219            destroyAppDataLIF(pkg, userId,
18220                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18221            destroyAppProfilesLIF(pkg, userId);
18222            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18223            schedulePackageCleaning(ps.name, nextUserId, false);
18224            synchronized (mPackages) {
18225                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18226                    scheduleWritePackageRestrictionsLocked(nextUserId);
18227                }
18228                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18229            }
18230        }
18231
18232        if (outInfo != null) {
18233            outInfo.removedPackage = ps.name;
18234            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18235            outInfo.removedAppId = ps.appId;
18236            outInfo.removedUsers = userIds;
18237        }
18238
18239        return true;
18240    }
18241
18242    private final class ClearStorageConnection implements ServiceConnection {
18243        IMediaContainerService mContainerService;
18244
18245        @Override
18246        public void onServiceConnected(ComponentName name, IBinder service) {
18247            synchronized (this) {
18248                mContainerService = IMediaContainerService.Stub
18249                        .asInterface(Binder.allowBlocking(service));
18250                notifyAll();
18251            }
18252        }
18253
18254        @Override
18255        public void onServiceDisconnected(ComponentName name) {
18256        }
18257    }
18258
18259    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18260        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18261
18262        final boolean mounted;
18263        if (Environment.isExternalStorageEmulated()) {
18264            mounted = true;
18265        } else {
18266            final String status = Environment.getExternalStorageState();
18267
18268            mounted = status.equals(Environment.MEDIA_MOUNTED)
18269                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18270        }
18271
18272        if (!mounted) {
18273            return;
18274        }
18275
18276        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18277        int[] users;
18278        if (userId == UserHandle.USER_ALL) {
18279            users = sUserManager.getUserIds();
18280        } else {
18281            users = new int[] { userId };
18282        }
18283        final ClearStorageConnection conn = new ClearStorageConnection();
18284        if (mContext.bindServiceAsUser(
18285                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18286            try {
18287                for (int curUser : users) {
18288                    long timeout = SystemClock.uptimeMillis() + 5000;
18289                    synchronized (conn) {
18290                        long now;
18291                        while (conn.mContainerService == null &&
18292                                (now = SystemClock.uptimeMillis()) < timeout) {
18293                            try {
18294                                conn.wait(timeout - now);
18295                            } catch (InterruptedException e) {
18296                            }
18297                        }
18298                    }
18299                    if (conn.mContainerService == null) {
18300                        return;
18301                    }
18302
18303                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18304                    clearDirectory(conn.mContainerService,
18305                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18306                    if (allData) {
18307                        clearDirectory(conn.mContainerService,
18308                                userEnv.buildExternalStorageAppDataDirs(packageName));
18309                        clearDirectory(conn.mContainerService,
18310                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18311                    }
18312                }
18313            } finally {
18314                mContext.unbindService(conn);
18315            }
18316        }
18317    }
18318
18319    @Override
18320    public void clearApplicationProfileData(String packageName) {
18321        enforceSystemOrRoot("Only the system can clear all profile data");
18322
18323        final PackageParser.Package pkg;
18324        synchronized (mPackages) {
18325            pkg = mPackages.get(packageName);
18326        }
18327
18328        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18329            synchronized (mInstallLock) {
18330                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18331            }
18332        }
18333    }
18334
18335    @Override
18336    public void clearApplicationUserData(final String packageName,
18337            final IPackageDataObserver observer, final int userId) {
18338        mContext.enforceCallingOrSelfPermission(
18339                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18340
18341        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18342                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18343
18344        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18345            throw new SecurityException("Cannot clear data for a protected package: "
18346                    + packageName);
18347        }
18348        // Queue up an async operation since the package deletion may take a little while.
18349        mHandler.post(new Runnable() {
18350            public void run() {
18351                mHandler.removeCallbacks(this);
18352                final boolean succeeded;
18353                try (PackageFreezer freezer = freezePackage(packageName,
18354                        "clearApplicationUserData")) {
18355                    synchronized (mInstallLock) {
18356                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18357                    }
18358                    clearExternalStorageDataSync(packageName, userId, true);
18359                    synchronized (mPackages) {
18360                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18361                                packageName, userId);
18362                    }
18363                }
18364                if (succeeded) {
18365                    // invoke DeviceStorageMonitor's update method to clear any notifications
18366                    DeviceStorageMonitorInternal dsm = LocalServices
18367                            .getService(DeviceStorageMonitorInternal.class);
18368                    if (dsm != null) {
18369                        dsm.checkMemory();
18370                    }
18371                }
18372                if(observer != null) {
18373                    try {
18374                        observer.onRemoveCompleted(packageName, succeeded);
18375                    } catch (RemoteException e) {
18376                        Log.i(TAG, "Observer no longer exists.");
18377                    }
18378                } //end if observer
18379            } //end run
18380        });
18381    }
18382
18383    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18384        if (packageName == null) {
18385            Slog.w(TAG, "Attempt to delete null packageName.");
18386            return false;
18387        }
18388
18389        // Try finding details about the requested package
18390        PackageParser.Package pkg;
18391        synchronized (mPackages) {
18392            pkg = mPackages.get(packageName);
18393            if (pkg == null) {
18394                final PackageSetting ps = mSettings.mPackages.get(packageName);
18395                if (ps != null) {
18396                    pkg = ps.pkg;
18397                }
18398            }
18399
18400            if (pkg == null) {
18401                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18402                return false;
18403            }
18404
18405            PackageSetting ps = (PackageSetting) pkg.mExtras;
18406            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18407        }
18408
18409        clearAppDataLIF(pkg, userId,
18410                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18411
18412        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18413        removeKeystoreDataIfNeeded(userId, appId);
18414
18415        UserManagerInternal umInternal = getUserManagerInternal();
18416        final int flags;
18417        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18418            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18419        } else if (umInternal.isUserRunning(userId)) {
18420            flags = StorageManager.FLAG_STORAGE_DE;
18421        } else {
18422            flags = 0;
18423        }
18424        prepareAppDataContentsLIF(pkg, userId, flags);
18425
18426        return true;
18427    }
18428
18429    /**
18430     * Reverts user permission state changes (permissions and flags) in
18431     * all packages for a given user.
18432     *
18433     * @param userId The device user for which to do a reset.
18434     */
18435    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18436        final int packageCount = mPackages.size();
18437        for (int i = 0; i < packageCount; i++) {
18438            PackageParser.Package pkg = mPackages.valueAt(i);
18439            PackageSetting ps = (PackageSetting) pkg.mExtras;
18440            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18441        }
18442    }
18443
18444    private void resetNetworkPolicies(int userId) {
18445        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18446    }
18447
18448    /**
18449     * Reverts user permission state changes (permissions and flags).
18450     *
18451     * @param ps The package for which to reset.
18452     * @param userId The device user for which to do a reset.
18453     */
18454    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18455            final PackageSetting ps, final int userId) {
18456        if (ps.pkg == null) {
18457            return;
18458        }
18459
18460        // These are flags that can change base on user actions.
18461        final int userSettableMask = FLAG_PERMISSION_USER_SET
18462                | FLAG_PERMISSION_USER_FIXED
18463                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18464                | FLAG_PERMISSION_REVIEW_REQUIRED;
18465
18466        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18467                | FLAG_PERMISSION_POLICY_FIXED;
18468
18469        boolean writeInstallPermissions = false;
18470        boolean writeRuntimePermissions = false;
18471
18472        final int permissionCount = ps.pkg.requestedPermissions.size();
18473        for (int i = 0; i < permissionCount; i++) {
18474            String permission = ps.pkg.requestedPermissions.get(i);
18475
18476            BasePermission bp = mSettings.mPermissions.get(permission);
18477            if (bp == null) {
18478                continue;
18479            }
18480
18481            // If shared user we just reset the state to which only this app contributed.
18482            if (ps.sharedUser != null) {
18483                boolean used = false;
18484                final int packageCount = ps.sharedUser.packages.size();
18485                for (int j = 0; j < packageCount; j++) {
18486                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18487                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18488                            && pkg.pkg.requestedPermissions.contains(permission)) {
18489                        used = true;
18490                        break;
18491                    }
18492                }
18493                if (used) {
18494                    continue;
18495                }
18496            }
18497
18498            PermissionsState permissionsState = ps.getPermissionsState();
18499
18500            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18501
18502            // Always clear the user settable flags.
18503            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18504                    bp.name) != null;
18505            // If permission review is enabled and this is a legacy app, mark the
18506            // permission as requiring a review as this is the initial state.
18507            int flags = 0;
18508            if (mPermissionReviewRequired
18509                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18510                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18511            }
18512            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18513                if (hasInstallState) {
18514                    writeInstallPermissions = true;
18515                } else {
18516                    writeRuntimePermissions = true;
18517                }
18518            }
18519
18520            // Below is only runtime permission handling.
18521            if (!bp.isRuntime()) {
18522                continue;
18523            }
18524
18525            // Never clobber system or policy.
18526            if ((oldFlags & policyOrSystemFlags) != 0) {
18527                continue;
18528            }
18529
18530            // If this permission was granted by default, make sure it is.
18531            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18532                if (permissionsState.grantRuntimePermission(bp, userId)
18533                        != PERMISSION_OPERATION_FAILURE) {
18534                    writeRuntimePermissions = true;
18535                }
18536            // If permission review is enabled the permissions for a legacy apps
18537            // are represented as constantly granted runtime ones, so don't revoke.
18538            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18539                // Otherwise, reset the permission.
18540                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18541                switch (revokeResult) {
18542                    case PERMISSION_OPERATION_SUCCESS:
18543                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18544                        writeRuntimePermissions = true;
18545                        final int appId = ps.appId;
18546                        mHandler.post(new Runnable() {
18547                            @Override
18548                            public void run() {
18549                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18550                            }
18551                        });
18552                    } break;
18553                }
18554            }
18555        }
18556
18557        // Synchronously write as we are taking permissions away.
18558        if (writeRuntimePermissions) {
18559            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18560        }
18561
18562        // Synchronously write as we are taking permissions away.
18563        if (writeInstallPermissions) {
18564            mSettings.writeLPr();
18565        }
18566    }
18567
18568    /**
18569     * Remove entries from the keystore daemon. Will only remove it if the
18570     * {@code appId} is valid.
18571     */
18572    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18573        if (appId < 0) {
18574            return;
18575        }
18576
18577        final KeyStore keyStore = KeyStore.getInstance();
18578        if (keyStore != null) {
18579            if (userId == UserHandle.USER_ALL) {
18580                for (final int individual : sUserManager.getUserIds()) {
18581                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18582                }
18583            } else {
18584                keyStore.clearUid(UserHandle.getUid(userId, appId));
18585            }
18586        } else {
18587            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18588        }
18589    }
18590
18591    @Override
18592    public void deleteApplicationCacheFiles(final String packageName,
18593            final IPackageDataObserver observer) {
18594        final int userId = UserHandle.getCallingUserId();
18595        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18596    }
18597
18598    @Override
18599    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18600            final IPackageDataObserver observer) {
18601        mContext.enforceCallingOrSelfPermission(
18602                android.Manifest.permission.DELETE_CACHE_FILES, null);
18603        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18604                /* requireFullPermission= */ true, /* checkShell= */ false,
18605                "delete application cache files");
18606
18607        final PackageParser.Package pkg;
18608        synchronized (mPackages) {
18609            pkg = mPackages.get(packageName);
18610        }
18611
18612        // Queue up an async operation since the package deletion may take a little while.
18613        mHandler.post(new Runnable() {
18614            public void run() {
18615                synchronized (mInstallLock) {
18616                    final int flags = StorageManager.FLAG_STORAGE_DE
18617                            | StorageManager.FLAG_STORAGE_CE;
18618                    // We're only clearing cache files, so we don't care if the
18619                    // app is unfrozen and still able to run
18620                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18621                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18622                }
18623                clearExternalStorageDataSync(packageName, userId, false);
18624                if (observer != null) {
18625                    try {
18626                        observer.onRemoveCompleted(packageName, true);
18627                    } catch (RemoteException e) {
18628                        Log.i(TAG, "Observer no longer exists.");
18629                    }
18630                }
18631            }
18632        });
18633    }
18634
18635    @Override
18636    public void getPackageSizeInfo(final String packageName, int userHandle,
18637            final IPackageStatsObserver observer) {
18638        throw new UnsupportedOperationException(
18639                "Shame on you for calling a hidden API. Shame!");
18640    }
18641
18642    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18643        final PackageSetting ps;
18644        synchronized (mPackages) {
18645            ps = mSettings.mPackages.get(packageName);
18646            if (ps == null) {
18647                Slog.w(TAG, "Failed to find settings for " + packageName);
18648                return false;
18649            }
18650        }
18651
18652        final String[] packageNames = { packageName };
18653        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18654        final String[] codePaths = { ps.codePathString };
18655
18656        try {
18657            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18658                    ps.appId, ceDataInodes, codePaths, stats);
18659
18660            // For now, ignore code size of packages on system partition
18661            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18662                stats.codeSize = 0;
18663            }
18664
18665            // External clients expect these to be tracked separately
18666            stats.dataSize -= stats.cacheSize;
18667
18668        } catch (InstallerException e) {
18669            Slog.w(TAG, String.valueOf(e));
18670            return false;
18671        }
18672
18673        return true;
18674    }
18675
18676    private int getUidTargetSdkVersionLockedLPr(int uid) {
18677        Object obj = mSettings.getUserIdLPr(uid);
18678        if (obj instanceof SharedUserSetting) {
18679            final SharedUserSetting sus = (SharedUserSetting) obj;
18680            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18681            final Iterator<PackageSetting> it = sus.packages.iterator();
18682            while (it.hasNext()) {
18683                final PackageSetting ps = it.next();
18684                if (ps.pkg != null) {
18685                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18686                    if (v < vers) vers = v;
18687                }
18688            }
18689            return vers;
18690        } else if (obj instanceof PackageSetting) {
18691            final PackageSetting ps = (PackageSetting) obj;
18692            if (ps.pkg != null) {
18693                return ps.pkg.applicationInfo.targetSdkVersion;
18694            }
18695        }
18696        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18697    }
18698
18699    @Override
18700    public void addPreferredActivity(IntentFilter filter, int match,
18701            ComponentName[] set, ComponentName activity, int userId) {
18702        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18703                "Adding preferred");
18704    }
18705
18706    private void addPreferredActivityInternal(IntentFilter filter, int match,
18707            ComponentName[] set, ComponentName activity, boolean always, int userId,
18708            String opname) {
18709        // writer
18710        int callingUid = Binder.getCallingUid();
18711        enforceCrossUserPermission(callingUid, userId,
18712                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18713        if (filter.countActions() == 0) {
18714            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18715            return;
18716        }
18717        synchronized (mPackages) {
18718            if (mContext.checkCallingOrSelfPermission(
18719                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18720                    != PackageManager.PERMISSION_GRANTED) {
18721                if (getUidTargetSdkVersionLockedLPr(callingUid)
18722                        < Build.VERSION_CODES.FROYO) {
18723                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18724                            + callingUid);
18725                    return;
18726                }
18727                mContext.enforceCallingOrSelfPermission(
18728                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18729            }
18730
18731            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18732            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18733                    + userId + ":");
18734            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18735            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18736            scheduleWritePackageRestrictionsLocked(userId);
18737            postPreferredActivityChangedBroadcast(userId);
18738        }
18739    }
18740
18741    private void postPreferredActivityChangedBroadcast(int userId) {
18742        mHandler.post(() -> {
18743            final IActivityManager am = ActivityManager.getService();
18744            if (am == null) {
18745                return;
18746            }
18747
18748            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18749            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18750            try {
18751                am.broadcastIntent(null, intent, null, null,
18752                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18753                        null, false, false, userId);
18754            } catch (RemoteException e) {
18755            }
18756        });
18757    }
18758
18759    @Override
18760    public void replacePreferredActivity(IntentFilter filter, int match,
18761            ComponentName[] set, ComponentName activity, int userId) {
18762        if (filter.countActions() != 1) {
18763            throw new IllegalArgumentException(
18764                    "replacePreferredActivity expects filter to have only 1 action.");
18765        }
18766        if (filter.countDataAuthorities() != 0
18767                || filter.countDataPaths() != 0
18768                || filter.countDataSchemes() > 1
18769                || filter.countDataTypes() != 0) {
18770            throw new IllegalArgumentException(
18771                    "replacePreferredActivity expects filter to have no data authorities, " +
18772                    "paths, or types; and at most one scheme.");
18773        }
18774
18775        final int callingUid = Binder.getCallingUid();
18776        enforceCrossUserPermission(callingUid, userId,
18777                true /* requireFullPermission */, false /* checkShell */,
18778                "replace preferred activity");
18779        synchronized (mPackages) {
18780            if (mContext.checkCallingOrSelfPermission(
18781                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18782                    != PackageManager.PERMISSION_GRANTED) {
18783                if (getUidTargetSdkVersionLockedLPr(callingUid)
18784                        < Build.VERSION_CODES.FROYO) {
18785                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18786                            + Binder.getCallingUid());
18787                    return;
18788                }
18789                mContext.enforceCallingOrSelfPermission(
18790                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18791            }
18792
18793            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18794            if (pir != null) {
18795                // Get all of the existing entries that exactly match this filter.
18796                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18797                if (existing != null && existing.size() == 1) {
18798                    PreferredActivity cur = existing.get(0);
18799                    if (DEBUG_PREFERRED) {
18800                        Slog.i(TAG, "Checking replace of preferred:");
18801                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18802                        if (!cur.mPref.mAlways) {
18803                            Slog.i(TAG, "  -- CUR; not mAlways!");
18804                        } else {
18805                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18806                            Slog.i(TAG, "  -- CUR: mSet="
18807                                    + Arrays.toString(cur.mPref.mSetComponents));
18808                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18809                            Slog.i(TAG, "  -- NEW: mMatch="
18810                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18811                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18812                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18813                        }
18814                    }
18815                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18816                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18817                            && cur.mPref.sameSet(set)) {
18818                        // Setting the preferred activity to what it happens to be already
18819                        if (DEBUG_PREFERRED) {
18820                            Slog.i(TAG, "Replacing with same preferred activity "
18821                                    + cur.mPref.mShortComponent + " for user "
18822                                    + userId + ":");
18823                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18824                        }
18825                        return;
18826                    }
18827                }
18828
18829                if (existing != null) {
18830                    if (DEBUG_PREFERRED) {
18831                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18832                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18833                    }
18834                    for (int i = 0; i < existing.size(); i++) {
18835                        PreferredActivity pa = existing.get(i);
18836                        if (DEBUG_PREFERRED) {
18837                            Slog.i(TAG, "Removing existing preferred activity "
18838                                    + pa.mPref.mComponent + ":");
18839                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18840                        }
18841                        pir.removeFilter(pa);
18842                    }
18843                }
18844            }
18845            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18846                    "Replacing preferred");
18847        }
18848    }
18849
18850    @Override
18851    public void clearPackagePreferredActivities(String packageName) {
18852        final int uid = Binder.getCallingUid();
18853        // writer
18854        synchronized (mPackages) {
18855            PackageParser.Package pkg = mPackages.get(packageName);
18856            if (pkg == null || pkg.applicationInfo.uid != uid) {
18857                if (mContext.checkCallingOrSelfPermission(
18858                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18859                        != PackageManager.PERMISSION_GRANTED) {
18860                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18861                            < Build.VERSION_CODES.FROYO) {
18862                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18863                                + Binder.getCallingUid());
18864                        return;
18865                    }
18866                    mContext.enforceCallingOrSelfPermission(
18867                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18868                }
18869            }
18870
18871            int user = UserHandle.getCallingUserId();
18872            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18873                scheduleWritePackageRestrictionsLocked(user);
18874            }
18875        }
18876    }
18877
18878    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18879    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18880        ArrayList<PreferredActivity> removed = null;
18881        boolean changed = false;
18882        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18883            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18884            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18885            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18886                continue;
18887            }
18888            Iterator<PreferredActivity> it = pir.filterIterator();
18889            while (it.hasNext()) {
18890                PreferredActivity pa = it.next();
18891                // Mark entry for removal only if it matches the package name
18892                // and the entry is of type "always".
18893                if (packageName == null ||
18894                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18895                                && pa.mPref.mAlways)) {
18896                    if (removed == null) {
18897                        removed = new ArrayList<PreferredActivity>();
18898                    }
18899                    removed.add(pa);
18900                }
18901            }
18902            if (removed != null) {
18903                for (int j=0; j<removed.size(); j++) {
18904                    PreferredActivity pa = removed.get(j);
18905                    pir.removeFilter(pa);
18906                }
18907                changed = true;
18908            }
18909        }
18910        if (changed) {
18911            postPreferredActivityChangedBroadcast(userId);
18912        }
18913        return changed;
18914    }
18915
18916    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18917    private void clearIntentFilterVerificationsLPw(int userId) {
18918        final int packageCount = mPackages.size();
18919        for (int i = 0; i < packageCount; i++) {
18920            PackageParser.Package pkg = mPackages.valueAt(i);
18921            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18922        }
18923    }
18924
18925    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18926    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18927        if (userId == UserHandle.USER_ALL) {
18928            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18929                    sUserManager.getUserIds())) {
18930                for (int oneUserId : sUserManager.getUserIds()) {
18931                    scheduleWritePackageRestrictionsLocked(oneUserId);
18932                }
18933            }
18934        } else {
18935            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18936                scheduleWritePackageRestrictionsLocked(userId);
18937            }
18938        }
18939    }
18940
18941    void clearDefaultBrowserIfNeeded(String packageName) {
18942        for (int oneUserId : sUserManager.getUserIds()) {
18943            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18944            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18945            if (packageName.equals(defaultBrowserPackageName)) {
18946                setDefaultBrowserPackageName(null, oneUserId);
18947            }
18948        }
18949    }
18950
18951    @Override
18952    public void resetApplicationPreferences(int userId) {
18953        mContext.enforceCallingOrSelfPermission(
18954                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18955        final long identity = Binder.clearCallingIdentity();
18956        // writer
18957        try {
18958            synchronized (mPackages) {
18959                clearPackagePreferredActivitiesLPw(null, userId);
18960                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18961                // TODO: We have to reset the default SMS and Phone. This requires
18962                // significant refactoring to keep all default apps in the package
18963                // manager (cleaner but more work) or have the services provide
18964                // callbacks to the package manager to request a default app reset.
18965                applyFactoryDefaultBrowserLPw(userId);
18966                clearIntentFilterVerificationsLPw(userId);
18967                primeDomainVerificationsLPw(userId);
18968                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18969                scheduleWritePackageRestrictionsLocked(userId);
18970            }
18971            resetNetworkPolicies(userId);
18972        } finally {
18973            Binder.restoreCallingIdentity(identity);
18974        }
18975    }
18976
18977    @Override
18978    public int getPreferredActivities(List<IntentFilter> outFilters,
18979            List<ComponentName> outActivities, String packageName) {
18980
18981        int num = 0;
18982        final int userId = UserHandle.getCallingUserId();
18983        // reader
18984        synchronized (mPackages) {
18985            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18986            if (pir != null) {
18987                final Iterator<PreferredActivity> it = pir.filterIterator();
18988                while (it.hasNext()) {
18989                    final PreferredActivity pa = it.next();
18990                    if (packageName == null
18991                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18992                                    && pa.mPref.mAlways)) {
18993                        if (outFilters != null) {
18994                            outFilters.add(new IntentFilter(pa));
18995                        }
18996                        if (outActivities != null) {
18997                            outActivities.add(pa.mPref.mComponent);
18998                        }
18999                    }
19000                }
19001            }
19002        }
19003
19004        return num;
19005    }
19006
19007    @Override
19008    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19009            int userId) {
19010        int callingUid = Binder.getCallingUid();
19011        if (callingUid != Process.SYSTEM_UID) {
19012            throw new SecurityException(
19013                    "addPersistentPreferredActivity can only be run by the system");
19014        }
19015        if (filter.countActions() == 0) {
19016            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19017            return;
19018        }
19019        synchronized (mPackages) {
19020            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19021                    ":");
19022            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19023            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19024                    new PersistentPreferredActivity(filter, activity));
19025            scheduleWritePackageRestrictionsLocked(userId);
19026            postPreferredActivityChangedBroadcast(userId);
19027        }
19028    }
19029
19030    @Override
19031    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19032        int callingUid = Binder.getCallingUid();
19033        if (callingUid != Process.SYSTEM_UID) {
19034            throw new SecurityException(
19035                    "clearPackagePersistentPreferredActivities can only be run by the system");
19036        }
19037        ArrayList<PersistentPreferredActivity> removed = null;
19038        boolean changed = false;
19039        synchronized (mPackages) {
19040            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19041                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19042                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19043                        .valueAt(i);
19044                if (userId != thisUserId) {
19045                    continue;
19046                }
19047                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19048                while (it.hasNext()) {
19049                    PersistentPreferredActivity ppa = it.next();
19050                    // Mark entry for removal only if it matches the package name.
19051                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19052                        if (removed == null) {
19053                            removed = new ArrayList<PersistentPreferredActivity>();
19054                        }
19055                        removed.add(ppa);
19056                    }
19057                }
19058                if (removed != null) {
19059                    for (int j=0; j<removed.size(); j++) {
19060                        PersistentPreferredActivity ppa = removed.get(j);
19061                        ppir.removeFilter(ppa);
19062                    }
19063                    changed = true;
19064                }
19065            }
19066
19067            if (changed) {
19068                scheduleWritePackageRestrictionsLocked(userId);
19069                postPreferredActivityChangedBroadcast(userId);
19070            }
19071        }
19072    }
19073
19074    /**
19075     * Common machinery for picking apart a restored XML blob and passing
19076     * it to a caller-supplied functor to be applied to the running system.
19077     */
19078    private void restoreFromXml(XmlPullParser parser, int userId,
19079            String expectedStartTag, BlobXmlRestorer functor)
19080            throws IOException, XmlPullParserException {
19081        int type;
19082        while ((type = parser.next()) != XmlPullParser.START_TAG
19083                && type != XmlPullParser.END_DOCUMENT) {
19084        }
19085        if (type != XmlPullParser.START_TAG) {
19086            // oops didn't find a start tag?!
19087            if (DEBUG_BACKUP) {
19088                Slog.e(TAG, "Didn't find start tag during restore");
19089            }
19090            return;
19091        }
19092Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19093        // this is supposed to be TAG_PREFERRED_BACKUP
19094        if (!expectedStartTag.equals(parser.getName())) {
19095            if (DEBUG_BACKUP) {
19096                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19097            }
19098            return;
19099        }
19100
19101        // skip interfering stuff, then we're aligned with the backing implementation
19102        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19103Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19104        functor.apply(parser, userId);
19105    }
19106
19107    private interface BlobXmlRestorer {
19108        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19109    }
19110
19111    /**
19112     * Non-Binder method, support for the backup/restore mechanism: write the
19113     * full set of preferred activities in its canonical XML format.  Returns the
19114     * XML output as a byte array, or null if there is none.
19115     */
19116    @Override
19117    public byte[] getPreferredActivityBackup(int userId) {
19118        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19119            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19120        }
19121
19122        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19123        try {
19124            final XmlSerializer serializer = new FastXmlSerializer();
19125            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19126            serializer.startDocument(null, true);
19127            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19128
19129            synchronized (mPackages) {
19130                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19131            }
19132
19133            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19134            serializer.endDocument();
19135            serializer.flush();
19136        } catch (Exception e) {
19137            if (DEBUG_BACKUP) {
19138                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19139            }
19140            return null;
19141        }
19142
19143        return dataStream.toByteArray();
19144    }
19145
19146    @Override
19147    public void restorePreferredActivities(byte[] backup, int userId) {
19148        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19149            throw new SecurityException("Only the system may call restorePreferredActivities()");
19150        }
19151
19152        try {
19153            final XmlPullParser parser = Xml.newPullParser();
19154            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19155            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19156                    new BlobXmlRestorer() {
19157                        @Override
19158                        public void apply(XmlPullParser parser, int userId)
19159                                throws XmlPullParserException, IOException {
19160                            synchronized (mPackages) {
19161                                mSettings.readPreferredActivitiesLPw(parser, userId);
19162                            }
19163                        }
19164                    } );
19165        } catch (Exception e) {
19166            if (DEBUG_BACKUP) {
19167                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19168            }
19169        }
19170    }
19171
19172    /**
19173     * Non-Binder method, support for the backup/restore mechanism: write the
19174     * default browser (etc) settings in its canonical XML format.  Returns the default
19175     * browser XML representation as a byte array, or null if there is none.
19176     */
19177    @Override
19178    public byte[] getDefaultAppsBackup(int userId) {
19179        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19180            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19181        }
19182
19183        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19184        try {
19185            final XmlSerializer serializer = new FastXmlSerializer();
19186            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19187            serializer.startDocument(null, true);
19188            serializer.startTag(null, TAG_DEFAULT_APPS);
19189
19190            synchronized (mPackages) {
19191                mSettings.writeDefaultAppsLPr(serializer, userId);
19192            }
19193
19194            serializer.endTag(null, TAG_DEFAULT_APPS);
19195            serializer.endDocument();
19196            serializer.flush();
19197        } catch (Exception e) {
19198            if (DEBUG_BACKUP) {
19199                Slog.e(TAG, "Unable to write default apps for backup", e);
19200            }
19201            return null;
19202        }
19203
19204        return dataStream.toByteArray();
19205    }
19206
19207    @Override
19208    public void restoreDefaultApps(byte[] backup, int userId) {
19209        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19210            throw new SecurityException("Only the system may call restoreDefaultApps()");
19211        }
19212
19213        try {
19214            final XmlPullParser parser = Xml.newPullParser();
19215            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19216            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19217                    new BlobXmlRestorer() {
19218                        @Override
19219                        public void apply(XmlPullParser parser, int userId)
19220                                throws XmlPullParserException, IOException {
19221                            synchronized (mPackages) {
19222                                mSettings.readDefaultAppsLPw(parser, userId);
19223                            }
19224                        }
19225                    } );
19226        } catch (Exception e) {
19227            if (DEBUG_BACKUP) {
19228                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19229            }
19230        }
19231    }
19232
19233    @Override
19234    public byte[] getIntentFilterVerificationBackup(int userId) {
19235        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19236            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19237        }
19238
19239        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19240        try {
19241            final XmlSerializer serializer = new FastXmlSerializer();
19242            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19243            serializer.startDocument(null, true);
19244            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19245
19246            synchronized (mPackages) {
19247                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19248            }
19249
19250            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19251            serializer.endDocument();
19252            serializer.flush();
19253        } catch (Exception e) {
19254            if (DEBUG_BACKUP) {
19255                Slog.e(TAG, "Unable to write default apps for backup", e);
19256            }
19257            return null;
19258        }
19259
19260        return dataStream.toByteArray();
19261    }
19262
19263    @Override
19264    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19265        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19266            throw new SecurityException("Only the system may call restorePreferredActivities()");
19267        }
19268
19269        try {
19270            final XmlPullParser parser = Xml.newPullParser();
19271            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19272            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19273                    new BlobXmlRestorer() {
19274                        @Override
19275                        public void apply(XmlPullParser parser, int userId)
19276                                throws XmlPullParserException, IOException {
19277                            synchronized (mPackages) {
19278                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19279                                mSettings.writeLPr();
19280                            }
19281                        }
19282                    } );
19283        } catch (Exception e) {
19284            if (DEBUG_BACKUP) {
19285                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19286            }
19287        }
19288    }
19289
19290    @Override
19291    public byte[] getPermissionGrantBackup(int userId) {
19292        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19293            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19294        }
19295
19296        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19297        try {
19298            final XmlSerializer serializer = new FastXmlSerializer();
19299            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19300            serializer.startDocument(null, true);
19301            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19302
19303            synchronized (mPackages) {
19304                serializeRuntimePermissionGrantsLPr(serializer, userId);
19305            }
19306
19307            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19308            serializer.endDocument();
19309            serializer.flush();
19310        } catch (Exception e) {
19311            if (DEBUG_BACKUP) {
19312                Slog.e(TAG, "Unable to write default apps for backup", e);
19313            }
19314            return null;
19315        }
19316
19317        return dataStream.toByteArray();
19318    }
19319
19320    @Override
19321    public void restorePermissionGrants(byte[] backup, int userId) {
19322        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19323            throw new SecurityException("Only the system may call restorePermissionGrants()");
19324        }
19325
19326        try {
19327            final XmlPullParser parser = Xml.newPullParser();
19328            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19329            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19330                    new BlobXmlRestorer() {
19331                        @Override
19332                        public void apply(XmlPullParser parser, int userId)
19333                                throws XmlPullParserException, IOException {
19334                            synchronized (mPackages) {
19335                                processRestoredPermissionGrantsLPr(parser, userId);
19336                            }
19337                        }
19338                    } );
19339        } catch (Exception e) {
19340            if (DEBUG_BACKUP) {
19341                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19342            }
19343        }
19344    }
19345
19346    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19347            throws IOException {
19348        serializer.startTag(null, TAG_ALL_GRANTS);
19349
19350        final int N = mSettings.mPackages.size();
19351        for (int i = 0; i < N; i++) {
19352            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19353            boolean pkgGrantsKnown = false;
19354
19355            PermissionsState packagePerms = ps.getPermissionsState();
19356
19357            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19358                final int grantFlags = state.getFlags();
19359                // only look at grants that are not system/policy fixed
19360                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19361                    final boolean isGranted = state.isGranted();
19362                    // And only back up the user-twiddled state bits
19363                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19364                        final String packageName = mSettings.mPackages.keyAt(i);
19365                        if (!pkgGrantsKnown) {
19366                            serializer.startTag(null, TAG_GRANT);
19367                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19368                            pkgGrantsKnown = true;
19369                        }
19370
19371                        final boolean userSet =
19372                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19373                        final boolean userFixed =
19374                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19375                        final boolean revoke =
19376                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19377
19378                        serializer.startTag(null, TAG_PERMISSION);
19379                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19380                        if (isGranted) {
19381                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19382                        }
19383                        if (userSet) {
19384                            serializer.attribute(null, ATTR_USER_SET, "true");
19385                        }
19386                        if (userFixed) {
19387                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19388                        }
19389                        if (revoke) {
19390                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19391                        }
19392                        serializer.endTag(null, TAG_PERMISSION);
19393                    }
19394                }
19395            }
19396
19397            if (pkgGrantsKnown) {
19398                serializer.endTag(null, TAG_GRANT);
19399            }
19400        }
19401
19402        serializer.endTag(null, TAG_ALL_GRANTS);
19403    }
19404
19405    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19406            throws XmlPullParserException, IOException {
19407        String pkgName = null;
19408        int outerDepth = parser.getDepth();
19409        int type;
19410        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19411                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19412            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19413                continue;
19414            }
19415
19416            final String tagName = parser.getName();
19417            if (tagName.equals(TAG_GRANT)) {
19418                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19419                if (DEBUG_BACKUP) {
19420                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19421                }
19422            } else if (tagName.equals(TAG_PERMISSION)) {
19423
19424                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19425                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19426
19427                int newFlagSet = 0;
19428                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19429                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19430                }
19431                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19432                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19433                }
19434                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19435                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19436                }
19437                if (DEBUG_BACKUP) {
19438                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19439                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19440                }
19441                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19442                if (ps != null) {
19443                    // Already installed so we apply the grant immediately
19444                    if (DEBUG_BACKUP) {
19445                        Slog.v(TAG, "        + already installed; applying");
19446                    }
19447                    PermissionsState perms = ps.getPermissionsState();
19448                    BasePermission bp = mSettings.mPermissions.get(permName);
19449                    if (bp != null) {
19450                        if (isGranted) {
19451                            perms.grantRuntimePermission(bp, userId);
19452                        }
19453                        if (newFlagSet != 0) {
19454                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19455                        }
19456                    }
19457                } else {
19458                    // Need to wait for post-restore install to apply the grant
19459                    if (DEBUG_BACKUP) {
19460                        Slog.v(TAG, "        - not yet installed; saving for later");
19461                    }
19462                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19463                            isGranted, newFlagSet, userId);
19464                }
19465            } else {
19466                PackageManagerService.reportSettingsProblem(Log.WARN,
19467                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19468                XmlUtils.skipCurrentTag(parser);
19469            }
19470        }
19471
19472        scheduleWriteSettingsLocked();
19473        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19474    }
19475
19476    @Override
19477    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19478            int sourceUserId, int targetUserId, int flags) {
19479        mContext.enforceCallingOrSelfPermission(
19480                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19481        int callingUid = Binder.getCallingUid();
19482        enforceOwnerRights(ownerPackage, callingUid);
19483        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19484        if (intentFilter.countActions() == 0) {
19485            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19486            return;
19487        }
19488        synchronized (mPackages) {
19489            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19490                    ownerPackage, targetUserId, flags);
19491            CrossProfileIntentResolver resolver =
19492                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19493            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19494            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19495            if (existing != null) {
19496                int size = existing.size();
19497                for (int i = 0; i < size; i++) {
19498                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19499                        return;
19500                    }
19501                }
19502            }
19503            resolver.addFilter(newFilter);
19504            scheduleWritePackageRestrictionsLocked(sourceUserId);
19505        }
19506    }
19507
19508    @Override
19509    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19510        mContext.enforceCallingOrSelfPermission(
19511                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19512        int callingUid = Binder.getCallingUid();
19513        enforceOwnerRights(ownerPackage, callingUid);
19514        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19515        synchronized (mPackages) {
19516            CrossProfileIntentResolver resolver =
19517                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19518            ArraySet<CrossProfileIntentFilter> set =
19519                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19520            for (CrossProfileIntentFilter filter : set) {
19521                if (filter.getOwnerPackage().equals(ownerPackage)) {
19522                    resolver.removeFilter(filter);
19523                }
19524            }
19525            scheduleWritePackageRestrictionsLocked(sourceUserId);
19526        }
19527    }
19528
19529    // Enforcing that callingUid is owning pkg on userId
19530    private void enforceOwnerRights(String pkg, int callingUid) {
19531        // The system owns everything.
19532        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19533            return;
19534        }
19535        int callingUserId = UserHandle.getUserId(callingUid);
19536        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19537        if (pi == null) {
19538            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19539                    + callingUserId);
19540        }
19541        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19542            throw new SecurityException("Calling uid " + callingUid
19543                    + " does not own package " + pkg);
19544        }
19545    }
19546
19547    @Override
19548    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19549        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19550    }
19551
19552    /**
19553     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19554     * then reports the most likely home activity or null if there are more than one.
19555     */
19556    public ComponentName getDefaultHomeActivity(int userId) {
19557        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19558        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19559        if (cn != null) {
19560            return cn;
19561        }
19562
19563        // Find the launcher with the highest priority and return that component if there are no
19564        // other home activity with the same priority.
19565        int lastPriority = Integer.MIN_VALUE;
19566        ComponentName lastComponent = null;
19567        final int size = allHomeCandidates.size();
19568        for (int i = 0; i < size; i++) {
19569            final ResolveInfo ri = allHomeCandidates.get(i);
19570            if (ri.priority > lastPriority) {
19571                lastComponent = ri.activityInfo.getComponentName();
19572                lastPriority = ri.priority;
19573            } else if (ri.priority == lastPriority) {
19574                // Two components found with same priority.
19575                lastComponent = null;
19576            }
19577        }
19578        return lastComponent;
19579    }
19580
19581    private Intent getHomeIntent() {
19582        Intent intent = new Intent(Intent.ACTION_MAIN);
19583        intent.addCategory(Intent.CATEGORY_HOME);
19584        intent.addCategory(Intent.CATEGORY_DEFAULT);
19585        return intent;
19586    }
19587
19588    private IntentFilter getHomeFilter() {
19589        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19590        filter.addCategory(Intent.CATEGORY_HOME);
19591        filter.addCategory(Intent.CATEGORY_DEFAULT);
19592        return filter;
19593    }
19594
19595    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19596            int userId) {
19597        Intent intent  = getHomeIntent();
19598        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19599                PackageManager.GET_META_DATA, userId);
19600        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19601                true, false, false, userId);
19602
19603        allHomeCandidates.clear();
19604        if (list != null) {
19605            for (ResolveInfo ri : list) {
19606                allHomeCandidates.add(ri);
19607            }
19608        }
19609        return (preferred == null || preferred.activityInfo == null)
19610                ? null
19611                : new ComponentName(preferred.activityInfo.packageName,
19612                        preferred.activityInfo.name);
19613    }
19614
19615    @Override
19616    public void setHomeActivity(ComponentName comp, int userId) {
19617        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19618        getHomeActivitiesAsUser(homeActivities, userId);
19619
19620        boolean found = false;
19621
19622        final int size = homeActivities.size();
19623        final ComponentName[] set = new ComponentName[size];
19624        for (int i = 0; i < size; i++) {
19625            final ResolveInfo candidate = homeActivities.get(i);
19626            final ActivityInfo info = candidate.activityInfo;
19627            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19628            set[i] = activityName;
19629            if (!found && activityName.equals(comp)) {
19630                found = true;
19631            }
19632        }
19633        if (!found) {
19634            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19635                    + userId);
19636        }
19637        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19638                set, comp, userId);
19639    }
19640
19641    private @Nullable String getSetupWizardPackageName() {
19642        final Intent intent = new Intent(Intent.ACTION_MAIN);
19643        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19644
19645        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19646                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19647                        | MATCH_DISABLED_COMPONENTS,
19648                UserHandle.myUserId());
19649        if (matches.size() == 1) {
19650            return matches.get(0).getComponentInfo().packageName;
19651        } else {
19652            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19653                    + ": matches=" + matches);
19654            return null;
19655        }
19656    }
19657
19658    private @Nullable String getStorageManagerPackageName() {
19659        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19660
19661        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19662                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19663                        | MATCH_DISABLED_COMPONENTS,
19664                UserHandle.myUserId());
19665        if (matches.size() == 1) {
19666            return matches.get(0).getComponentInfo().packageName;
19667        } else {
19668            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19669                    + matches.size() + ": matches=" + matches);
19670            return null;
19671        }
19672    }
19673
19674    @Override
19675    public void setApplicationEnabledSetting(String appPackageName,
19676            int newState, int flags, int userId, String callingPackage) {
19677        if (!sUserManager.exists(userId)) return;
19678        if (callingPackage == null) {
19679            callingPackage = Integer.toString(Binder.getCallingUid());
19680        }
19681        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19682    }
19683
19684    @Override
19685    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19686        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19687        synchronized (mPackages) {
19688            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19689            if (pkgSetting != null) {
19690                pkgSetting.setUpdateAvailable(updateAvailable);
19691            }
19692        }
19693    }
19694
19695    @Override
19696    public void setComponentEnabledSetting(ComponentName componentName,
19697            int newState, int flags, int userId) {
19698        if (!sUserManager.exists(userId)) return;
19699        setEnabledSetting(componentName.getPackageName(),
19700                componentName.getClassName(), newState, flags, userId, null);
19701    }
19702
19703    private void setEnabledSetting(final String packageName, String className, int newState,
19704            final int flags, int userId, String callingPackage) {
19705        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19706              || newState == COMPONENT_ENABLED_STATE_ENABLED
19707              || newState == COMPONENT_ENABLED_STATE_DISABLED
19708              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19709              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19710            throw new IllegalArgumentException("Invalid new component state: "
19711                    + newState);
19712        }
19713        PackageSetting pkgSetting;
19714        final int uid = Binder.getCallingUid();
19715        final int permission;
19716        if (uid == Process.SYSTEM_UID) {
19717            permission = PackageManager.PERMISSION_GRANTED;
19718        } else {
19719            permission = mContext.checkCallingOrSelfPermission(
19720                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19721        }
19722        enforceCrossUserPermission(uid, userId,
19723                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19724        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19725        boolean sendNow = false;
19726        boolean isApp = (className == null);
19727        String componentName = isApp ? packageName : className;
19728        int packageUid = -1;
19729        ArrayList<String> components;
19730
19731        // writer
19732        synchronized (mPackages) {
19733            pkgSetting = mSettings.mPackages.get(packageName);
19734            if (pkgSetting == null) {
19735                if (className == null) {
19736                    throw new IllegalArgumentException("Unknown package: " + packageName);
19737                }
19738                throw new IllegalArgumentException(
19739                        "Unknown component: " + packageName + "/" + className);
19740            }
19741        }
19742
19743        // Limit who can change which apps
19744        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19745            // Don't allow apps that don't have permission to modify other apps
19746            if (!allowedByPermission) {
19747                throw new SecurityException(
19748                        "Permission Denial: attempt to change component state from pid="
19749                        + Binder.getCallingPid()
19750                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19751            }
19752            // Don't allow changing protected packages.
19753            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19754                throw new SecurityException("Cannot disable a protected package: " + packageName);
19755            }
19756        }
19757
19758        synchronized (mPackages) {
19759            if (uid == Process.SHELL_UID
19760                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19761                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19762                // unless it is a test package.
19763                int oldState = pkgSetting.getEnabled(userId);
19764                if (className == null
19765                    &&
19766                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19767                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19768                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19769                    &&
19770                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19771                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19772                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19773                    // ok
19774                } else {
19775                    throw new SecurityException(
19776                            "Shell cannot change component state for " + packageName + "/"
19777                            + className + " to " + newState);
19778                }
19779            }
19780            if (className == null) {
19781                // We're dealing with an application/package level state change
19782                if (pkgSetting.getEnabled(userId) == newState) {
19783                    // Nothing to do
19784                    return;
19785                }
19786                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19787                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19788                    // Don't care about who enables an app.
19789                    callingPackage = null;
19790                }
19791                pkgSetting.setEnabled(newState, userId, callingPackage);
19792                // pkgSetting.pkg.mSetEnabled = newState;
19793            } else {
19794                // We're dealing with a component level state change
19795                // First, verify that this is a valid class name.
19796                PackageParser.Package pkg = pkgSetting.pkg;
19797                if (pkg == null || !pkg.hasComponentClassName(className)) {
19798                    if (pkg != null &&
19799                            pkg.applicationInfo.targetSdkVersion >=
19800                                    Build.VERSION_CODES.JELLY_BEAN) {
19801                        throw new IllegalArgumentException("Component class " + className
19802                                + " does not exist in " + packageName);
19803                    } else {
19804                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19805                                + className + " does not exist in " + packageName);
19806                    }
19807                }
19808                switch (newState) {
19809                case COMPONENT_ENABLED_STATE_ENABLED:
19810                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19811                        return;
19812                    }
19813                    break;
19814                case COMPONENT_ENABLED_STATE_DISABLED:
19815                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19816                        return;
19817                    }
19818                    break;
19819                case COMPONENT_ENABLED_STATE_DEFAULT:
19820                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19821                        return;
19822                    }
19823                    break;
19824                default:
19825                    Slog.e(TAG, "Invalid new component state: " + newState);
19826                    return;
19827                }
19828            }
19829            scheduleWritePackageRestrictionsLocked(userId);
19830            updateSequenceNumberLP(packageName, new int[] { userId });
19831            components = mPendingBroadcasts.get(userId, packageName);
19832            final boolean newPackage = components == null;
19833            if (newPackage) {
19834                components = new ArrayList<String>();
19835            }
19836            if (!components.contains(componentName)) {
19837                components.add(componentName);
19838            }
19839            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19840                sendNow = true;
19841                // Purge entry from pending broadcast list if another one exists already
19842                // since we are sending one right away.
19843                mPendingBroadcasts.remove(userId, packageName);
19844            } else {
19845                if (newPackage) {
19846                    mPendingBroadcasts.put(userId, packageName, components);
19847                }
19848                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19849                    // Schedule a message
19850                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19851                }
19852            }
19853        }
19854
19855        long callingId = Binder.clearCallingIdentity();
19856        try {
19857            if (sendNow) {
19858                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19859                sendPackageChangedBroadcast(packageName,
19860                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19861            }
19862        } finally {
19863            Binder.restoreCallingIdentity(callingId);
19864        }
19865    }
19866
19867    @Override
19868    public void flushPackageRestrictionsAsUser(int userId) {
19869        if (!sUserManager.exists(userId)) {
19870            return;
19871        }
19872        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19873                false /* checkShell */, "flushPackageRestrictions");
19874        synchronized (mPackages) {
19875            mSettings.writePackageRestrictionsLPr(userId);
19876            mDirtyUsers.remove(userId);
19877            if (mDirtyUsers.isEmpty()) {
19878                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19879            }
19880        }
19881    }
19882
19883    private void sendPackageChangedBroadcast(String packageName,
19884            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19885        if (DEBUG_INSTALL)
19886            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19887                    + componentNames);
19888        Bundle extras = new Bundle(4);
19889        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19890        String nameList[] = new String[componentNames.size()];
19891        componentNames.toArray(nameList);
19892        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19893        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19894        extras.putInt(Intent.EXTRA_UID, packageUid);
19895        // If this is not reporting a change of the overall package, then only send it
19896        // to registered receivers.  We don't want to launch a swath of apps for every
19897        // little component state change.
19898        final int flags = !componentNames.contains(packageName)
19899                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19900        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19901                new int[] {UserHandle.getUserId(packageUid)});
19902    }
19903
19904    @Override
19905    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19906        if (!sUserManager.exists(userId)) return;
19907        final int uid = Binder.getCallingUid();
19908        final int permission = mContext.checkCallingOrSelfPermission(
19909                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19910        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19911        enforceCrossUserPermission(uid, userId,
19912                true /* requireFullPermission */, true /* checkShell */, "stop package");
19913        // writer
19914        synchronized (mPackages) {
19915            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19916                    allowedByPermission, uid, userId)) {
19917                scheduleWritePackageRestrictionsLocked(userId);
19918            }
19919        }
19920    }
19921
19922    @Override
19923    public String getInstallerPackageName(String packageName) {
19924        // reader
19925        synchronized (mPackages) {
19926            return mSettings.getInstallerPackageNameLPr(packageName);
19927        }
19928    }
19929
19930    public boolean isOrphaned(String packageName) {
19931        // reader
19932        synchronized (mPackages) {
19933            return mSettings.isOrphaned(packageName);
19934        }
19935    }
19936
19937    @Override
19938    public int getApplicationEnabledSetting(String packageName, int userId) {
19939        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19940        int uid = Binder.getCallingUid();
19941        enforceCrossUserPermission(uid, userId,
19942                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19943        // reader
19944        synchronized (mPackages) {
19945            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19946        }
19947    }
19948
19949    @Override
19950    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19951        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19952        int uid = Binder.getCallingUid();
19953        enforceCrossUserPermission(uid, userId,
19954                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19955        // reader
19956        synchronized (mPackages) {
19957            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19958        }
19959    }
19960
19961    @Override
19962    public void enterSafeMode() {
19963        enforceSystemOrRoot("Only the system can request entering safe mode");
19964
19965        if (!mSystemReady) {
19966            mSafeMode = true;
19967        }
19968    }
19969
19970    @Override
19971    public void systemReady() {
19972        mSystemReady = true;
19973
19974        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19975        // disabled after already being started.
19976        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19977                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19978
19979        // Read the compatibilty setting when the system is ready.
19980        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19981                mContext.getContentResolver(),
19982                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19983        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19984        if (DEBUG_SETTINGS) {
19985            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19986        }
19987
19988        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19989
19990        synchronized (mPackages) {
19991            // Verify that all of the preferred activity components actually
19992            // exist.  It is possible for applications to be updated and at
19993            // that point remove a previously declared activity component that
19994            // had been set as a preferred activity.  We try to clean this up
19995            // the next time we encounter that preferred activity, but it is
19996            // possible for the user flow to never be able to return to that
19997            // situation so here we do a sanity check to make sure we haven't
19998            // left any junk around.
19999            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20000            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20001                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20002                removed.clear();
20003                for (PreferredActivity pa : pir.filterSet()) {
20004                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20005                        removed.add(pa);
20006                    }
20007                }
20008                if (removed.size() > 0) {
20009                    for (int r=0; r<removed.size(); r++) {
20010                        PreferredActivity pa = removed.get(r);
20011                        Slog.w(TAG, "Removing dangling preferred activity: "
20012                                + pa.mPref.mComponent);
20013                        pir.removeFilter(pa);
20014                    }
20015                    mSettings.writePackageRestrictionsLPr(
20016                            mSettings.mPreferredActivities.keyAt(i));
20017                }
20018            }
20019
20020            for (int userId : UserManagerService.getInstance().getUserIds()) {
20021                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20022                    grantPermissionsUserIds = ArrayUtils.appendInt(
20023                            grantPermissionsUserIds, userId);
20024                }
20025            }
20026        }
20027        sUserManager.systemReady();
20028
20029        // If we upgraded grant all default permissions before kicking off.
20030        for (int userId : grantPermissionsUserIds) {
20031            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20032        }
20033
20034        // If we did not grant default permissions, we preload from this the
20035        // default permission exceptions lazily to ensure we don't hit the
20036        // disk on a new user creation.
20037        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20038            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20039        }
20040
20041        // Kick off any messages waiting for system ready
20042        if (mPostSystemReadyMessages != null) {
20043            for (Message msg : mPostSystemReadyMessages) {
20044                msg.sendToTarget();
20045            }
20046            mPostSystemReadyMessages = null;
20047        }
20048
20049        // Watch for external volumes that come and go over time
20050        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20051        storage.registerListener(mStorageListener);
20052
20053        mInstallerService.systemReady();
20054        mPackageDexOptimizer.systemReady();
20055
20056        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20057                StorageManagerInternal.class);
20058        StorageManagerInternal.addExternalStoragePolicy(
20059                new StorageManagerInternal.ExternalStorageMountPolicy() {
20060            @Override
20061            public int getMountMode(int uid, String packageName) {
20062                if (Process.isIsolated(uid)) {
20063                    return Zygote.MOUNT_EXTERNAL_NONE;
20064                }
20065                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20066                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20067                }
20068                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20069                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20070                }
20071                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20072                    return Zygote.MOUNT_EXTERNAL_READ;
20073                }
20074                return Zygote.MOUNT_EXTERNAL_WRITE;
20075            }
20076
20077            @Override
20078            public boolean hasExternalStorage(int uid, String packageName) {
20079                return true;
20080            }
20081        });
20082
20083        // Now that we're mostly running, clean up stale users and apps
20084        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20085        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20086
20087        if (mPrivappPermissionsViolations != null) {
20088            Slog.wtf(TAG,"Signature|privileged permissions not in "
20089                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20090            mPrivappPermissionsViolations = null;
20091        }
20092    }
20093
20094    public void waitForAppDataPrepared() {
20095        if (mPrepareAppDataFuture == null) {
20096            return;
20097        }
20098        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20099        mPrepareAppDataFuture = null;
20100    }
20101
20102    @Override
20103    public boolean isSafeMode() {
20104        return mSafeMode;
20105    }
20106
20107    @Override
20108    public boolean hasSystemUidErrors() {
20109        return mHasSystemUidErrors;
20110    }
20111
20112    static String arrayToString(int[] array) {
20113        StringBuffer buf = new StringBuffer(128);
20114        buf.append('[');
20115        if (array != null) {
20116            for (int i=0; i<array.length; i++) {
20117                if (i > 0) buf.append(", ");
20118                buf.append(array[i]);
20119            }
20120        }
20121        buf.append(']');
20122        return buf.toString();
20123    }
20124
20125    static class DumpState {
20126        public static final int DUMP_LIBS = 1 << 0;
20127        public static final int DUMP_FEATURES = 1 << 1;
20128        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20129        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20130        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20131        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20132        public static final int DUMP_PERMISSIONS = 1 << 6;
20133        public static final int DUMP_PACKAGES = 1 << 7;
20134        public static final int DUMP_SHARED_USERS = 1 << 8;
20135        public static final int DUMP_MESSAGES = 1 << 9;
20136        public static final int DUMP_PROVIDERS = 1 << 10;
20137        public static final int DUMP_VERIFIERS = 1 << 11;
20138        public static final int DUMP_PREFERRED = 1 << 12;
20139        public static final int DUMP_PREFERRED_XML = 1 << 13;
20140        public static final int DUMP_KEYSETS = 1 << 14;
20141        public static final int DUMP_VERSION = 1 << 15;
20142        public static final int DUMP_INSTALLS = 1 << 16;
20143        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20144        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20145        public static final int DUMP_FROZEN = 1 << 19;
20146        public static final int DUMP_DEXOPT = 1 << 20;
20147        public static final int DUMP_COMPILER_STATS = 1 << 21;
20148        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20149
20150        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20151
20152        private int mTypes;
20153
20154        private int mOptions;
20155
20156        private boolean mTitlePrinted;
20157
20158        private SharedUserSetting mSharedUser;
20159
20160        public boolean isDumping(int type) {
20161            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20162                return true;
20163            }
20164
20165            return (mTypes & type) != 0;
20166        }
20167
20168        public void setDump(int type) {
20169            mTypes |= type;
20170        }
20171
20172        public boolean isOptionEnabled(int option) {
20173            return (mOptions & option) != 0;
20174        }
20175
20176        public void setOptionEnabled(int option) {
20177            mOptions |= option;
20178        }
20179
20180        public boolean onTitlePrinted() {
20181            final boolean printed = mTitlePrinted;
20182            mTitlePrinted = true;
20183            return printed;
20184        }
20185
20186        public boolean getTitlePrinted() {
20187            return mTitlePrinted;
20188        }
20189
20190        public void setTitlePrinted(boolean enabled) {
20191            mTitlePrinted = enabled;
20192        }
20193
20194        public SharedUserSetting getSharedUser() {
20195            return mSharedUser;
20196        }
20197
20198        public void setSharedUser(SharedUserSetting user) {
20199            mSharedUser = user;
20200        }
20201    }
20202
20203    @Override
20204    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20205            FileDescriptor err, String[] args, ShellCallback callback,
20206            ResultReceiver resultReceiver) {
20207        (new PackageManagerShellCommand(this)).exec(
20208                this, in, out, err, args, callback, resultReceiver);
20209    }
20210
20211    @Override
20212    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20213        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20214                != PackageManager.PERMISSION_GRANTED) {
20215            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20216                    + Binder.getCallingPid()
20217                    + ", uid=" + Binder.getCallingUid()
20218                    + " without permission "
20219                    + android.Manifest.permission.DUMP);
20220            return;
20221        }
20222
20223        DumpState dumpState = new DumpState();
20224        boolean fullPreferred = false;
20225        boolean checkin = false;
20226
20227        String packageName = null;
20228        ArraySet<String> permissionNames = null;
20229
20230        int opti = 0;
20231        while (opti < args.length) {
20232            String opt = args[opti];
20233            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20234                break;
20235            }
20236            opti++;
20237
20238            if ("-a".equals(opt)) {
20239                // Right now we only know how to print all.
20240            } else if ("-h".equals(opt)) {
20241                pw.println("Package manager dump options:");
20242                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20243                pw.println("    --checkin: dump for a checkin");
20244                pw.println("    -f: print details of intent filters");
20245                pw.println("    -h: print this help");
20246                pw.println("  cmd may be one of:");
20247                pw.println("    l[ibraries]: list known shared libraries");
20248                pw.println("    f[eatures]: list device features");
20249                pw.println("    k[eysets]: print known keysets");
20250                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20251                pw.println("    perm[issions]: dump permissions");
20252                pw.println("    permission [name ...]: dump declaration and use of given permission");
20253                pw.println("    pref[erred]: print preferred package settings");
20254                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20255                pw.println("    prov[iders]: dump content providers");
20256                pw.println("    p[ackages]: dump installed packages");
20257                pw.println("    s[hared-users]: dump shared user IDs");
20258                pw.println("    m[essages]: print collected runtime messages");
20259                pw.println("    v[erifiers]: print package verifier info");
20260                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20261                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20262                pw.println("    version: print database version info");
20263                pw.println("    write: write current settings now");
20264                pw.println("    installs: details about install sessions");
20265                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20266                pw.println("    dexopt: dump dexopt state");
20267                pw.println("    compiler-stats: dump compiler statistics");
20268                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20269                pw.println("    <package.name>: info about given package");
20270                return;
20271            } else if ("--checkin".equals(opt)) {
20272                checkin = true;
20273            } else if ("-f".equals(opt)) {
20274                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20275            } else if ("--proto".equals(opt)) {
20276                dumpProto(fd);
20277                return;
20278            } else {
20279                pw.println("Unknown argument: " + opt + "; use -h for help");
20280            }
20281        }
20282
20283        // Is the caller requesting to dump a particular piece of data?
20284        if (opti < args.length) {
20285            String cmd = args[opti];
20286            opti++;
20287            // Is this a package name?
20288            if ("android".equals(cmd) || cmd.contains(".")) {
20289                packageName = cmd;
20290                // When dumping a single package, we always dump all of its
20291                // filter information since the amount of data will be reasonable.
20292                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20293            } else if ("check-permission".equals(cmd)) {
20294                if (opti >= args.length) {
20295                    pw.println("Error: check-permission missing permission argument");
20296                    return;
20297                }
20298                String perm = args[opti];
20299                opti++;
20300                if (opti >= args.length) {
20301                    pw.println("Error: check-permission missing package argument");
20302                    return;
20303                }
20304
20305                String pkg = args[opti];
20306                opti++;
20307                int user = UserHandle.getUserId(Binder.getCallingUid());
20308                if (opti < args.length) {
20309                    try {
20310                        user = Integer.parseInt(args[opti]);
20311                    } catch (NumberFormatException e) {
20312                        pw.println("Error: check-permission user argument is not a number: "
20313                                + args[opti]);
20314                        return;
20315                    }
20316                }
20317
20318                // Normalize package name to handle renamed packages and static libs
20319                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20320
20321                pw.println(checkPermission(perm, pkg, user));
20322                return;
20323            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20324                dumpState.setDump(DumpState.DUMP_LIBS);
20325            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20326                dumpState.setDump(DumpState.DUMP_FEATURES);
20327            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20328                if (opti >= args.length) {
20329                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20330                            | DumpState.DUMP_SERVICE_RESOLVERS
20331                            | DumpState.DUMP_RECEIVER_RESOLVERS
20332                            | DumpState.DUMP_CONTENT_RESOLVERS);
20333                } else {
20334                    while (opti < args.length) {
20335                        String name = args[opti];
20336                        if ("a".equals(name) || "activity".equals(name)) {
20337                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20338                        } else if ("s".equals(name) || "service".equals(name)) {
20339                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20340                        } else if ("r".equals(name) || "receiver".equals(name)) {
20341                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20342                        } else if ("c".equals(name) || "content".equals(name)) {
20343                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20344                        } else {
20345                            pw.println("Error: unknown resolver table type: " + name);
20346                            return;
20347                        }
20348                        opti++;
20349                    }
20350                }
20351            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20352                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20353            } else if ("permission".equals(cmd)) {
20354                if (opti >= args.length) {
20355                    pw.println("Error: permission requires permission name");
20356                    return;
20357                }
20358                permissionNames = new ArraySet<>();
20359                while (opti < args.length) {
20360                    permissionNames.add(args[opti]);
20361                    opti++;
20362                }
20363                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20364                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20365            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20366                dumpState.setDump(DumpState.DUMP_PREFERRED);
20367            } else if ("preferred-xml".equals(cmd)) {
20368                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20369                if (opti < args.length && "--full".equals(args[opti])) {
20370                    fullPreferred = true;
20371                    opti++;
20372                }
20373            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20374                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20375            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20376                dumpState.setDump(DumpState.DUMP_PACKAGES);
20377            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20378                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20379            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20380                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20381            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20382                dumpState.setDump(DumpState.DUMP_MESSAGES);
20383            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20384                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20385            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20386                    || "intent-filter-verifiers".equals(cmd)) {
20387                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20388            } else if ("version".equals(cmd)) {
20389                dumpState.setDump(DumpState.DUMP_VERSION);
20390            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20391                dumpState.setDump(DumpState.DUMP_KEYSETS);
20392            } else if ("installs".equals(cmd)) {
20393                dumpState.setDump(DumpState.DUMP_INSTALLS);
20394            } else if ("frozen".equals(cmd)) {
20395                dumpState.setDump(DumpState.DUMP_FROZEN);
20396            } else if ("dexopt".equals(cmd)) {
20397                dumpState.setDump(DumpState.DUMP_DEXOPT);
20398            } else if ("compiler-stats".equals(cmd)) {
20399                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20400            } else if ("enabled-overlays".equals(cmd)) {
20401                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20402            } else if ("write".equals(cmd)) {
20403                synchronized (mPackages) {
20404                    mSettings.writeLPr();
20405                    pw.println("Settings written.");
20406                    return;
20407                }
20408            }
20409        }
20410
20411        if (checkin) {
20412            pw.println("vers,1");
20413        }
20414
20415        // reader
20416        synchronized (mPackages) {
20417            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20418                if (!checkin) {
20419                    if (dumpState.onTitlePrinted())
20420                        pw.println();
20421                    pw.println("Database versions:");
20422                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20423                }
20424            }
20425
20426            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20427                if (!checkin) {
20428                    if (dumpState.onTitlePrinted())
20429                        pw.println();
20430                    pw.println("Verifiers:");
20431                    pw.print("  Required: ");
20432                    pw.print(mRequiredVerifierPackage);
20433                    pw.print(" (uid=");
20434                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20435                            UserHandle.USER_SYSTEM));
20436                    pw.println(")");
20437                } else if (mRequiredVerifierPackage != null) {
20438                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20439                    pw.print(",");
20440                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20441                            UserHandle.USER_SYSTEM));
20442                }
20443            }
20444
20445            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20446                    packageName == null) {
20447                if (mIntentFilterVerifierComponent != null) {
20448                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20449                    if (!checkin) {
20450                        if (dumpState.onTitlePrinted())
20451                            pw.println();
20452                        pw.println("Intent Filter Verifier:");
20453                        pw.print("  Using: ");
20454                        pw.print(verifierPackageName);
20455                        pw.print(" (uid=");
20456                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20457                                UserHandle.USER_SYSTEM));
20458                        pw.println(")");
20459                    } else if (verifierPackageName != null) {
20460                        pw.print("ifv,"); pw.print(verifierPackageName);
20461                        pw.print(",");
20462                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20463                                UserHandle.USER_SYSTEM));
20464                    }
20465                } else {
20466                    pw.println();
20467                    pw.println("No Intent Filter Verifier available!");
20468                }
20469            }
20470
20471            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20472                boolean printedHeader = false;
20473                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20474                while (it.hasNext()) {
20475                    String libName = it.next();
20476                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20477                    if (versionedLib == null) {
20478                        continue;
20479                    }
20480                    final int versionCount = versionedLib.size();
20481                    for (int i = 0; i < versionCount; i++) {
20482                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20483                        if (!checkin) {
20484                            if (!printedHeader) {
20485                                if (dumpState.onTitlePrinted())
20486                                    pw.println();
20487                                pw.println("Libraries:");
20488                                printedHeader = true;
20489                            }
20490                            pw.print("  ");
20491                        } else {
20492                            pw.print("lib,");
20493                        }
20494                        pw.print(libEntry.info.getName());
20495                        if (libEntry.info.isStatic()) {
20496                            pw.print(" version=" + libEntry.info.getVersion());
20497                        }
20498                        if (!checkin) {
20499                            pw.print(" -> ");
20500                        }
20501                        if (libEntry.path != null) {
20502                            pw.print(" (jar) ");
20503                            pw.print(libEntry.path);
20504                        } else {
20505                            pw.print(" (apk) ");
20506                            pw.print(libEntry.apk);
20507                        }
20508                        pw.println();
20509                    }
20510                }
20511            }
20512
20513            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20514                if (dumpState.onTitlePrinted())
20515                    pw.println();
20516                if (!checkin) {
20517                    pw.println("Features:");
20518                }
20519
20520                synchronized (mAvailableFeatures) {
20521                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20522                        if (checkin) {
20523                            pw.print("feat,");
20524                            pw.print(feat.name);
20525                            pw.print(",");
20526                            pw.println(feat.version);
20527                        } else {
20528                            pw.print("  ");
20529                            pw.print(feat.name);
20530                            if (feat.version > 0) {
20531                                pw.print(" version=");
20532                                pw.print(feat.version);
20533                            }
20534                            pw.println();
20535                        }
20536                    }
20537                }
20538            }
20539
20540            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20541                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20542                        : "Activity Resolver Table:", "  ", packageName,
20543                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20544                    dumpState.setTitlePrinted(true);
20545                }
20546            }
20547            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20548                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20549                        : "Receiver Resolver Table:", "  ", packageName,
20550                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20551                    dumpState.setTitlePrinted(true);
20552                }
20553            }
20554            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20555                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20556                        : "Service Resolver Table:", "  ", packageName,
20557                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20558                    dumpState.setTitlePrinted(true);
20559                }
20560            }
20561            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20562                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20563                        : "Provider Resolver Table:", "  ", packageName,
20564                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20565                    dumpState.setTitlePrinted(true);
20566                }
20567            }
20568
20569            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20570                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20571                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20572                    int user = mSettings.mPreferredActivities.keyAt(i);
20573                    if (pir.dump(pw,
20574                            dumpState.getTitlePrinted()
20575                                ? "\nPreferred Activities User " + user + ":"
20576                                : "Preferred Activities User " + user + ":", "  ",
20577                            packageName, true, false)) {
20578                        dumpState.setTitlePrinted(true);
20579                    }
20580                }
20581            }
20582
20583            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20584                pw.flush();
20585                FileOutputStream fout = new FileOutputStream(fd);
20586                BufferedOutputStream str = new BufferedOutputStream(fout);
20587                XmlSerializer serializer = new FastXmlSerializer();
20588                try {
20589                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20590                    serializer.startDocument(null, true);
20591                    serializer.setFeature(
20592                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20593                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20594                    serializer.endDocument();
20595                    serializer.flush();
20596                } catch (IllegalArgumentException e) {
20597                    pw.println("Failed writing: " + e);
20598                } catch (IllegalStateException e) {
20599                    pw.println("Failed writing: " + e);
20600                } catch (IOException e) {
20601                    pw.println("Failed writing: " + e);
20602                }
20603            }
20604
20605            if (!checkin
20606                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20607                    && packageName == null) {
20608                pw.println();
20609                int count = mSettings.mPackages.size();
20610                if (count == 0) {
20611                    pw.println("No applications!");
20612                    pw.println();
20613                } else {
20614                    final String prefix = "  ";
20615                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20616                    if (allPackageSettings.size() == 0) {
20617                        pw.println("No domain preferred apps!");
20618                        pw.println();
20619                    } else {
20620                        pw.println("App verification status:");
20621                        pw.println();
20622                        count = 0;
20623                        for (PackageSetting ps : allPackageSettings) {
20624                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20625                            if (ivi == null || ivi.getPackageName() == null) continue;
20626                            pw.println(prefix + "Package: " + ivi.getPackageName());
20627                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20628                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20629                            pw.println();
20630                            count++;
20631                        }
20632                        if (count == 0) {
20633                            pw.println(prefix + "No app verification established.");
20634                            pw.println();
20635                        }
20636                        for (int userId : sUserManager.getUserIds()) {
20637                            pw.println("App linkages for user " + userId + ":");
20638                            pw.println();
20639                            count = 0;
20640                            for (PackageSetting ps : allPackageSettings) {
20641                                final long status = ps.getDomainVerificationStatusForUser(userId);
20642                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20643                                        && !DEBUG_DOMAIN_VERIFICATION) {
20644                                    continue;
20645                                }
20646                                pw.println(prefix + "Package: " + ps.name);
20647                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20648                                String statusStr = IntentFilterVerificationInfo.
20649                                        getStatusStringFromValue(status);
20650                                pw.println(prefix + "Status:  " + statusStr);
20651                                pw.println();
20652                                count++;
20653                            }
20654                            if (count == 0) {
20655                                pw.println(prefix + "No configured app linkages.");
20656                                pw.println();
20657                            }
20658                        }
20659                    }
20660                }
20661            }
20662
20663            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20664                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20665                if (packageName == null && permissionNames == null) {
20666                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20667                        if (iperm == 0) {
20668                            if (dumpState.onTitlePrinted())
20669                                pw.println();
20670                            pw.println("AppOp Permissions:");
20671                        }
20672                        pw.print("  AppOp Permission ");
20673                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20674                        pw.println(":");
20675                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20676                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20677                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20678                        }
20679                    }
20680                }
20681            }
20682
20683            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20684                boolean printedSomething = false;
20685                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20686                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20687                        continue;
20688                    }
20689                    if (!printedSomething) {
20690                        if (dumpState.onTitlePrinted())
20691                            pw.println();
20692                        pw.println("Registered ContentProviders:");
20693                        printedSomething = true;
20694                    }
20695                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20696                    pw.print("    "); pw.println(p.toString());
20697                }
20698                printedSomething = false;
20699                for (Map.Entry<String, PackageParser.Provider> entry :
20700                        mProvidersByAuthority.entrySet()) {
20701                    PackageParser.Provider p = entry.getValue();
20702                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20703                        continue;
20704                    }
20705                    if (!printedSomething) {
20706                        if (dumpState.onTitlePrinted())
20707                            pw.println();
20708                        pw.println("ContentProvider Authorities:");
20709                        printedSomething = true;
20710                    }
20711                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20712                    pw.print("    "); pw.println(p.toString());
20713                    if (p.info != null && p.info.applicationInfo != null) {
20714                        final String appInfo = p.info.applicationInfo.toString();
20715                        pw.print("      applicationInfo="); pw.println(appInfo);
20716                    }
20717                }
20718            }
20719
20720            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20721                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20722            }
20723
20724            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20725                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20726            }
20727
20728            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20729                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20730            }
20731
20732            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20733                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20734            }
20735
20736            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20737                // XXX should handle packageName != null by dumping only install data that
20738                // the given package is involved with.
20739                if (dumpState.onTitlePrinted()) pw.println();
20740                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20741            }
20742
20743            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20744                // XXX should handle packageName != null by dumping only install data that
20745                // the given package is involved with.
20746                if (dumpState.onTitlePrinted()) pw.println();
20747
20748                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20749                ipw.println();
20750                ipw.println("Frozen packages:");
20751                ipw.increaseIndent();
20752                if (mFrozenPackages.size() == 0) {
20753                    ipw.println("(none)");
20754                } else {
20755                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20756                        ipw.println(mFrozenPackages.valueAt(i));
20757                    }
20758                }
20759                ipw.decreaseIndent();
20760            }
20761
20762            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20763                if (dumpState.onTitlePrinted()) pw.println();
20764                dumpDexoptStateLPr(pw, packageName);
20765            }
20766
20767            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20768                if (dumpState.onTitlePrinted()) pw.println();
20769                dumpCompilerStatsLPr(pw, packageName);
20770            }
20771
20772            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20773                if (dumpState.onTitlePrinted()) pw.println();
20774                dumpEnabledOverlaysLPr(pw);
20775            }
20776
20777            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20778                if (dumpState.onTitlePrinted()) pw.println();
20779                mSettings.dumpReadMessagesLPr(pw, dumpState);
20780
20781                pw.println();
20782                pw.println("Package warning messages:");
20783                BufferedReader in = null;
20784                String line = null;
20785                try {
20786                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20787                    while ((line = in.readLine()) != null) {
20788                        if (line.contains("ignored: updated version")) continue;
20789                        pw.println(line);
20790                    }
20791                } catch (IOException ignored) {
20792                } finally {
20793                    IoUtils.closeQuietly(in);
20794                }
20795            }
20796
20797            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20798                BufferedReader in = null;
20799                String line = null;
20800                try {
20801                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20802                    while ((line = in.readLine()) != null) {
20803                        if (line.contains("ignored: updated version")) continue;
20804                        pw.print("msg,");
20805                        pw.println(line);
20806                    }
20807                } catch (IOException ignored) {
20808                } finally {
20809                    IoUtils.closeQuietly(in);
20810                }
20811            }
20812        }
20813    }
20814
20815    private void dumpProto(FileDescriptor fd) {
20816        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20817
20818        synchronized (mPackages) {
20819            final long requiredVerifierPackageToken =
20820                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20821            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20822            proto.write(
20823                    PackageServiceDumpProto.PackageShortProto.UID,
20824                    getPackageUid(
20825                            mRequiredVerifierPackage,
20826                            MATCH_DEBUG_TRIAGED_MISSING,
20827                            UserHandle.USER_SYSTEM));
20828            proto.end(requiredVerifierPackageToken);
20829
20830            if (mIntentFilterVerifierComponent != null) {
20831                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20832                final long verifierPackageToken =
20833                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20834                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20835                proto.write(
20836                        PackageServiceDumpProto.PackageShortProto.UID,
20837                        getPackageUid(
20838                                verifierPackageName,
20839                                MATCH_DEBUG_TRIAGED_MISSING,
20840                                UserHandle.USER_SYSTEM));
20841                proto.end(verifierPackageToken);
20842            }
20843
20844            dumpSharedLibrariesProto(proto);
20845            dumpFeaturesProto(proto);
20846            mSettings.dumpPackagesProto(proto);
20847            mSettings.dumpSharedUsersProto(proto);
20848            dumpMessagesProto(proto);
20849        }
20850        proto.flush();
20851    }
20852
20853    private void dumpMessagesProto(ProtoOutputStream proto) {
20854        BufferedReader in = null;
20855        String line = null;
20856        try {
20857            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20858            while ((line = in.readLine()) != null) {
20859                if (line.contains("ignored: updated version")) continue;
20860                proto.write(PackageServiceDumpProto.MESSAGES, line);
20861            }
20862        } catch (IOException ignored) {
20863        } finally {
20864            IoUtils.closeQuietly(in);
20865        }
20866    }
20867
20868    private void dumpFeaturesProto(ProtoOutputStream proto) {
20869        synchronized (mAvailableFeatures) {
20870            final int count = mAvailableFeatures.size();
20871            for (int i = 0; i < count; i++) {
20872                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
20873                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
20874                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
20875                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
20876                proto.end(featureToken);
20877            }
20878        }
20879    }
20880
20881    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20882        final int count = mSharedLibraries.size();
20883        for (int i = 0; i < count; i++) {
20884            final String libName = mSharedLibraries.keyAt(i);
20885            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20886            if (versionedLib == null) {
20887                continue;
20888            }
20889            final int versionCount = versionedLib.size();
20890            for (int j = 0; j < versionCount; j++) {
20891                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20892                final long sharedLibraryToken =
20893                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20894                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20895                final boolean isJar = (libEntry.path != null);
20896                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20897                if (isJar) {
20898                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20899                } else {
20900                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20901                }
20902                proto.end(sharedLibraryToken);
20903            }
20904        }
20905    }
20906
20907    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20908        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20909        ipw.println();
20910        ipw.println("Dexopt state:");
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            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20929            ipw.decreaseIndent();
20930        }
20931    }
20932
20933    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20934        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20935        ipw.println();
20936        ipw.println("Compiler stats:");
20937        ipw.increaseIndent();
20938        Collection<PackageParser.Package> packages = null;
20939        if (packageName != null) {
20940            PackageParser.Package targetPackage = mPackages.get(packageName);
20941            if (targetPackage != null) {
20942                packages = Collections.singletonList(targetPackage);
20943            } else {
20944                ipw.println("Unable to find package: " + packageName);
20945                return;
20946            }
20947        } else {
20948            packages = mPackages.values();
20949        }
20950
20951        for (PackageParser.Package pkg : packages) {
20952            ipw.println("[" + pkg.packageName + "]");
20953            ipw.increaseIndent();
20954
20955            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20956            if (stats == null) {
20957                ipw.println("(No recorded stats)");
20958            } else {
20959                stats.dump(ipw);
20960            }
20961            ipw.decreaseIndent();
20962        }
20963    }
20964
20965    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
20966        pw.println("Enabled overlay paths:");
20967        final int N = mEnabledOverlayPaths.size();
20968        for (int i = 0; i < N; i++) {
20969            final int userId = mEnabledOverlayPaths.keyAt(i);
20970            pw.println(String.format("    User %d:", userId));
20971            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
20972                mEnabledOverlayPaths.valueAt(i);
20973            final int M = userSpecificOverlays.size();
20974            for (int j = 0; j < M; j++) {
20975                final String targetPackageName = userSpecificOverlays.keyAt(j);
20976                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
20977                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
20978            }
20979        }
20980    }
20981
20982    private String dumpDomainString(String packageName) {
20983        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20984                .getList();
20985        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20986
20987        ArraySet<String> result = new ArraySet<>();
20988        if (iviList.size() > 0) {
20989            for (IntentFilterVerificationInfo ivi : iviList) {
20990                for (String host : ivi.getDomains()) {
20991                    result.add(host);
20992                }
20993            }
20994        }
20995        if (filters != null && filters.size() > 0) {
20996            for (IntentFilter filter : filters) {
20997                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20998                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20999                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21000                    result.addAll(filter.getHostsList());
21001                }
21002            }
21003        }
21004
21005        StringBuilder sb = new StringBuilder(result.size() * 16);
21006        for (String domain : result) {
21007            if (sb.length() > 0) sb.append(" ");
21008            sb.append(domain);
21009        }
21010        return sb.toString();
21011    }
21012
21013    // ------- apps on sdcard specific code -------
21014    static final boolean DEBUG_SD_INSTALL = false;
21015
21016    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21017
21018    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21019
21020    private boolean mMediaMounted = false;
21021
21022    static String getEncryptKey() {
21023        try {
21024            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21025                    SD_ENCRYPTION_KEYSTORE_NAME);
21026            if (sdEncKey == null) {
21027                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21028                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21029                if (sdEncKey == null) {
21030                    Slog.e(TAG, "Failed to create encryption keys");
21031                    return null;
21032                }
21033            }
21034            return sdEncKey;
21035        } catch (NoSuchAlgorithmException nsae) {
21036            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21037            return null;
21038        } catch (IOException ioe) {
21039            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21040            return null;
21041        }
21042    }
21043
21044    /*
21045     * Update media status on PackageManager.
21046     */
21047    @Override
21048    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21049        int callingUid = Binder.getCallingUid();
21050        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21051            throw new SecurityException("Media status can only be updated by the system");
21052        }
21053        // reader; this apparently protects mMediaMounted, but should probably
21054        // be a different lock in that case.
21055        synchronized (mPackages) {
21056            Log.i(TAG, "Updating external media status from "
21057                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21058                    + (mediaStatus ? "mounted" : "unmounted"));
21059            if (DEBUG_SD_INSTALL)
21060                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21061                        + ", mMediaMounted=" + mMediaMounted);
21062            if (mediaStatus == mMediaMounted) {
21063                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21064                        : 0, -1);
21065                mHandler.sendMessage(msg);
21066                return;
21067            }
21068            mMediaMounted = mediaStatus;
21069        }
21070        // Queue up an async operation since the package installation may take a
21071        // little while.
21072        mHandler.post(new Runnable() {
21073            public void run() {
21074                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21075            }
21076        });
21077    }
21078
21079    /**
21080     * Called by StorageManagerService when the initial ASECs to scan are available.
21081     * Should block until all the ASEC containers are finished being scanned.
21082     */
21083    public void scanAvailableAsecs() {
21084        updateExternalMediaStatusInner(true, false, false);
21085    }
21086
21087    /*
21088     * Collect information of applications on external media, map them against
21089     * existing containers and update information based on current mount status.
21090     * Please note that we always have to report status if reportStatus has been
21091     * set to true especially when unloading packages.
21092     */
21093    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21094            boolean externalStorage) {
21095        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21096        int[] uidArr = EmptyArray.INT;
21097
21098        final String[] list = PackageHelper.getSecureContainerList();
21099        if (ArrayUtils.isEmpty(list)) {
21100            Log.i(TAG, "No secure containers found");
21101        } else {
21102            // Process list of secure containers and categorize them
21103            // as active or stale based on their package internal state.
21104
21105            // reader
21106            synchronized (mPackages) {
21107                for (String cid : list) {
21108                    // Leave stages untouched for now; installer service owns them
21109                    if (PackageInstallerService.isStageName(cid)) continue;
21110
21111                    if (DEBUG_SD_INSTALL)
21112                        Log.i(TAG, "Processing container " + cid);
21113                    String pkgName = getAsecPackageName(cid);
21114                    if (pkgName == null) {
21115                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21116                        continue;
21117                    }
21118                    if (DEBUG_SD_INSTALL)
21119                        Log.i(TAG, "Looking for pkg : " + pkgName);
21120
21121                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21122                    if (ps == null) {
21123                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21124                        continue;
21125                    }
21126
21127                    /*
21128                     * Skip packages that are not external if we're unmounting
21129                     * external storage.
21130                     */
21131                    if (externalStorage && !isMounted && !isExternal(ps)) {
21132                        continue;
21133                    }
21134
21135                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21136                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21137                    // The package status is changed only if the code path
21138                    // matches between settings and the container id.
21139                    if (ps.codePathString != null
21140                            && ps.codePathString.startsWith(args.getCodePath())) {
21141                        if (DEBUG_SD_INSTALL) {
21142                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21143                                    + " at code path: " + ps.codePathString);
21144                        }
21145
21146                        // We do have a valid package installed on sdcard
21147                        processCids.put(args, ps.codePathString);
21148                        final int uid = ps.appId;
21149                        if (uid != -1) {
21150                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21151                        }
21152                    } else {
21153                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21154                                + ps.codePathString);
21155                    }
21156                }
21157            }
21158
21159            Arrays.sort(uidArr);
21160        }
21161
21162        // Process packages with valid entries.
21163        if (isMounted) {
21164            if (DEBUG_SD_INSTALL)
21165                Log.i(TAG, "Loading packages");
21166            loadMediaPackages(processCids, uidArr, externalStorage);
21167            startCleaningPackages();
21168            mInstallerService.onSecureContainersAvailable();
21169        } else {
21170            if (DEBUG_SD_INSTALL)
21171                Log.i(TAG, "Unloading packages");
21172            unloadMediaPackages(processCids, uidArr, reportStatus);
21173        }
21174    }
21175
21176    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21177            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21178        final int size = infos.size();
21179        final String[] packageNames = new String[size];
21180        final int[] packageUids = new int[size];
21181        for (int i = 0; i < size; i++) {
21182            final ApplicationInfo info = infos.get(i);
21183            packageNames[i] = info.packageName;
21184            packageUids[i] = info.uid;
21185        }
21186        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21187                finishedReceiver);
21188    }
21189
21190    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21191            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21192        sendResourcesChangedBroadcast(mediaStatus, replacing,
21193                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21194    }
21195
21196    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21197            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21198        int size = pkgList.length;
21199        if (size > 0) {
21200            // Send broadcasts here
21201            Bundle extras = new Bundle();
21202            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21203            if (uidArr != null) {
21204                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21205            }
21206            if (replacing) {
21207                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21208            }
21209            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21210                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21211            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21212        }
21213    }
21214
21215   /*
21216     * Look at potentially valid container ids from processCids If package
21217     * information doesn't match the one on record or package scanning fails,
21218     * the cid is added to list of removeCids. We currently don't delete stale
21219     * containers.
21220     */
21221    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21222            boolean externalStorage) {
21223        ArrayList<String> pkgList = new ArrayList<String>();
21224        Set<AsecInstallArgs> keys = processCids.keySet();
21225
21226        for (AsecInstallArgs args : keys) {
21227            String codePath = processCids.get(args);
21228            if (DEBUG_SD_INSTALL)
21229                Log.i(TAG, "Loading container : " + args.cid);
21230            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21231            try {
21232                // Make sure there are no container errors first.
21233                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21234                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21235                            + " when installing from sdcard");
21236                    continue;
21237                }
21238                // Check code path here.
21239                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21240                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21241                            + " does not match one in settings " + codePath);
21242                    continue;
21243                }
21244                // Parse package
21245                int parseFlags = mDefParseFlags;
21246                if (args.isExternalAsec()) {
21247                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21248                }
21249                if (args.isFwdLocked()) {
21250                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21251                }
21252
21253                synchronized (mInstallLock) {
21254                    PackageParser.Package pkg = null;
21255                    try {
21256                        // Sadly we don't know the package name yet to freeze it
21257                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21258                                SCAN_IGNORE_FROZEN, 0, null);
21259                    } catch (PackageManagerException e) {
21260                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21261                    }
21262                    // Scan the package
21263                    if (pkg != null) {
21264                        /*
21265                         * TODO why is the lock being held? doPostInstall is
21266                         * called in other places without the lock. This needs
21267                         * to be straightened out.
21268                         */
21269                        // writer
21270                        synchronized (mPackages) {
21271                            retCode = PackageManager.INSTALL_SUCCEEDED;
21272                            pkgList.add(pkg.packageName);
21273                            // Post process args
21274                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21275                                    pkg.applicationInfo.uid);
21276                        }
21277                    } else {
21278                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21279                    }
21280                }
21281
21282            } finally {
21283                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21284                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21285                }
21286            }
21287        }
21288        // writer
21289        synchronized (mPackages) {
21290            // If the platform SDK has changed since the last time we booted,
21291            // we need to re-grant app permission to catch any new ones that
21292            // appear. This is really a hack, and means that apps can in some
21293            // cases get permissions that the user didn't initially explicitly
21294            // allow... it would be nice to have some better way to handle
21295            // this situation.
21296            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21297                    : mSettings.getInternalVersion();
21298            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21299                    : StorageManager.UUID_PRIVATE_INTERNAL;
21300
21301            int updateFlags = UPDATE_PERMISSIONS_ALL;
21302            if (ver.sdkVersion != mSdkVersion) {
21303                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21304                        + mSdkVersion + "; regranting permissions for external");
21305                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21306            }
21307            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21308
21309            // Yay, everything is now upgraded
21310            ver.forceCurrent();
21311
21312            // can downgrade to reader
21313            // Persist settings
21314            mSettings.writeLPr();
21315        }
21316        // Send a broadcast to let everyone know we are done processing
21317        if (pkgList.size() > 0) {
21318            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21319        }
21320    }
21321
21322   /*
21323     * Utility method to unload a list of specified containers
21324     */
21325    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21326        // Just unmount all valid containers.
21327        for (AsecInstallArgs arg : cidArgs) {
21328            synchronized (mInstallLock) {
21329                arg.doPostDeleteLI(false);
21330           }
21331       }
21332   }
21333
21334    /*
21335     * Unload packages mounted on external media. This involves deleting package
21336     * data from internal structures, sending broadcasts about disabled packages,
21337     * gc'ing to free up references, unmounting all secure containers
21338     * corresponding to packages on external media, and posting a
21339     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21340     * that we always have to post this message if status has been requested no
21341     * matter what.
21342     */
21343    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21344            final boolean reportStatus) {
21345        if (DEBUG_SD_INSTALL)
21346            Log.i(TAG, "unloading media packages");
21347        ArrayList<String> pkgList = new ArrayList<String>();
21348        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21349        final Set<AsecInstallArgs> keys = processCids.keySet();
21350        for (AsecInstallArgs args : keys) {
21351            String pkgName = args.getPackageName();
21352            if (DEBUG_SD_INSTALL)
21353                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21354            // Delete package internally
21355            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21356            synchronized (mInstallLock) {
21357                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21358                final boolean res;
21359                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21360                        "unloadMediaPackages")) {
21361                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21362                            null);
21363                }
21364                if (res) {
21365                    pkgList.add(pkgName);
21366                } else {
21367                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21368                    failedList.add(args);
21369                }
21370            }
21371        }
21372
21373        // reader
21374        synchronized (mPackages) {
21375            // We didn't update the settings after removing each package;
21376            // write them now for all packages.
21377            mSettings.writeLPr();
21378        }
21379
21380        // We have to absolutely send UPDATED_MEDIA_STATUS only
21381        // after confirming that all the receivers processed the ordered
21382        // broadcast when packages get disabled, force a gc to clean things up.
21383        // and unload all the containers.
21384        if (pkgList.size() > 0) {
21385            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21386                    new IIntentReceiver.Stub() {
21387                public void performReceive(Intent intent, int resultCode, String data,
21388                        Bundle extras, boolean ordered, boolean sticky,
21389                        int sendingUser) throws RemoteException {
21390                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21391                            reportStatus ? 1 : 0, 1, keys);
21392                    mHandler.sendMessage(msg);
21393                }
21394            });
21395        } else {
21396            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21397                    keys);
21398            mHandler.sendMessage(msg);
21399        }
21400    }
21401
21402    private void loadPrivatePackages(final VolumeInfo vol) {
21403        mHandler.post(new Runnable() {
21404            @Override
21405            public void run() {
21406                loadPrivatePackagesInner(vol);
21407            }
21408        });
21409    }
21410
21411    private void loadPrivatePackagesInner(VolumeInfo vol) {
21412        final String volumeUuid = vol.fsUuid;
21413        if (TextUtils.isEmpty(volumeUuid)) {
21414            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21415            return;
21416        }
21417
21418        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21419        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21420        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21421
21422        final VersionInfo ver;
21423        final List<PackageSetting> packages;
21424        synchronized (mPackages) {
21425            ver = mSettings.findOrCreateVersion(volumeUuid);
21426            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21427        }
21428
21429        for (PackageSetting ps : packages) {
21430            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21431            synchronized (mInstallLock) {
21432                final PackageParser.Package pkg;
21433                try {
21434                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21435                    loaded.add(pkg.applicationInfo);
21436
21437                } catch (PackageManagerException e) {
21438                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21439                }
21440
21441                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21442                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21443                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21444                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21445                }
21446            }
21447        }
21448
21449        // Reconcile app data for all started/unlocked users
21450        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21451        final UserManager um = mContext.getSystemService(UserManager.class);
21452        UserManagerInternal umInternal = getUserManagerInternal();
21453        for (UserInfo user : um.getUsers()) {
21454            final int flags;
21455            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21456                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21457            } else if (umInternal.isUserRunning(user.id)) {
21458                flags = StorageManager.FLAG_STORAGE_DE;
21459            } else {
21460                continue;
21461            }
21462
21463            try {
21464                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21465                synchronized (mInstallLock) {
21466                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21467                }
21468            } catch (IllegalStateException e) {
21469                // Device was probably ejected, and we'll process that event momentarily
21470                Slog.w(TAG, "Failed to prepare storage: " + e);
21471            }
21472        }
21473
21474        synchronized (mPackages) {
21475            int updateFlags = UPDATE_PERMISSIONS_ALL;
21476            if (ver.sdkVersion != mSdkVersion) {
21477                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21478                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21479                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21480            }
21481            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21482
21483            // Yay, everything is now upgraded
21484            ver.forceCurrent();
21485
21486            mSettings.writeLPr();
21487        }
21488
21489        for (PackageFreezer freezer : freezers) {
21490            freezer.close();
21491        }
21492
21493        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21494        sendResourcesChangedBroadcast(true, false, loaded, null);
21495    }
21496
21497    private void unloadPrivatePackages(final VolumeInfo vol) {
21498        mHandler.post(new Runnable() {
21499            @Override
21500            public void run() {
21501                unloadPrivatePackagesInner(vol);
21502            }
21503        });
21504    }
21505
21506    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21507        final String volumeUuid = vol.fsUuid;
21508        if (TextUtils.isEmpty(volumeUuid)) {
21509            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21510            return;
21511        }
21512
21513        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21514        synchronized (mInstallLock) {
21515        synchronized (mPackages) {
21516            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21517            for (PackageSetting ps : packages) {
21518                if (ps.pkg == null) continue;
21519
21520                final ApplicationInfo info = ps.pkg.applicationInfo;
21521                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21522                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21523
21524                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21525                        "unloadPrivatePackagesInner")) {
21526                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21527                            false, null)) {
21528                        unloaded.add(info);
21529                    } else {
21530                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21531                    }
21532                }
21533
21534                // Try very hard to release any references to this package
21535                // so we don't risk the system server being killed due to
21536                // open FDs
21537                AttributeCache.instance().removePackage(ps.name);
21538            }
21539
21540            mSettings.writeLPr();
21541        }
21542        }
21543
21544        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21545        sendResourcesChangedBroadcast(false, false, unloaded, null);
21546
21547        // Try very hard to release any references to this path so we don't risk
21548        // the system server being killed due to open FDs
21549        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21550
21551        for (int i = 0; i < 3; i++) {
21552            System.gc();
21553            System.runFinalization();
21554        }
21555    }
21556
21557    private void assertPackageKnown(String volumeUuid, String packageName)
21558            throws PackageManagerException {
21559        synchronized (mPackages) {
21560            // Normalize package name to handle renamed packages
21561            packageName = normalizePackageNameLPr(packageName);
21562
21563            final PackageSetting ps = mSettings.mPackages.get(packageName);
21564            if (ps == null) {
21565                throw new PackageManagerException("Package " + packageName + " is unknown");
21566            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21567                throw new PackageManagerException(
21568                        "Package " + packageName + " found on unknown volume " + volumeUuid
21569                                + "; expected volume " + ps.volumeUuid);
21570            }
21571        }
21572    }
21573
21574    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21575            throws PackageManagerException {
21576        synchronized (mPackages) {
21577            // Normalize package name to handle renamed packages
21578            packageName = normalizePackageNameLPr(packageName);
21579
21580            final PackageSetting ps = mSettings.mPackages.get(packageName);
21581            if (ps == null) {
21582                throw new PackageManagerException("Package " + packageName + " is unknown");
21583            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21584                throw new PackageManagerException(
21585                        "Package " + packageName + " found on unknown volume " + volumeUuid
21586                                + "; expected volume " + ps.volumeUuid);
21587            } else if (!ps.getInstalled(userId)) {
21588                throw new PackageManagerException(
21589                        "Package " + packageName + " not installed for user " + userId);
21590            }
21591        }
21592    }
21593
21594    private List<String> collectAbsoluteCodePaths() {
21595        synchronized (mPackages) {
21596            List<String> codePaths = new ArrayList<>();
21597            final int packageCount = mSettings.mPackages.size();
21598            for (int i = 0; i < packageCount; i++) {
21599                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21600                codePaths.add(ps.codePath.getAbsolutePath());
21601            }
21602            return codePaths;
21603        }
21604    }
21605
21606    /**
21607     * Examine all apps present on given mounted volume, and destroy apps that
21608     * aren't expected, either due to uninstallation or reinstallation on
21609     * another volume.
21610     */
21611    private void reconcileApps(String volumeUuid) {
21612        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21613        List<File> filesToDelete = null;
21614
21615        final File[] files = FileUtils.listFilesOrEmpty(
21616                Environment.getDataAppDirectory(volumeUuid));
21617        for (File file : files) {
21618            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21619                    && !PackageInstallerService.isStageName(file.getName());
21620            if (!isPackage) {
21621                // Ignore entries which are not packages
21622                continue;
21623            }
21624
21625            String absolutePath = file.getAbsolutePath();
21626
21627            boolean pathValid = false;
21628            final int absoluteCodePathCount = absoluteCodePaths.size();
21629            for (int i = 0; i < absoluteCodePathCount; i++) {
21630                String absoluteCodePath = absoluteCodePaths.get(i);
21631                if (absolutePath.startsWith(absoluteCodePath)) {
21632                    pathValid = true;
21633                    break;
21634                }
21635            }
21636
21637            if (!pathValid) {
21638                if (filesToDelete == null) {
21639                    filesToDelete = new ArrayList<>();
21640                }
21641                filesToDelete.add(file);
21642            }
21643        }
21644
21645        if (filesToDelete != null) {
21646            final int fileToDeleteCount = filesToDelete.size();
21647            for (int i = 0; i < fileToDeleteCount; i++) {
21648                File fileToDelete = filesToDelete.get(i);
21649                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21650                synchronized (mInstallLock) {
21651                    removeCodePathLI(fileToDelete);
21652                }
21653            }
21654        }
21655    }
21656
21657    /**
21658     * Reconcile all app data for the given user.
21659     * <p>
21660     * Verifies that directories exist and that ownership and labeling is
21661     * correct for all installed apps on all mounted volumes.
21662     */
21663    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21664        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21665        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21666            final String volumeUuid = vol.getFsUuid();
21667            synchronized (mInstallLock) {
21668                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21669            }
21670        }
21671    }
21672
21673    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21674            boolean migrateAppData) {
21675        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21676    }
21677
21678    /**
21679     * Reconcile all app data on given mounted volume.
21680     * <p>
21681     * Destroys app data that isn't expected, either due to uninstallation or
21682     * reinstallation on another volume.
21683     * <p>
21684     * Verifies that directories exist and that ownership and labeling is
21685     * correct for all installed apps.
21686     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21687     */
21688    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21689            boolean migrateAppData, boolean onlyCoreApps) {
21690        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21691                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21692        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21693
21694        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21695        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21696
21697        // First look for stale data that doesn't belong, and check if things
21698        // have changed since we did our last restorecon
21699        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21700            if (StorageManager.isFileEncryptedNativeOrEmulated()
21701                    && !StorageManager.isUserKeyUnlocked(userId)) {
21702                throw new RuntimeException(
21703                        "Yikes, someone asked us to reconcile CE storage while " + userId
21704                                + " was still locked; this would have caused massive data loss!");
21705            }
21706
21707            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21708            for (File file : files) {
21709                final String packageName = file.getName();
21710                try {
21711                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21712                } catch (PackageManagerException e) {
21713                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21714                    try {
21715                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21716                                StorageManager.FLAG_STORAGE_CE, 0);
21717                    } catch (InstallerException e2) {
21718                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21719                    }
21720                }
21721            }
21722        }
21723        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21724            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21725            for (File file : files) {
21726                final String packageName = file.getName();
21727                try {
21728                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21729                } catch (PackageManagerException e) {
21730                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21731                    try {
21732                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21733                                StorageManager.FLAG_STORAGE_DE, 0);
21734                    } catch (InstallerException e2) {
21735                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21736                    }
21737                }
21738            }
21739        }
21740
21741        // Ensure that data directories are ready to roll for all packages
21742        // installed for this volume and user
21743        final List<PackageSetting> packages;
21744        synchronized (mPackages) {
21745            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21746        }
21747        int preparedCount = 0;
21748        for (PackageSetting ps : packages) {
21749            final String packageName = ps.name;
21750            if (ps.pkg == null) {
21751                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21752                // TODO: might be due to legacy ASEC apps; we should circle back
21753                // and reconcile again once they're scanned
21754                continue;
21755            }
21756            // Skip non-core apps if requested
21757            if (onlyCoreApps && !ps.pkg.coreApp) {
21758                result.add(packageName);
21759                continue;
21760            }
21761
21762            if (ps.getInstalled(userId)) {
21763                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21764                preparedCount++;
21765            }
21766        }
21767
21768        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21769        return result;
21770    }
21771
21772    /**
21773     * Prepare app data for the given app just after it was installed or
21774     * upgraded. This method carefully only touches users that it's installed
21775     * for, and it forces a restorecon to handle any seinfo changes.
21776     * <p>
21777     * Verifies that directories exist and that ownership and labeling is
21778     * correct for all installed apps. If there is an ownership mismatch, it
21779     * will try recovering system apps by wiping data; third-party app data is
21780     * left intact.
21781     * <p>
21782     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21783     */
21784    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21785        final PackageSetting ps;
21786        synchronized (mPackages) {
21787            ps = mSettings.mPackages.get(pkg.packageName);
21788            mSettings.writeKernelMappingLPr(ps);
21789        }
21790
21791        final UserManager um = mContext.getSystemService(UserManager.class);
21792        UserManagerInternal umInternal = getUserManagerInternal();
21793        for (UserInfo user : um.getUsers()) {
21794            final int flags;
21795            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21796                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21797            } else if (umInternal.isUserRunning(user.id)) {
21798                flags = StorageManager.FLAG_STORAGE_DE;
21799            } else {
21800                continue;
21801            }
21802
21803            if (ps.getInstalled(user.id)) {
21804                // TODO: when user data is locked, mark that we're still dirty
21805                prepareAppDataLIF(pkg, user.id, flags);
21806            }
21807        }
21808    }
21809
21810    /**
21811     * Prepare app data for the given app.
21812     * <p>
21813     * Verifies that directories exist and that ownership and labeling is
21814     * correct for all installed apps. If there is an ownership mismatch, this
21815     * will try recovering system apps by wiping data; third-party app data is
21816     * left intact.
21817     */
21818    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21819        if (pkg == null) {
21820            Slog.wtf(TAG, "Package was null!", new Throwable());
21821            return;
21822        }
21823        prepareAppDataLeafLIF(pkg, userId, flags);
21824        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21825        for (int i = 0; i < childCount; i++) {
21826            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21827        }
21828    }
21829
21830    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21831            boolean maybeMigrateAppData) {
21832        prepareAppDataLIF(pkg, userId, flags);
21833
21834        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21835            // We may have just shuffled around app data directories, so
21836            // prepare them one more time
21837            prepareAppDataLIF(pkg, userId, flags);
21838        }
21839    }
21840
21841    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21842        if (DEBUG_APP_DATA) {
21843            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21844                    + Integer.toHexString(flags));
21845        }
21846
21847        final String volumeUuid = pkg.volumeUuid;
21848        final String packageName = pkg.packageName;
21849        final ApplicationInfo app = pkg.applicationInfo;
21850        final int appId = UserHandle.getAppId(app.uid);
21851
21852        Preconditions.checkNotNull(app.seInfo);
21853
21854        long ceDataInode = -1;
21855        try {
21856            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21857                    appId, app.seInfo, app.targetSdkVersion);
21858        } catch (InstallerException e) {
21859            if (app.isSystemApp()) {
21860                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21861                        + ", but trying to recover: " + e);
21862                destroyAppDataLeafLIF(pkg, userId, flags);
21863                try {
21864                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21865                            appId, app.seInfo, app.targetSdkVersion);
21866                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21867                } catch (InstallerException e2) {
21868                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21869                }
21870            } else {
21871                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21872            }
21873        }
21874
21875        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21876            // TODO: mark this structure as dirty so we persist it!
21877            synchronized (mPackages) {
21878                final PackageSetting ps = mSettings.mPackages.get(packageName);
21879                if (ps != null) {
21880                    ps.setCeDataInode(ceDataInode, userId);
21881                }
21882            }
21883        }
21884
21885        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21886    }
21887
21888    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21889        if (pkg == null) {
21890            Slog.wtf(TAG, "Package was null!", new Throwable());
21891            return;
21892        }
21893        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21894        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21895        for (int i = 0; i < childCount; i++) {
21896            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21897        }
21898    }
21899
21900    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21901        final String volumeUuid = pkg.volumeUuid;
21902        final String packageName = pkg.packageName;
21903        final ApplicationInfo app = pkg.applicationInfo;
21904
21905        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21906            // Create a native library symlink only if we have native libraries
21907            // and if the native libraries are 32 bit libraries. We do not provide
21908            // this symlink for 64 bit libraries.
21909            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21910                final String nativeLibPath = app.nativeLibraryDir;
21911                try {
21912                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21913                            nativeLibPath, userId);
21914                } catch (InstallerException e) {
21915                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21916                }
21917            }
21918        }
21919    }
21920
21921    /**
21922     * For system apps on non-FBE devices, this method migrates any existing
21923     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21924     * requested by the app.
21925     */
21926    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21927        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21928                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21929            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21930                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21931            try {
21932                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21933                        storageTarget);
21934            } catch (InstallerException e) {
21935                logCriticalInfo(Log.WARN,
21936                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21937            }
21938            return true;
21939        } else {
21940            return false;
21941        }
21942    }
21943
21944    public PackageFreezer freezePackage(String packageName, String killReason) {
21945        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21946    }
21947
21948    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21949        return new PackageFreezer(packageName, userId, killReason);
21950    }
21951
21952    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21953            String killReason) {
21954        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21955    }
21956
21957    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21958            String killReason) {
21959        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21960            return new PackageFreezer();
21961        } else {
21962            return freezePackage(packageName, userId, killReason);
21963        }
21964    }
21965
21966    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21967            String killReason) {
21968        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21969    }
21970
21971    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21972            String killReason) {
21973        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21974            return new PackageFreezer();
21975        } else {
21976            return freezePackage(packageName, userId, killReason);
21977        }
21978    }
21979
21980    /**
21981     * Class that freezes and kills the given package upon creation, and
21982     * unfreezes it upon closing. This is typically used when doing surgery on
21983     * app code/data to prevent the app from running while you're working.
21984     */
21985    private class PackageFreezer implements AutoCloseable {
21986        private final String mPackageName;
21987        private final PackageFreezer[] mChildren;
21988
21989        private final boolean mWeFroze;
21990
21991        private final AtomicBoolean mClosed = new AtomicBoolean();
21992        private final CloseGuard mCloseGuard = CloseGuard.get();
21993
21994        /**
21995         * Create and return a stub freezer that doesn't actually do anything,
21996         * typically used when someone requested
21997         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21998         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21999         */
22000        public PackageFreezer() {
22001            mPackageName = null;
22002            mChildren = null;
22003            mWeFroze = false;
22004            mCloseGuard.open("close");
22005        }
22006
22007        public PackageFreezer(String packageName, int userId, String killReason) {
22008            synchronized (mPackages) {
22009                mPackageName = packageName;
22010                mWeFroze = mFrozenPackages.add(mPackageName);
22011
22012                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22013                if (ps != null) {
22014                    killApplication(ps.name, ps.appId, userId, killReason);
22015                }
22016
22017                final PackageParser.Package p = mPackages.get(packageName);
22018                if (p != null && p.childPackages != null) {
22019                    final int N = p.childPackages.size();
22020                    mChildren = new PackageFreezer[N];
22021                    for (int i = 0; i < N; i++) {
22022                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22023                                userId, killReason);
22024                    }
22025                } else {
22026                    mChildren = null;
22027                }
22028            }
22029            mCloseGuard.open("close");
22030        }
22031
22032        @Override
22033        protected void finalize() throws Throwable {
22034            try {
22035                mCloseGuard.warnIfOpen();
22036                close();
22037            } finally {
22038                super.finalize();
22039            }
22040        }
22041
22042        @Override
22043        public void close() {
22044            mCloseGuard.close();
22045            if (mClosed.compareAndSet(false, true)) {
22046                synchronized (mPackages) {
22047                    if (mWeFroze) {
22048                        mFrozenPackages.remove(mPackageName);
22049                    }
22050
22051                    if (mChildren != null) {
22052                        for (PackageFreezer freezer : mChildren) {
22053                            freezer.close();
22054                        }
22055                    }
22056                }
22057            }
22058        }
22059    }
22060
22061    /**
22062     * Verify that given package is currently frozen.
22063     */
22064    private void checkPackageFrozen(String packageName) {
22065        synchronized (mPackages) {
22066            if (!mFrozenPackages.contains(packageName)) {
22067                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22068            }
22069        }
22070    }
22071
22072    @Override
22073    public int movePackage(final String packageName, final String volumeUuid) {
22074        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22075
22076        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22077        final int moveId = mNextMoveId.getAndIncrement();
22078        mHandler.post(new Runnable() {
22079            @Override
22080            public void run() {
22081                try {
22082                    movePackageInternal(packageName, volumeUuid, moveId, user);
22083                } catch (PackageManagerException e) {
22084                    Slog.w(TAG, "Failed to move " + packageName, e);
22085                    mMoveCallbacks.notifyStatusChanged(moveId,
22086                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22087                }
22088            }
22089        });
22090        return moveId;
22091    }
22092
22093    private void movePackageInternal(final String packageName, final String volumeUuid,
22094            final int moveId, UserHandle user) throws PackageManagerException {
22095        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22096        final PackageManager pm = mContext.getPackageManager();
22097
22098        final boolean currentAsec;
22099        final String currentVolumeUuid;
22100        final File codeFile;
22101        final String installerPackageName;
22102        final String packageAbiOverride;
22103        final int appId;
22104        final String seinfo;
22105        final String label;
22106        final int targetSdkVersion;
22107        final PackageFreezer freezer;
22108        final int[] installedUserIds;
22109
22110        // reader
22111        synchronized (mPackages) {
22112            final PackageParser.Package pkg = mPackages.get(packageName);
22113            final PackageSetting ps = mSettings.mPackages.get(packageName);
22114            if (pkg == null || ps == null) {
22115                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22116            }
22117
22118            if (pkg.applicationInfo.isSystemApp()) {
22119                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22120                        "Cannot move system application");
22121            }
22122
22123            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22124            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22125                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22126            if (isInternalStorage && !allow3rdPartyOnInternal) {
22127                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22128                        "3rd party apps are not allowed on internal storage");
22129            }
22130
22131            if (pkg.applicationInfo.isExternalAsec()) {
22132                currentAsec = true;
22133                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22134            } else if (pkg.applicationInfo.isForwardLocked()) {
22135                currentAsec = true;
22136                currentVolumeUuid = "forward_locked";
22137            } else {
22138                currentAsec = false;
22139                currentVolumeUuid = ps.volumeUuid;
22140
22141                final File probe = new File(pkg.codePath);
22142                final File probeOat = new File(probe, "oat");
22143                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22144                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22145                            "Move only supported for modern cluster style installs");
22146                }
22147            }
22148
22149            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22150                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22151                        "Package already moved to " + volumeUuid);
22152            }
22153            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22154                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22155                        "Device admin cannot be moved");
22156            }
22157
22158            if (mFrozenPackages.contains(packageName)) {
22159                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22160                        "Failed to move already frozen package");
22161            }
22162
22163            codeFile = new File(pkg.codePath);
22164            installerPackageName = ps.installerPackageName;
22165            packageAbiOverride = ps.cpuAbiOverrideString;
22166            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22167            seinfo = pkg.applicationInfo.seInfo;
22168            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22169            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22170            freezer = freezePackage(packageName, "movePackageInternal");
22171            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22172        }
22173
22174        final Bundle extras = new Bundle();
22175        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22176        extras.putString(Intent.EXTRA_TITLE, label);
22177        mMoveCallbacks.notifyCreated(moveId, extras);
22178
22179        int installFlags;
22180        final boolean moveCompleteApp;
22181        final File measurePath;
22182
22183        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22184            installFlags = INSTALL_INTERNAL;
22185            moveCompleteApp = !currentAsec;
22186            measurePath = Environment.getDataAppDirectory(volumeUuid);
22187        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22188            installFlags = INSTALL_EXTERNAL;
22189            moveCompleteApp = false;
22190            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22191        } else {
22192            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22193            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22194                    || !volume.isMountedWritable()) {
22195                freezer.close();
22196                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22197                        "Move location not mounted private volume");
22198            }
22199
22200            Preconditions.checkState(!currentAsec);
22201
22202            installFlags = INSTALL_INTERNAL;
22203            moveCompleteApp = true;
22204            measurePath = Environment.getDataAppDirectory(volumeUuid);
22205        }
22206
22207        final PackageStats stats = new PackageStats(null, -1);
22208        synchronized (mInstaller) {
22209            for (int userId : installedUserIds) {
22210                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22211                    freezer.close();
22212                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22213                            "Failed to measure package size");
22214                }
22215            }
22216        }
22217
22218        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22219                + stats.dataSize);
22220
22221        final long startFreeBytes = measurePath.getFreeSpace();
22222        final long sizeBytes;
22223        if (moveCompleteApp) {
22224            sizeBytes = stats.codeSize + stats.dataSize;
22225        } else {
22226            sizeBytes = stats.codeSize;
22227        }
22228
22229        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22230            freezer.close();
22231            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22232                    "Not enough free space to move");
22233        }
22234
22235        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22236
22237        final CountDownLatch installedLatch = new CountDownLatch(1);
22238        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22239            @Override
22240            public void onUserActionRequired(Intent intent) throws RemoteException {
22241                throw new IllegalStateException();
22242            }
22243
22244            @Override
22245            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22246                    Bundle extras) throws RemoteException {
22247                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22248                        + PackageManager.installStatusToString(returnCode, msg));
22249
22250                installedLatch.countDown();
22251                freezer.close();
22252
22253                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22254                switch (status) {
22255                    case PackageInstaller.STATUS_SUCCESS:
22256                        mMoveCallbacks.notifyStatusChanged(moveId,
22257                                PackageManager.MOVE_SUCCEEDED);
22258                        break;
22259                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22260                        mMoveCallbacks.notifyStatusChanged(moveId,
22261                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22262                        break;
22263                    default:
22264                        mMoveCallbacks.notifyStatusChanged(moveId,
22265                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22266                        break;
22267                }
22268            }
22269        };
22270
22271        final MoveInfo move;
22272        if (moveCompleteApp) {
22273            // Kick off a thread to report progress estimates
22274            new Thread() {
22275                @Override
22276                public void run() {
22277                    while (true) {
22278                        try {
22279                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22280                                break;
22281                            }
22282                        } catch (InterruptedException ignored) {
22283                        }
22284
22285                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22286                        final int progress = 10 + (int) MathUtils.constrain(
22287                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22288                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22289                    }
22290                }
22291            }.start();
22292
22293            final String dataAppName = codeFile.getName();
22294            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22295                    dataAppName, appId, seinfo, targetSdkVersion);
22296        } else {
22297            move = null;
22298        }
22299
22300        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22301
22302        final Message msg = mHandler.obtainMessage(INIT_COPY);
22303        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22304        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22305                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22306                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22307                PackageManager.INSTALL_REASON_UNKNOWN);
22308        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22309        msg.obj = params;
22310
22311        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22312                System.identityHashCode(msg.obj));
22313        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22314                System.identityHashCode(msg.obj));
22315
22316        mHandler.sendMessage(msg);
22317    }
22318
22319    @Override
22320    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22321        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22322
22323        final int realMoveId = mNextMoveId.getAndIncrement();
22324        final Bundle extras = new Bundle();
22325        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22326        mMoveCallbacks.notifyCreated(realMoveId, extras);
22327
22328        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22329            @Override
22330            public void onCreated(int moveId, Bundle extras) {
22331                // Ignored
22332            }
22333
22334            @Override
22335            public void onStatusChanged(int moveId, int status, long estMillis) {
22336                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22337            }
22338        };
22339
22340        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22341        storage.setPrimaryStorageUuid(volumeUuid, callback);
22342        return realMoveId;
22343    }
22344
22345    @Override
22346    public int getMoveStatus(int moveId) {
22347        mContext.enforceCallingOrSelfPermission(
22348                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22349        return mMoveCallbacks.mLastStatus.get(moveId);
22350    }
22351
22352    @Override
22353    public void registerMoveCallback(IPackageMoveObserver callback) {
22354        mContext.enforceCallingOrSelfPermission(
22355                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22356        mMoveCallbacks.register(callback);
22357    }
22358
22359    @Override
22360    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22361        mContext.enforceCallingOrSelfPermission(
22362                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22363        mMoveCallbacks.unregister(callback);
22364    }
22365
22366    @Override
22367    public boolean setInstallLocation(int loc) {
22368        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22369                null);
22370        if (getInstallLocation() == loc) {
22371            return true;
22372        }
22373        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22374                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22375            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22376                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22377            return true;
22378        }
22379        return false;
22380   }
22381
22382    @Override
22383    public int getInstallLocation() {
22384        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22385                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22386                PackageHelper.APP_INSTALL_AUTO);
22387    }
22388
22389    /** Called by UserManagerService */
22390    void cleanUpUser(UserManagerService userManager, int userHandle) {
22391        synchronized (mPackages) {
22392            mDirtyUsers.remove(userHandle);
22393            mUserNeedsBadging.delete(userHandle);
22394            mSettings.removeUserLPw(userHandle);
22395            mPendingBroadcasts.remove(userHandle);
22396            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22397            removeUnusedPackagesLPw(userManager, userHandle);
22398        }
22399    }
22400
22401    /**
22402     * We're removing userHandle and would like to remove any downloaded packages
22403     * that are no longer in use by any other user.
22404     * @param userHandle the user being removed
22405     */
22406    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22407        final boolean DEBUG_CLEAN_APKS = false;
22408        int [] users = userManager.getUserIds();
22409        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22410        while (psit.hasNext()) {
22411            PackageSetting ps = psit.next();
22412            if (ps.pkg == null) {
22413                continue;
22414            }
22415            final String packageName = ps.pkg.packageName;
22416            // Skip over if system app
22417            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22418                continue;
22419            }
22420            if (DEBUG_CLEAN_APKS) {
22421                Slog.i(TAG, "Checking package " + packageName);
22422            }
22423            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22424            if (keep) {
22425                if (DEBUG_CLEAN_APKS) {
22426                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22427                }
22428            } else {
22429                for (int i = 0; i < users.length; i++) {
22430                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22431                        keep = true;
22432                        if (DEBUG_CLEAN_APKS) {
22433                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22434                                    + users[i]);
22435                        }
22436                        break;
22437                    }
22438                }
22439            }
22440            if (!keep) {
22441                if (DEBUG_CLEAN_APKS) {
22442                    Slog.i(TAG, "  Removing package " + packageName);
22443                }
22444                mHandler.post(new Runnable() {
22445                    public void run() {
22446                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22447                                userHandle, 0);
22448                    } //end run
22449                });
22450            }
22451        }
22452    }
22453
22454    /** Called by UserManagerService */
22455    void createNewUser(int userId, String[] disallowedPackages) {
22456        synchronized (mInstallLock) {
22457            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22458        }
22459        synchronized (mPackages) {
22460            scheduleWritePackageRestrictionsLocked(userId);
22461            scheduleWritePackageListLocked(userId);
22462            applyFactoryDefaultBrowserLPw(userId);
22463            primeDomainVerificationsLPw(userId);
22464        }
22465    }
22466
22467    void onNewUserCreated(final int userId) {
22468        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22469        // If permission review for legacy apps is required, we represent
22470        // dagerous permissions for such apps as always granted runtime
22471        // permissions to keep per user flag state whether review is needed.
22472        // Hence, if a new user is added we have to propagate dangerous
22473        // permission grants for these legacy apps.
22474        if (mPermissionReviewRequired) {
22475            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22476                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22477        }
22478    }
22479
22480    @Override
22481    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22482        mContext.enforceCallingOrSelfPermission(
22483                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22484                "Only package verification agents can read the verifier device identity");
22485
22486        synchronized (mPackages) {
22487            return mSettings.getVerifierDeviceIdentityLPw();
22488        }
22489    }
22490
22491    @Override
22492    public void setPermissionEnforced(String permission, boolean enforced) {
22493        // TODO: Now that we no longer change GID for storage, this should to away.
22494        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22495                "setPermissionEnforced");
22496        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22497            synchronized (mPackages) {
22498                if (mSettings.mReadExternalStorageEnforced == null
22499                        || mSettings.mReadExternalStorageEnforced != enforced) {
22500                    mSettings.mReadExternalStorageEnforced = enforced;
22501                    mSettings.writeLPr();
22502                }
22503            }
22504            // kill any non-foreground processes so we restart them and
22505            // grant/revoke the GID.
22506            final IActivityManager am = ActivityManager.getService();
22507            if (am != null) {
22508                final long token = Binder.clearCallingIdentity();
22509                try {
22510                    am.killProcessesBelowForeground("setPermissionEnforcement");
22511                } catch (RemoteException e) {
22512                } finally {
22513                    Binder.restoreCallingIdentity(token);
22514                }
22515            }
22516        } else {
22517            throw new IllegalArgumentException("No selective enforcement for " + permission);
22518        }
22519    }
22520
22521    @Override
22522    @Deprecated
22523    public boolean isPermissionEnforced(String permission) {
22524        return true;
22525    }
22526
22527    @Override
22528    public boolean isStorageLow() {
22529        final long token = Binder.clearCallingIdentity();
22530        try {
22531            final DeviceStorageMonitorInternal
22532                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22533            if (dsm != null) {
22534                return dsm.isMemoryLow();
22535            } else {
22536                return false;
22537            }
22538        } finally {
22539            Binder.restoreCallingIdentity(token);
22540        }
22541    }
22542
22543    @Override
22544    public IPackageInstaller getPackageInstaller() {
22545        return mInstallerService;
22546    }
22547
22548    private boolean userNeedsBadging(int userId) {
22549        int index = mUserNeedsBadging.indexOfKey(userId);
22550        if (index < 0) {
22551            final UserInfo userInfo;
22552            final long token = Binder.clearCallingIdentity();
22553            try {
22554                userInfo = sUserManager.getUserInfo(userId);
22555            } finally {
22556                Binder.restoreCallingIdentity(token);
22557            }
22558            final boolean b;
22559            if (userInfo != null && userInfo.isManagedProfile()) {
22560                b = true;
22561            } else {
22562                b = false;
22563            }
22564            mUserNeedsBadging.put(userId, b);
22565            return b;
22566        }
22567        return mUserNeedsBadging.valueAt(index);
22568    }
22569
22570    @Override
22571    public KeySet getKeySetByAlias(String packageName, String alias) {
22572        if (packageName == null || alias == null) {
22573            return null;
22574        }
22575        synchronized(mPackages) {
22576            final PackageParser.Package pkg = mPackages.get(packageName);
22577            if (pkg == null) {
22578                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22579                throw new IllegalArgumentException("Unknown package: " + packageName);
22580            }
22581            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22582            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22583        }
22584    }
22585
22586    @Override
22587    public KeySet getSigningKeySet(String packageName) {
22588        if (packageName == null) {
22589            return null;
22590        }
22591        synchronized(mPackages) {
22592            final PackageParser.Package pkg = mPackages.get(packageName);
22593            if (pkg == null) {
22594                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22595                throw new IllegalArgumentException("Unknown package: " + packageName);
22596            }
22597            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22598                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22599                throw new SecurityException("May not access signing KeySet of other apps.");
22600            }
22601            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22602            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22603        }
22604    }
22605
22606    @Override
22607    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22608        if (packageName == null || ks == null) {
22609            return false;
22610        }
22611        synchronized(mPackages) {
22612            final PackageParser.Package pkg = mPackages.get(packageName);
22613            if (pkg == null) {
22614                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22615                throw new IllegalArgumentException("Unknown package: " + packageName);
22616            }
22617            IBinder ksh = ks.getToken();
22618            if (ksh instanceof KeySetHandle) {
22619                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22620                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22621            }
22622            return false;
22623        }
22624    }
22625
22626    @Override
22627    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22628        if (packageName == null || ks == null) {
22629            return false;
22630        }
22631        synchronized(mPackages) {
22632            final PackageParser.Package pkg = mPackages.get(packageName);
22633            if (pkg == null) {
22634                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22635                throw new IllegalArgumentException("Unknown package: " + packageName);
22636            }
22637            IBinder ksh = ks.getToken();
22638            if (ksh instanceof KeySetHandle) {
22639                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22640                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22641            }
22642            return false;
22643        }
22644    }
22645
22646    private void deletePackageIfUnusedLPr(final String packageName) {
22647        PackageSetting ps = mSettings.mPackages.get(packageName);
22648        if (ps == null) {
22649            return;
22650        }
22651        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22652            // TODO Implement atomic delete if package is unused
22653            // It is currently possible that the package will be deleted even if it is installed
22654            // after this method returns.
22655            mHandler.post(new Runnable() {
22656                public void run() {
22657                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22658                            0, PackageManager.DELETE_ALL_USERS);
22659                }
22660            });
22661        }
22662    }
22663
22664    /**
22665     * Check and throw if the given before/after packages would be considered a
22666     * downgrade.
22667     */
22668    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22669            throws PackageManagerException {
22670        if (after.versionCode < before.mVersionCode) {
22671            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22672                    "Update version code " + after.versionCode + " is older than current "
22673                    + before.mVersionCode);
22674        } else if (after.versionCode == before.mVersionCode) {
22675            if (after.baseRevisionCode < before.baseRevisionCode) {
22676                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22677                        "Update base revision code " + after.baseRevisionCode
22678                        + " is older than current " + before.baseRevisionCode);
22679            }
22680
22681            if (!ArrayUtils.isEmpty(after.splitNames)) {
22682                for (int i = 0; i < after.splitNames.length; i++) {
22683                    final String splitName = after.splitNames[i];
22684                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22685                    if (j != -1) {
22686                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22687                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22688                                    "Update split " + splitName + " revision code "
22689                                    + after.splitRevisionCodes[i] + " is older than current "
22690                                    + before.splitRevisionCodes[j]);
22691                        }
22692                    }
22693                }
22694            }
22695        }
22696    }
22697
22698    private static class MoveCallbacks extends Handler {
22699        private static final int MSG_CREATED = 1;
22700        private static final int MSG_STATUS_CHANGED = 2;
22701
22702        private final RemoteCallbackList<IPackageMoveObserver>
22703                mCallbacks = new RemoteCallbackList<>();
22704
22705        private final SparseIntArray mLastStatus = new SparseIntArray();
22706
22707        public MoveCallbacks(Looper looper) {
22708            super(looper);
22709        }
22710
22711        public void register(IPackageMoveObserver callback) {
22712            mCallbacks.register(callback);
22713        }
22714
22715        public void unregister(IPackageMoveObserver callback) {
22716            mCallbacks.unregister(callback);
22717        }
22718
22719        @Override
22720        public void handleMessage(Message msg) {
22721            final SomeArgs args = (SomeArgs) msg.obj;
22722            final int n = mCallbacks.beginBroadcast();
22723            for (int i = 0; i < n; i++) {
22724                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22725                try {
22726                    invokeCallback(callback, msg.what, args);
22727                } catch (RemoteException ignored) {
22728                }
22729            }
22730            mCallbacks.finishBroadcast();
22731            args.recycle();
22732        }
22733
22734        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22735                throws RemoteException {
22736            switch (what) {
22737                case MSG_CREATED: {
22738                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22739                    break;
22740                }
22741                case MSG_STATUS_CHANGED: {
22742                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22743                    break;
22744                }
22745            }
22746        }
22747
22748        private void notifyCreated(int moveId, Bundle extras) {
22749            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22750
22751            final SomeArgs args = SomeArgs.obtain();
22752            args.argi1 = moveId;
22753            args.arg2 = extras;
22754            obtainMessage(MSG_CREATED, args).sendToTarget();
22755        }
22756
22757        private void notifyStatusChanged(int moveId, int status) {
22758            notifyStatusChanged(moveId, status, -1);
22759        }
22760
22761        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22762            Slog.v(TAG, "Move " + moveId + " status " + status);
22763
22764            final SomeArgs args = SomeArgs.obtain();
22765            args.argi1 = moveId;
22766            args.argi2 = status;
22767            args.arg3 = estMillis;
22768            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22769
22770            synchronized (mLastStatus) {
22771                mLastStatus.put(moveId, status);
22772            }
22773        }
22774    }
22775
22776    private final static class OnPermissionChangeListeners extends Handler {
22777        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22778
22779        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22780                new RemoteCallbackList<>();
22781
22782        public OnPermissionChangeListeners(Looper looper) {
22783            super(looper);
22784        }
22785
22786        @Override
22787        public void handleMessage(Message msg) {
22788            switch (msg.what) {
22789                case MSG_ON_PERMISSIONS_CHANGED: {
22790                    final int uid = msg.arg1;
22791                    handleOnPermissionsChanged(uid);
22792                } break;
22793            }
22794        }
22795
22796        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22797            mPermissionListeners.register(listener);
22798
22799        }
22800
22801        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22802            mPermissionListeners.unregister(listener);
22803        }
22804
22805        public void onPermissionsChanged(int uid) {
22806            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22807                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22808            }
22809        }
22810
22811        private void handleOnPermissionsChanged(int uid) {
22812            final int count = mPermissionListeners.beginBroadcast();
22813            try {
22814                for (int i = 0; i < count; i++) {
22815                    IOnPermissionsChangeListener callback = mPermissionListeners
22816                            .getBroadcastItem(i);
22817                    try {
22818                        callback.onPermissionsChanged(uid);
22819                    } catch (RemoteException e) {
22820                        Log.e(TAG, "Permission listener is dead", e);
22821                    }
22822                }
22823            } finally {
22824                mPermissionListeners.finishBroadcast();
22825            }
22826        }
22827    }
22828
22829    private class PackageManagerInternalImpl extends PackageManagerInternal {
22830        @Override
22831        public void setLocationPackagesProvider(PackagesProvider provider) {
22832            synchronized (mPackages) {
22833                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22834            }
22835        }
22836
22837        @Override
22838        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22839            synchronized (mPackages) {
22840                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22841            }
22842        }
22843
22844        @Override
22845        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22846            synchronized (mPackages) {
22847                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22848            }
22849        }
22850
22851        @Override
22852        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22853            synchronized (mPackages) {
22854                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22855            }
22856        }
22857
22858        @Override
22859        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22860            synchronized (mPackages) {
22861                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22862            }
22863        }
22864
22865        @Override
22866        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22867            synchronized (mPackages) {
22868                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22869            }
22870        }
22871
22872        @Override
22873        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22874            synchronized (mPackages) {
22875                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22876                        packageName, userId);
22877            }
22878        }
22879
22880        @Override
22881        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22882            synchronized (mPackages) {
22883                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22884                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22885                        packageName, userId);
22886            }
22887        }
22888
22889        @Override
22890        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22891            synchronized (mPackages) {
22892                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22893                        packageName, userId);
22894            }
22895        }
22896
22897        @Override
22898        public void setKeepUninstalledPackages(final List<String> packageList) {
22899            Preconditions.checkNotNull(packageList);
22900            List<String> removedFromList = null;
22901            synchronized (mPackages) {
22902                if (mKeepUninstalledPackages != null) {
22903                    final int packagesCount = mKeepUninstalledPackages.size();
22904                    for (int i = 0; i < packagesCount; i++) {
22905                        String oldPackage = mKeepUninstalledPackages.get(i);
22906                        if (packageList != null && packageList.contains(oldPackage)) {
22907                            continue;
22908                        }
22909                        if (removedFromList == null) {
22910                            removedFromList = new ArrayList<>();
22911                        }
22912                        removedFromList.add(oldPackage);
22913                    }
22914                }
22915                mKeepUninstalledPackages = new ArrayList<>(packageList);
22916                if (removedFromList != null) {
22917                    final int removedCount = removedFromList.size();
22918                    for (int i = 0; i < removedCount; i++) {
22919                        deletePackageIfUnusedLPr(removedFromList.get(i));
22920                    }
22921                }
22922            }
22923        }
22924
22925        @Override
22926        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22927            synchronized (mPackages) {
22928                // If we do not support permission review, done.
22929                if (!mPermissionReviewRequired) {
22930                    return false;
22931                }
22932
22933                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22934                if (packageSetting == null) {
22935                    return false;
22936                }
22937
22938                // Permission review applies only to apps not supporting the new permission model.
22939                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22940                    return false;
22941                }
22942
22943                // Legacy apps have the permission and get user consent on launch.
22944                PermissionsState permissionsState = packageSetting.getPermissionsState();
22945                return permissionsState.isPermissionReviewRequired(userId);
22946            }
22947        }
22948
22949        @Override
22950        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22951            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22952        }
22953
22954        @Override
22955        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22956                int userId) {
22957            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22958        }
22959
22960        @Override
22961        public void setDeviceAndProfileOwnerPackages(
22962                int deviceOwnerUserId, String deviceOwnerPackage,
22963                SparseArray<String> profileOwnerPackages) {
22964            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22965                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22966        }
22967
22968        @Override
22969        public boolean isPackageDataProtected(int userId, String packageName) {
22970            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22971        }
22972
22973        @Override
22974        public boolean isPackageEphemeral(int userId, String packageName) {
22975            synchronized (mPackages) {
22976                final PackageSetting ps = mSettings.mPackages.get(packageName);
22977                return ps != null ? ps.getInstantApp(userId) : false;
22978            }
22979        }
22980
22981        @Override
22982        public boolean wasPackageEverLaunched(String packageName, int userId) {
22983            synchronized (mPackages) {
22984                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22985            }
22986        }
22987
22988        @Override
22989        public void grantRuntimePermission(String packageName, String name, int userId,
22990                boolean overridePolicy) {
22991            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22992                    overridePolicy);
22993        }
22994
22995        @Override
22996        public void revokeRuntimePermission(String packageName, String name, int userId,
22997                boolean overridePolicy) {
22998            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22999                    overridePolicy);
23000        }
23001
23002        @Override
23003        public String getNameForUid(int uid) {
23004            return PackageManagerService.this.getNameForUid(uid);
23005        }
23006
23007        @Override
23008        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23009                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23010            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23011                    responseObj, origIntent, resolvedType, callingPackage, userId);
23012        }
23013
23014        @Override
23015        public void grantEphemeralAccess(int userId, Intent intent,
23016                int targetAppId, int ephemeralAppId) {
23017            synchronized (mPackages) {
23018                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23019                        targetAppId, ephemeralAppId);
23020            }
23021        }
23022
23023        @Override
23024        public void pruneInstantApps() {
23025            synchronized (mPackages) {
23026                mInstantAppRegistry.pruneInstantAppsLPw();
23027            }
23028        }
23029
23030        @Override
23031        public String getSetupWizardPackageName() {
23032            return mSetupWizardPackage;
23033        }
23034
23035        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23036            if (policy != null) {
23037                mExternalSourcesPolicy = policy;
23038            }
23039        }
23040
23041        @Override
23042        public boolean isPackagePersistent(String packageName) {
23043            synchronized (mPackages) {
23044                PackageParser.Package pkg = mPackages.get(packageName);
23045                return pkg != null
23046                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23047                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23048                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23049                        : false;
23050            }
23051        }
23052
23053        @Override
23054        public List<PackageInfo> getOverlayPackages(int userId) {
23055            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23056            synchronized (mPackages) {
23057                for (PackageParser.Package p : mPackages.values()) {
23058                    if (p.mOverlayTarget != null) {
23059                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23060                        if (pkg != null) {
23061                            overlayPackages.add(pkg);
23062                        }
23063                    }
23064                }
23065            }
23066            return overlayPackages;
23067        }
23068
23069        @Override
23070        public List<String> getTargetPackageNames(int userId) {
23071            List<String> targetPackages = new ArrayList<>();
23072            synchronized (mPackages) {
23073                for (PackageParser.Package p : mPackages.values()) {
23074                    if (p.mOverlayTarget == null) {
23075                        targetPackages.add(p.packageName);
23076                    }
23077                }
23078            }
23079            return targetPackages;
23080        }
23081
23082        @Override
23083        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23084                @Nullable List<String> overlayPackageNames) {
23085            synchronized (mPackages) {
23086                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23087                    Slog.e(TAG, "failed to find package " + targetPackageName);
23088                    return false;
23089                }
23090
23091                ArrayList<String> paths = null;
23092                if (overlayPackageNames != null) {
23093                    final int N = overlayPackageNames.size();
23094                    paths = new ArrayList<>(N);
23095                    for (int i = 0; i < N; i++) {
23096                        final String packageName = overlayPackageNames.get(i);
23097                        final PackageParser.Package pkg = mPackages.get(packageName);
23098                        if (pkg == null) {
23099                            Slog.e(TAG, "failed to find package " + packageName);
23100                            return false;
23101                        }
23102                        paths.add(pkg.baseCodePath);
23103                    }
23104                }
23105
23106                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23107                    mEnabledOverlayPaths.get(userId);
23108                if (userSpecificOverlays == null) {
23109                    userSpecificOverlays = new ArrayMap<>();
23110                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23111                }
23112
23113                if (paths != null && paths.size() > 0) {
23114                    userSpecificOverlays.put(targetPackageName, paths);
23115                } else {
23116                    userSpecificOverlays.remove(targetPackageName);
23117                }
23118                return true;
23119            }
23120        }
23121
23122        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23123                int flags, int userId) {
23124            return resolveIntentInternal(
23125                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23126        }
23127    }
23128
23129    @Override
23130    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23131        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23132        synchronized (mPackages) {
23133            final long identity = Binder.clearCallingIdentity();
23134            try {
23135                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23136                        packageNames, userId);
23137            } finally {
23138                Binder.restoreCallingIdentity(identity);
23139            }
23140        }
23141    }
23142
23143    @Override
23144    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23145        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23146        synchronized (mPackages) {
23147            final long identity = Binder.clearCallingIdentity();
23148            try {
23149                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23150                        packageNames, userId);
23151            } finally {
23152                Binder.restoreCallingIdentity(identity);
23153            }
23154        }
23155    }
23156
23157    private static void enforceSystemOrPhoneCaller(String tag) {
23158        int callingUid = Binder.getCallingUid();
23159        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23160            throw new SecurityException(
23161                    "Cannot call " + tag + " from UID " + callingUid);
23162        }
23163    }
23164
23165    boolean isHistoricalPackageUsageAvailable() {
23166        return mPackageUsage.isHistoricalPackageUsageAvailable();
23167    }
23168
23169    /**
23170     * Return a <b>copy</b> of the collection of packages known to the package manager.
23171     * @return A copy of the values of mPackages.
23172     */
23173    Collection<PackageParser.Package> getPackages() {
23174        synchronized (mPackages) {
23175            return new ArrayList<>(mPackages.values());
23176        }
23177    }
23178
23179    /**
23180     * Logs process start information (including base APK hash) to the security log.
23181     * @hide
23182     */
23183    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23184            String apkFile, int pid) {
23185        if (!SecurityLog.isLoggingEnabled()) {
23186            return;
23187        }
23188        Bundle data = new Bundle();
23189        data.putLong("startTimestamp", System.currentTimeMillis());
23190        data.putString("processName", processName);
23191        data.putInt("uid", uid);
23192        data.putString("seinfo", seinfo);
23193        data.putString("apkFile", apkFile);
23194        data.putInt("pid", pid);
23195        Message msg = mProcessLoggingHandler.obtainMessage(
23196                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23197        msg.setData(data);
23198        mProcessLoggingHandler.sendMessage(msg);
23199    }
23200
23201    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23202        return mCompilerStats.getPackageStats(pkgName);
23203    }
23204
23205    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23206        return getOrCreateCompilerPackageStats(pkg.packageName);
23207    }
23208
23209    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23210        return mCompilerStats.getOrCreatePackageStats(pkgName);
23211    }
23212
23213    public void deleteCompilerPackageStats(String pkgName) {
23214        mCompilerStats.deletePackageStats(pkgName);
23215    }
23216
23217    @Override
23218    public int getInstallReason(String packageName, int userId) {
23219        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23220                true /* requireFullPermission */, false /* checkShell */,
23221                "get install reason");
23222        synchronized (mPackages) {
23223            final PackageSetting ps = mSettings.mPackages.get(packageName);
23224            if (ps != null) {
23225                return ps.getInstallReason(userId);
23226            }
23227        }
23228        return PackageManager.INSTALL_REASON_UNKNOWN;
23229    }
23230
23231    @Override
23232    public boolean canRequestPackageInstalls(String packageName, int userId) {
23233        int callingUid = Binder.getCallingUid();
23234        int uid = getPackageUid(packageName, 0, userId);
23235        if (callingUid != uid && callingUid != Process.ROOT_UID
23236                && callingUid != Process.SYSTEM_UID) {
23237            throw new SecurityException(
23238                    "Caller uid " + callingUid + " does not own package " + packageName);
23239        }
23240        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23241        if (info == null) {
23242            return false;
23243        }
23244        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23245            throw new UnsupportedOperationException(
23246                    "Operation only supported on apps targeting Android O or higher");
23247        }
23248        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23249        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23250        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23251            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23252        }
23253        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23254            return false;
23255        }
23256        if (mExternalSourcesPolicy != null) {
23257            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23258            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23259                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23260            }
23261        }
23262        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23263    }
23264}
23265